From 5b7cbf7af0d375d660f56e2e9f7467f4509fd1f1 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Mon, 14 Jun 2021 00:41:25 +0300 Subject: [PATCH] [Build] --- ...2528f8941f699.worker.js => 24a861ad9dabd3acfe82.worker.js} | 2 +- ...1f699.worker.js.map => 24a861ad9dabd3acfe82.worker.js.map} | 2 +- dist/3d0807b05cc1ab7d3c59.worker.js | 3 +++ ...LICENSE.txt => 3d0807b05cc1ab7d3c59.worker.js.LICENSE.txt} | 0 dist/3d0807b05cc1ab7d3c59.worker.js.map | 1 + dist/6b9e1c477ee38548ce72.worker.js | 3 --- dist/6b9e1c477ee38548ce72.worker.js.map | 1 - dist/{7.3c4397f983ad7c01b144.js => 7.4122a010f2ae7876c212.js} | 4 ++-- ...397f983ad7c01b144.js.map => 7.4122a010f2ae7876c212.js.map} | 2 +- dist/index.html | 2 +- ...n.a578e966316fd5919f1a.js => main.a06c93992fe858fca979.js} | 4 ++-- ...66316fd5919f1a.js.map => main.a06c93992fe858fca979.js.map} | 2 +- dist/report.html | 4 ++-- 13 files changed, 15 insertions(+), 15 deletions(-) rename dist/{056df1c2528f8941f699.worker.js => 24a861ad9dabd3acfe82.worker.js} (98%) rename dist/{056df1c2528f8941f699.worker.js.map => 24a861ad9dabd3acfe82.worker.js.map} (99%) create mode 100644 dist/3d0807b05cc1ab7d3c59.worker.js rename dist/{6b9e1c477ee38548ce72.worker.js.LICENSE.txt => 3d0807b05cc1ab7d3c59.worker.js.LICENSE.txt} (100%) create mode 100644 dist/3d0807b05cc1ab7d3c59.worker.js.map delete mode 100644 dist/6b9e1c477ee38548ce72.worker.js delete mode 100644 dist/6b9e1c477ee38548ce72.worker.js.map rename dist/{7.3c4397f983ad7c01b144.js => 7.4122a010f2ae7876c212.js} (98%) rename dist/{7.3c4397f983ad7c01b144.js.map => 7.4122a010f2ae7876c212.js.map} (99%) rename dist/{main.a578e966316fd5919f1a.js => main.a06c93992fe858fca979.js} (99%) rename dist/{main.a578e966316fd5919f1a.js.map => main.a06c93992fe858fca979.js.map} (99%) diff --git a/dist/056df1c2528f8941f699.worker.js b/dist/24a861ad9dabd3acfe82.worker.js similarity index 98% rename from dist/056df1c2528f8941f699.worker.js rename to dist/24a861ad9dabd3acfe82.worker.js index 29b03cd9..8f3071a5 100644 --- a/dist/056df1c2528f8941f699.worker.js +++ b/dist/24a861ad9dabd3acfe82.worker.js @@ -1,2 +1,2 @@ !function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";t.r(r);new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight;self.onerror=e=>{console.error(e),o({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),o({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const n=new Map;function o(e,r){r?postMessage(e,r):postMessage(e)}let s;self.importScripts("rlottie-wasm.js");const a=new Promise(e=>{Module.onRuntimeInitialized=()=>{s={init:Module.cwrap("lottie_init","",[]),destroy:Module.cwrap("lottie_destroy","",["number"]),resize:Module.cwrap("lottie_resize","",["number","number","number"]),buffer:Module.cwrap("lottie_buffer","number",["number"]),render:Module.cwrap("lottie_render","",["number","number"]),loadFromData:Module.cwrap("lottie_load_from_data","number",["number","number"])},e()}}),i=new Map;var c;c={init:async function(e,r,t,n,o,c){s||await a;const u=JSON.stringify(r),d=allocate(intArrayFromString(u),"i8",0),l=s.init(),f=s.loadFromData(l,d);s.resize(l,t,t),i.set(e,{imgSize:t,reduceFactor:o,handle:l}),c(Math.ceil(f/o))},renderFrames:async function(e,r,t,n){s||await a;const{imgSize:o,reduceFactor:c,handle:u}=i.get(e);for(let e=r;e<=t;e++){const r=e*c;s.render(u,r);const t=s.buffer(u),a=Module.HEAPU8.subarray(t,t+o*o*4);n(e,new Uint8ClampedArray(a).buffer)}},destroy:function(e){const r=i.get(e);s.destroy(r.handle),i.delete(e)}},onmessage=async e=>{const{data:r}=e;switch(r.type){case"callMethod":{const{messageId:e,name:t,args:s}=r;try{if(e){const r=(...r)=>{const t=r[r.length-1];o({type:"methodCallback",messageId:e,callbackArgs:r},t instanceof ArrayBuffer?[t]:void 0)};n.set(e,r),s.push(r)}const[r,a]=await c[t](...s)||[];e&&o({type:"methodResponse",messageId:e,response:r},a)}catch(r){e&&o({type:"methodResponse",messageId:e,error:{message:r.message}})}e&&n.delete(e);break}case"cancelProgress":{const e=n.get(r.messageId);e&&(e.isCanceled=!0);break}}}}]); -//# sourceMappingURL=056df1c2528f8941f699.worker.js.map \ No newline at end of file +//# sourceMappingURL=24a861ad9dabd3acfe82.worker.js.map \ No newline at end of file diff --git a/dist/056df1c2528f8941f699.worker.js.map b/dist/24a861ad9dabd3acfe82.worker.js.map similarity index 99% rename from dist/056df1c2528f8941f699.worker.js.map rename to dist/24a861ad9dabd3acfe82.worker.js.map index 328c112c..1429887e 100644 --- a/dist/056df1c2528f8941f699.worker.js.map +++ b/dist/24a861ad9dabd3acfe82.worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/config.ts","webpack:///./src/util/createWorkerInterface.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Set","window","innerHeight","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","Math","ceil","renderFrames","fromIndex","toIndex","onProgress","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAA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,EAAUA,EAAU,GAExFkB,EAAWtF,EADS,IAAI2F,kBAAkB5C,GAAMc,UAgBlDF,QAXF,SAAiBpC,GACf,MAAMqE,EAAW5B,EAAUnD,IAAIU,GAE/B2B,EAAWS,QAAQiC,EAASd,QAE5Bd,EAAU6B,OAAOtE,KDzEjBuE,UAAY5B,UACV,MAAM,KAAEnB,GAASL,EAEjB,OAAQK,EAAKN,MACX,IAAK,aAAc,CACjB,MAAM,UAAEsD,EAAF,KAAaxF,EAAb,KAAmByF,GAASjD,EAClC,IACE,GAAIgD,EAAW,CACb,MAAME,EAAW,IAAIC,KACnB,MAAMC,EAAUD,EAAaA,EAAaE,OAAS,GAEnD5D,EAAa,CACXC,KAAM,iBACNsD,YACAG,gBACCC,aAAmBE,YAAc,CAACF,QAAWG,IAGlDzD,EAAcmC,IAAIe,EAAWE,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAUxD,SAAuBiB,EAAI1D,MAASyF,IAAU,GAE3DD,GACFvD,EACE,CACEC,KAAM,iBACNsD,YACAS,YAEFxD,GAGJ,MAAOT,GAMHwD,GACFvD,EAAa,CACXC,KAAM,iBACNsD,YACAxD,MAAO,CAAEG,QAASH,EAAMG,WAK1BqD,GACFlD,EAAcgD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAME,EAAWpD,EAAchC,IAAIkC,EAAKgD,WACpCE,IACFA,EAASQ,YAAa,GAGxB","file":"056df1c2528f8941f699.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? [lastArg] : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const [response, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\n }\n };\n}\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/config.ts","webpack:///./src/util/createWorkerInterface.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Set","window","innerHeight","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","Math","ceil","renderFrames","fromIndex","toIndex","onProgress","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,KAQvDrB,EAAoBsB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQrB,EAAoBqB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFA1B,EAAoBkB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOrB,EAAoBU,EAAEe,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,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GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAUxD,SAAuBiB,EAAI1D,MAASyF,IAAU,GAE3DD,GACFvD,EACE,CACEC,KAAM,iBACNsD,YACAS,YAEFxD,GAGJ,MAAOT,GAMHwD,GACFvD,EAAa,CACXC,KAAM,iBACNsD,YACAxD,MAAO,CAAEG,QAASH,EAAMG,WAK1BqD,GACFlD,EAAcgD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAME,EAAWpD,EAAchC,IAAIkC,EAAKgD,WACpCE,IACFA,EAASQ,YAAa,GAGxB","file":"24a861ad9dabd3acfe82.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? [lastArg] : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const [response, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\n }\n };\n}\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/3d0807b05cc1ab7d3c59.worker.js b/dist/3d0807b05cc1ab7d3c59.worker.js new file mode 100644 index 00000000..653291e4 --- /dev/null +++ b/dist/3d0807b05cc1ab7d3c59.worker.js @@ -0,0 +1,3 @@ +/*! For license information please see 3d0807b05cc1ab7d3c59.worker.js.LICENSE.txt */ +!function(e){var t={};function n(s){if(t[s])return t[s].exports;var i=t[s]={i:s,l:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(s,i,function(t){return e[t]}.bind(null,i));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=111)}([function(e,t,n){const s=n(6),i=n(81),a=n(59),r=n(21),o=n(99),c=n(100),u=n(20),d=n(29),l=n(104),f=n(42),p=n(8);e.exports={Api:s,TelegramClient:i,sessions:l,connection:a,extensions:f,tl:r,version:o,events:c,utils:u,errors:d,helpers:p}},function(e,t,n){"use strict";n.d(t,"f",(function(){return M})),n.d(t,"a",(function(){return k})),n.d(t,"b",(function(){return E})),n.d(t,"e",(function(){return R})),n.d(t,"g",(function(){return T})),n.d(t,"c",(function(){return D})),n.d(t,"i",(function(){return B})),n.d(t,"h",(function(){return x})),n.d(t,"d",(function(){return j}));var s={};n.r(s),n.d(s,"Type",(function(){return m})),n.d(s,"fetch",(function(){return y})),n.d(s,"save",(function(){return b})),n.d(s,"clear",(function(){return _}));var i=n(0),a=n(42),r=n(4),o=n(17),c=n(26),u=n(9),d=n(41),l=n(11),f=n(5),p=n(2),g=n(34);const h=self.caches;let m;async function y(e,t,n){if(h)try{const s=new Request(t),i=await h.open(e),a=await i.match(s);if(!a)return;switch(n){case m.Text:return await a.text();case m.Blob:{const e=await a.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=a.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case m.Json:return await a.json();default:return}}catch(e){return void console.warn(e)}}async function b(e,t,n){if(h)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),i=new Request(t),a=new Response(s),r=await h.open(e);return await r.put(i,a)}catch(e){return void console.warn(e)}}async function _(e){try{if(!h)return;return await h.delete(e)}catch(e){return void console.warn(e)}}async function w({url:e,mediaFormat:t,start:n,end:a},o,c,u){const{data:h,mimeType:m,fullSize:y}=await async function(e,t,n,s,a,o,c){const u=e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!u)return;if("file"===u[1]){const e=await fetch(u[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d,g=u[2];const h=u[3]?u[3].replace("?size=",""):void 0;let m;"avatar"===u[1]||"profile"===u[1]?(d=Object(p.s)(Number(g)),g=Math.abs(Number(g))):d=u[1];switch(d){case"channel":case"chat":m=f.a.chats[g];break;case"user":m=f.a.users[g];break;case"msg":m=f.a.messages[g];break;case"sticker":case"gif":case"wallpaper":m=f.a.documents[g];break;case"photo":m=f.a.photos[g];break;case"stickerSet":m=f.a.stickerSets[g]}if(!m)return;if(["msg","sticker","gif","wallpaper","photo"].includes(d)){c===l.ApiMediaFormat.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(m,{sizeType:h,start:a,end:o,progressCallback:s,workers:r.k});let n,u;return m instanceof i.Api.Message?(n=function(e,t){if(!e||!e.media)return;if(e.media instanceof i.Api.MessageMediaPhoto)return"image/jpeg";if(e.media instanceof i.Api.MessageMediaDocument&&e.media.document instanceof i.Api.Document)return t?e.media.document.attributes.some(e=>e instanceof i.Api.DocumentAttributeSticker)?"image/webp":"image/jpeg":e.media.document.mimeType;return}(m,h),m.media instanceof i.Api.MessageMediaDocument&&m.media.document instanceof i.Api.Document&&(u=m.media.document.size)):m instanceof i.Api.Photo?n="image/jpeg":"sticker"===d&&h?n="image/webp":(n=m.mimeType,u=m.size),{mimeType:n,data:e,fullSize:u}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(m);return{mimeType:c===l.ApiMediaFormat.Lottie?"application/json":v(e),data:e}}{const e=await t.downloadProfilePhoto(m,"profile"===u[1]);return{mimeType:v(e),data:e}}}(e,o,c,u,n,a,t)||{};if(!h)return;const _=await async function(e,t,n){switch(t){case l.ApiMediaFormat.DataUri:return Object(g.a)(new Blob([e],{type:n}));case l.ApiMediaFormat.BlobUrl:return new Blob([e],{type:n});case l.ApiMediaFormat.Lottie:{const t=Object(d.inflate)(e,{to:"string"});return JSON.parse(t)}case l.ApiMediaFormat.Progressive:return e.buffer}return}(h,t,m);if(!_)return;const w=t!==l.ApiMediaFormat.Progressive&&(t!==l.ApiMediaFormat.BlobUrl||_.size<=r.o);if(!r.n&&s&&w){b(e.startsWith("avatar")?r.q:r.p,e,_)}return{prepared:t===l.ApiMediaFormat.Progressive?"":function(e){if(e instanceof Blob)return URL.createObjectURL(e);return e}(_),arrayBuffer:t===l.ApiMediaFormat.Progressive?_:void 0,mimeType:m,fullSize:y}}function v(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce((e,t)=>e+t.toString(16),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(m||(m={}));var A=n(13);a.Logger.setLevel(r.h?"debug":"warn");const I={build:e=>e};let P,C,S=!1;async function M(e,t){P=e,r.g&&console.log(">>> START INIT API"),C=new i.TelegramClient(new i.sessions.CallbackSession(t,U),"739222","60d1e1063c72d4bc4cfdda99e8906f94",{deviceModel:navigator.userAgent||"Unknown UserAgent",appVersion:r.d+" Z",useWSS:!0,additionalDcsDisabled:r.l}),C.addEventHandler(O,I),C.addEventHandler(c.b,I);try{r.g&&console.log("[GramJs/client] CONNECTING"),await C.start({phoneNumber:o.g,phoneCode:o.e,password:o.f,firstAndLastNames:o.i,qrCode:o.h,onError:o.b}),r.g&&(console.log(">>> FINISH INIT API"),console.log("[GramJs/client] CONNECTED")),Object(o.c)(),P({"@type":"updateApiReady"}),j()}catch(e){throw r.g&&console.log("[GramJs/client] CONNECTING ERROR",e),e}}async function k(){await T(new i.Api.auth.LogOut),await C.destroy()}async function E(){await C.disconnect()}function R(){return C}function U(e){P({"@type":"updateSession",sessionData:e})}function O(e){e instanceof i.connection.UpdateConnectionState?S=e.state===i.connection.UpdateConnectionState.connected:e instanceof i.Api.UpdatesTooLong&&async function(){try{await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&P({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}()}async function T(e,t=!1,n=!1){if(S)try{r.g&&console.log("[GramJs/client] INVOKE "+e.className);const n=await C.invoke(e);if(r.g&&console.log("[GramJs/client] INVOKE RESPONSE "+e.className,n),t){let t;n instanceof i.Api.Updates||n instanceof i.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof i.Api.Updates||n.updates instanceof i.Api.UpdatesCombined)&&(t=n.updates),t?(!function(e){const t=[...e.users,...e.chats];e.updates.forEach(e=>{t&&(e._entities=t)})}(t),t.updates.forEach(t=>{Object(c.b)(t,e)})):n instanceof i.Api.UpdatesTooLong||Object(c.b)(n,e)}return n}catch(t){if(r.g&&(console.log("[GramJs/client] INVOKE ERROR "+e.className),console.error(t)),function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof i.Api.messages.SendMessage||t instanceof i.Api.messages.SendMedia||t instanceof i.Api.messages.SendMultiMedia),{message:s}=e;P({"@type":"error",error:{message:s,isSlowMode:n}})}(t,e),n)throw t;return}else r.g&&console.warn(`[GramJs/client] INVOKE ERROR ${e.className}: Client is not connected`)}function D(e,t){return w(e,C,S,t)}function B(e,t){return C.uploadFile({file:e,onProgress:t,workers:r.w})}function x(e){return C.updateTwoFaSettings(e)}async function j(){const e=await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}));if(!(e&&e.user instanceof i.Api.User))return;f.a.users[e.user.id]=e.user;const t=Object(A.b)(e);Object(u.o)(t.id),Object(o.d)(t)}},function(e,t,n){"use strict";(function(e){n.d(t,"s",(function(){return d})),n.d(t,"o",(function(){return l})),n.d(t,"i",(function(){return f})),n.d(t,"g",(function(){return g})),n.d(t,"l",(function(){return h})),n.d(t,"f",(function(){return m})),n.d(t,"h",(function(){return y})),n.d(t,"j",(function(){return b})),n.d(t,"d",(function(){return _})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return v})),n.d(t,"n",(function(){return A})),n.d(t,"q",(function(){return I})),n.d(t,"t",(function(){return P})),n.d(t,"u",(function(){return C})),n.d(t,"c",(function(){return S})),n.d(t,"e",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"a",(function(){return E})),n.d(t,"p",(function(){return R})),n.d(t,"k",(function(){return U}));var s=n(15),i=n.n(s),a=n(0),r=n(8),o=n(11),c=n(5),u=n(14);function d(e){return e>0?"user":e<=-1e9?"channel":"chat"}function l(e){return e>0?new a.Api.PeerUser({userId:e}):e<=-1e9?new a.Api.PeerChannel({channelId:-e}):new a.Api.PeerChat({chatId:-e})}function f(e,t){return e>0||e<=-1e9?e>0?new a.Api.InputPeerUser({userId:e,accessHash:i()(t)}):new a.Api.InputPeerChannel({channelId:-e,accessHash:i()(t)}):new a.Api.InputPeerChat({chatId:-e})}function p(e){if(e>0){const{accessHash:t}=c.a.users[e]||{};return t?new a.Api.InputPeerUser({userId:e,accessHash:t}):void 0}if(e<=-1e9){const{accessHash:t}=c.a.chats[-e]||{};return t?new a.Api.InputPeerChannel({channelId:-e,accessHash:t}):void 0}return new a.Api.InputPeerChat({chatId:-e})}function g(e,t){return e>0?new a.Api.InputUser({userId:e,accessHash:i()(t)}):e<=-1e9?new a.Api.InputChannel({channelId:-e,accessHash:i()(t)}):-e}function h(e,t){return new a.Api.InputStickerSetID({id:i()(e),accessHash:i()(t)})}function m(e){const t=c.a.documents[e.id];if(t)return new a.Api.InputDocument(Object(u.b)(t,["id","accessHash","fileReference"]))}function y(e){const t=m(e);if(t)return new a.Api.InputMediaDocument({id:t})}function b(t,n){const{summary:s,quiz:i}=t,r=new a.Api.Poll({id:n,publicVoters:s.isPublic,question:s.question,answers:s.answers.map(({text:t,option:n})=>new a.Api.PollAnswer({text:t,option:e.from(n)})),quiz:s.quiz,multipleChoice:s.multipleChoice});if(!i)return new a.Api.InputMediaPoll({poll:r});const o=i.correctAnswers.map(t=>e.from(t)),{solution:c}=i,u=i.solutionEntities?i.solutionEntities.map(A):[];return new a.Api.InputMediaPoll({poll:r,correctAnswers:o,...c&&{solution:c,solutionEntities:u}})}function _(e){const{emoticon:t,contacts:n,nonContacts:s,groups:i,channels:r,bots:o,excludeArchived:c,excludeMuted:u,excludeRead:d,pinnedChatIds:l,includedChatIds:f,excludedChatIds:g}=e,h=l?l.map(p).filter(Boolean):[],m=f?f.map(p).filter(Boolean):[],y=g?g.map(p).filter(Boolean):[];return new a.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:i||void 0,bots:o||void 0,excludeArchived:c||void 0,excludeMuted:u||void 0,excludeRead:d||void 0,broadcasts:r||void 0,pinnedPeers:h,includePeers:m,excludePeers:y})}function w(){return Object(r.readBigIntFromBuffer)(Object(r.generateRandomBytes)(8),!0,!0)}function v(e,t,n){return new a.Api.Message({id:e,peerId:l(t),fromId:l(t),media:n.media})}function A(e){const{type:t,offset:n,length:s,url:i,userId:r}=e,u=r?c.a.users[r]:void 0;switch(t){case o.ApiMessageEntityTypes.Bold:return new a.Api.MessageEntityBold({offset:n,length:s});case o.ApiMessageEntityTypes.Italic:return new a.Api.MessageEntityItalic({offset:n,length:s});case o.ApiMessageEntityTypes.Underline:return new a.Api.MessageEntityUnderline({offset:n,length:s});case o.ApiMessageEntityTypes.Strike:return new a.Api.MessageEntityStrike({offset:n,length:s});case o.ApiMessageEntityTypes.Code:return new a.Api.MessageEntityCode({offset:n,length:s});case o.ApiMessageEntityTypes.Pre:return new a.Api.MessageEntityPre({offset:n,length:s,language:""});case o.ApiMessageEntityTypes.Blockquote:return new a.Api.MessageEntityBlockquote({offset:n,length:s});case o.ApiMessageEntityTypes.TextUrl:return new a.Api.MessageEntityTextUrl({offset:n,length:s,url:i});case o.ApiMessageEntityTypes.Url:return new a.Api.MessageEntityUrl({offset:n,length:s});case o.ApiMessageEntityTypes.Hashtag:return new a.Api.MessageEntityHashtag({offset:n,length:s});case o.ApiMessageEntityTypes.MentionName:return new a.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new a.Api.InputUser({userId:r,accessHash:u.accessHash})});default:return new a.Api.MessageEntityUnknown({offset:n,length:s})}}function I(e){let t=0;return e.forEach(e=>{t=(20261*t&2147483647)+e&2147483647}),t}function P(e){const{media:t}=e;return!!t&&(t instanceof a.Api.MessageMediaPhoto||t instanceof a.Api.MessageMediaDocument||t instanceof a.Api.MessageMediaWebPage&&t.webpage instanceof a.Api.WebPage&&t.webpage.photo instanceof a.Api.Photo)}function C(e){return"photo"in e.action&&e.action.photo instanceof a.Api.Photo}function S(e){if(e instanceof a.Api.PhotoEmpty)return new a.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new a.Api.ChatPhoto({dcId:t,photoId:n})}function M({phone:e,firstName:t,lastName:n}){return new a.Api.InputPhoneContact({clientId:i()(1),phone:e,firstName:t,lastName:n})}function k(e,t=0){return new a.Api.ChatBannedRights({...e,untilDate:t})}function E(e){return new a.Api.ChatAdminRights(e)}function R(e){const{shippingAddress:t}=e;return new a.Api.PaymentRequestedInfo({...e,shippingAddress:t?new a.Api.PostAddress(t):void 0})}function U(e){switch(e){case"phoneNumber":return new a.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new a.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new a.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new a.Api.InputPrivacyKeyForwards;case"chatInvite":return new a.Api.InputPrivacyKeyChatInvite}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"k",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"f",(function(){return A})),n.d(t,"g",(function(){return I})),n.d(t,"h",(function(){return P})),n.d(t,"a",(function(){return C})),n.d(t,"b",(function(){return S}));var s=n(0),i=n(14);function a(e){return e.hasOwnProperty("userId")}function r(e){return e.hasOwnProperty("chatId")}var o=n(18);function c(e,t=!1){const n=Boolean("min"in e&&e.min),i="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&v(e.photo),r=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:r,...i&&{accessHash:i},...a&&{avatarHash:a},...(e instanceof s.Api.Channel||e instanceof s.Api.User)&&{username:e.username},..."verified"in e&&{isVerified:e.verified},..."callActive"in e&&{isCallActive:e.callActive},..."callNotEmpty"in e&&{isCallNotEmpty:e.callNotEmpty},...(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...d(e),..."creator"in e&&{isCreator:e.creator},...l(e),...f(e)}}function u(e,t){const{peer:n,folderId:s,unreadMark:i,unreadCount:a,unreadMentionsCount:r,notifySettings:{silent:o,muteUntil:u},readOutboxMaxId:d,readInboxMaxId:l}=e,f=o||"number"==typeof u&&Date.now()<1e3*u;return{id:h(n),...s&&{folderId:s},type:y(t),title:_(n,t),lastReadOutboxMessageId:d,lastReadInboxMessageId:l,unreadCount:a,unreadMentionsCount:r,isMuted:f,...i&&{hasUnreadMark:!0},...c(t)}}function d(e){return e instanceof s.Api.Chat||e instanceof s.Api.Channel?{adminRights:Object(o.b)(e.adminRights),currentUserBannedRights:e instanceof s.Api.Channel?Object(o.b)(e.bannedRights):void 0,defaultBannedRights:Object(o.b)(e.defaultBannedRights)}:{}}function l(e){if(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden)return{isRestricted:!0};if(e instanceof s.Api.User){const t=e.restricted?p(e.restrictionReason):void 0;return void 0===t?{isRestricted:!1}:{isRestricted:e.restricted,restrictionReason:t}}if(e instanceof s.Api.Chat)return{isNotJoined:e.left,isRestricted:e.kicked};if(e instanceof s.Api.Channel){const t=e.restricted&&e.restrictionReason&&e.restrictionReason.some(e=>"all"===e.platform);return{isNotJoined:e.left,isRestricted:t,restrictionReason:p(e.restrictionReason)}}return{}}function f(e){return e instanceof s.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof s.Api.InputChannelEmpty)?{migratedTo:{chatId:h(e.migratedTo),...e.migratedTo instanceof s.Api.InputChannel&&{accessHash:e.migratedTo.accessHash.toString()}}}:{}}function p(e){if(!e)return;const t=e.find(({platform:e})=>"all"===e);return t?Object(i.b)(t,["reason","text"]):void 0}function g(e,t=!1,n=!1){if(e instanceof s.Api.Chat||e instanceof s.Api.Channel||e instanceof s.Api.User||n&&(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden))return{id:e instanceof s.Api.User?e.id:-e.id,type:y(e),title:e instanceof s.Api.User?w(e):e.title,...c(e,t)}}function h(e){return a(e)?e.userId:r(e)?-e.chatId:-e.channelId}function m(e){return function(e){return e.hasOwnProperty("userId")}(e)?e.userId:function(e){return e.hasOwnProperty("chatId")}(e)?-e.chatId:function(e){return e.hasOwnProperty("channelId")}(e)?-e.channelId:void 0}function y(e){return e instanceof s.Api.User||e instanceof s.Api.UserEmpty?"chatTypePrivate":e instanceof s.Api.Chat||e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function b(e){return a(e)?"user"+e.userId:r(e)?"chat"+e.chatId:"chat"+e.channelId}function _(e,t){return a(e)?w(t):t.title}function w(e){return e.firstName?`${e.firstName}${e.lastName?" "+e.lastName:""}`:e.lastName||void 0}function v(e){if("photoId"in e)return e.photoId.toString()}function A(e){return{userId:e instanceof s.Api.ChannelParticipantBanned||e instanceof s.Api.ChannelParticipantLeft?h(e.peer):e.userId,inviterId:"inviterId"in e?e.inviterId:void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?e.kickedBy:void 0,promotedByUserId:"promotedBy"in e?e.promotedBy:void 0,bannedRights:"bannedRights"in e?Object(o.b)(e.bannedRights):void 0,adminRights:"adminRights"in e?Object(o.b)(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof s.Api.ChannelParticipantAdmin||e instanceof s.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof s.Api.ChannelParticipantCreator||e instanceof s.Api.ChatParticipantCreator)&&{isOwner:!0}}}function I(e){return e instanceof s.Api.ChatParticipants||e instanceof s.Api.channels.ChannelParticipants?e.participants.map(A).filter(Boolean):void 0}function P(e){let t="";if(!(e.action instanceof s.Api.SendMessageCancelAction))return e.action instanceof s.Api.SendMessageTypingAction?t="lng_user_typing":e.action instanceof s.Api.SendMessageRecordVideoAction?t="lng_send_action_record_video":e.action instanceof s.Api.SendMessageUploadVideoAction?t="lng_send_action_upload_video":e.action instanceof s.Api.SendMessageRecordAudioAction?t="lng_send_action_record_audio":e.action instanceof s.Api.SendMessageUploadAudioAction?t="lng_send_action_upload_audio":e.action instanceof s.Api.SendMessageUploadPhotoAction?t="lng_send_action_upload_photo":e.action instanceof s.Api.SendMessageUploadDocumentAction?t="lng_send_action_upload_file":e.action instanceof s.Api.SendMessageGeoLocationAction?t="selecting a location to share":e.action instanceof s.Api.SendMessageChooseContactAction?t="selecting a contact to share":e.action instanceof s.Api.SendMessageGamePlayAction?t="lng_playing_game":e.action instanceof s.Api.SendMessageRecordRoundAction?t="lng_send_action_record_round":e.action instanceof s.Api.SendMessageUploadRoundAction&&(t="lng_send_action_upload_round"),{action:t,...!(e instanceof s.Api.UpdateUserTyping)&&{userId:h(e.fromId)},timestamp:Date.now()}}function C(e){return{...Object(i.c)(e,["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"]),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(m).filter(Boolean),includedChatIds:e.includePeers.map(m).filter(Boolean),excludedChatIds:e.excludePeers.map(m).filter(Boolean)}}function S({filter:e,description:t}){return{...C(e),description:t}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return s})),n.d(t,"g",(function(){return i})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return r})),n.d(t,"n",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"q",(function(){return u})),n.d(t,"o",(function(){return d})),n.d(t,"c",(function(){return l})),n.d(t,"b",(function(){return f})),n.d(t,"k",(function(){return p})),n.d(t,"w",(function(){return g})),n.d(t,"r",(function(){return h})),n.d(t,"t",(function(){return m})),n.d(t,"f",(function(){return y})),n.d(t,"u",(function(){return b})),n.d(t,"m",(function(){return _})),n.d(t,"s",(function(){return w})),n.d(t,"v",(function(){return v})),n.d(t,"a",(function(){return A})),n.d(t,"e",(function(){return I})),n.d(t,"j",(function(){return P})),n.d(t,"i",(function(){return C}));const s="8b04a98",i=!1,a=!1,r=!1,o=!1,c="tt-media",u="tt-media-avatars",d=524288,l=300,f=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),p=16,g=16,h=("undefined"!=typeof window&&window.innerHeight,200),m=50,y=100,b=40,_=1e9,w="MEMOJI_STICKER",v=777e3,A=0,I=1,P=777,C="android"},function(e,t,n){"use strict";t.a={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{}}},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{parseTl:i,serializeBytes:a,serializeDate:r}=n(44),{toSignedLittleBuffer:o}=n(8),c=n(79),u=n(80),d="undefined"!=typeof self&&void 0!==self.localStorage;function l(e){const t=i(e,109),n=[],s=[];for(const e of t)e.isFunction?s.push(e):n.push(e);return[n,s]}function f(e,n){switch(n){case"int":{const n=t.alloc(4);return n.writeInt32LE(e,0),n}case"long":return o(e,8);case"int128":return o(e,16);case"int256":return o(e,32);case"double":{const n=t.alloc(8);return n.writeDoubleLE(e,0),n}case"string":return a(e);case"Bool":return e?t.from("b5757299","hex"):t.from("379779bc","hex");case"true":return t.alloc(0);case"bytes":return a(e);case"date":return r(e);default:return e.getBytes()}}function p(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let i=0;i{this[e]=t[e]})}static fromReader(e){const t={};for(const n in c)if(c.hasOwnProperty(n)){const s=c[n];if(s.isFlag){if("true"===s.type){t[n]=Boolean(t.flags&1<f(t,c[e].type))))}else if(c[e].flagIndicator)if(Object.values(c).some(e=>e.isFlag)){let e=0;for(const t in c)c[t].isFlag&&(!1===this[t]&&"true"===c[t].type||void 0===this[t]?e|=0:e|=1</);if(n){t.readInt();const e=[],s=t.readInt();if("int"===n[1])for(let n=0;n{"function"!=typeof t[e]&&n[e]?Object.assign(n[e],t[e]):n[e]=t[e]}),n}(g("constructor",e.constructors),g("request",e.requests))}()}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"p",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"k",(function(){return m})),n.d(t,"w",(function(){return y})),n.d(t,"h",(function(){return b})),n.d(t,"u",(function(){return _})),n.d(t,"v",(function(){return w})),n.d(t,"a",(function(){return v})),n.d(t,"H",(function(){return A})),n.d(t,"b",(function(){return I})),n.d(t,"q",(function(){return P})),n.d(t,"r",(function(){return C})),n.d(t,"d",(function(){return S})),n.d(t,"c",(function(){return M})),n.d(t,"g",(function(){return k})),n.d(t,"z",(function(){return E})),n.d(t,"y",(function(){return R})),n.d(t,"i",(function(){return U})),n.d(t,"n",(function(){return O})),n.d(t,"f",(function(){return T})),n.d(t,"e",(function(){return D})),n.d(t,"A",(function(){return B})),n.d(t,"o",(function(){return x})),n.d(t,"B",(function(){return j})),n.d(t,"F",(function(){return N})),n.d(t,"G",(function(){return V})),n.d(t,"E",(function(){return F})),n.d(t,"I",(function(){return L})),n.d(t,"D",(function(){return q})),n.d(t,"C",(function(){return H})),n.d(t,"m",(function(){return K})),n.d(t,"l",(function(){return z})),n.d(t,"x",(function(){return G})),n.d(t,"s",(function(){return W})),n.d(t,"t",(function(){return $}));var s=n(0),i=n(4),a=n(1),r=n(3),o=n(9),c=n(13),u=n(14),d=n(5),l=n(2),f=n(16);let p;function g(e){p=e}async function h({limit:e,offsetDate:t,archived:n,withPinned:d}){const l=await Object(a.g)(new s.Api.messages.GetDialogs({offsetPeer:new s.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?i.e:void 0,...d&&{excludePinned:!0}})),f=d?await Object(a.g)(new s.Api.messages.GetPinnedDialogs({folderId:n?i.e:void 0})):void 0;if(!l||l instanceof s.Api.messages.DialogsNotModified)return;Z(l),f&&Z(f);const p=Object(u.a)([...l.messages,...f?f.messages:[]].map(o.b).filter(Boolean),"chatId"),g={...J(l),...f&&J(f)},h=[],m={},y={},b=[...f?f.dialogs:[],...l.dialogs],_=[];b.forEach(e=>{if(!(e instanceof s.Api.Dialog)||!n&&e.folderId===i.e||n&&e.folderId!==i.e)return;const t=g[Object(r.k)(e.peer)],a=Object(r.c)(e,t);if(a.lastMessage=p[a.id],h.push(a),d&&e.pinned&&_.push(a.id),e.draft){const{formattedText:t,replyingToId:n}=Object(o.h)(e.draft)||{};t&&(m[a.id]=t),n&&(y[a.id]=n)}});const w=[...l.users,...f?f.users:[]].map(c.a).filter(Boolean),v=h.map(e=>e.id);let A;return A=l instanceof s.Api.messages.DialogsSlice?l.count:v.length,{chatIds:v,chats:h,users:w,draftsById:m,replyingToById:y,orderedPinnedIds:d?_:void 0,totalChatCount:A}}function m(e){const{id:t,accessHash:n,adminRights:i}=e;return Object(l.g)(t,n)instanceof s.Api.InputChannel?async function(e,t,n){const i=await Object(a.g)(new s.Api.channels.GetFullChannel({channel:Object(l.g)(e,t)}));if(!(i&&i.fullChat instanceof s.Api.ChannelFull))return;const{about:o,onlineCount:c,exportedInvite:u,slowmodeSeconds:d,slowmodeNextSendDate:f,migratedFromChatId:p,migratedFromMaxId:g,canViewParticipants:h,linkedChatId:m,hiddenPrehistory:y,call:b}=i.fullChat,_=u instanceof s.Api.ChatInviteExported?u.link:void 0,{members:w,users:v}=h&&await K(e,t)||{},{members:A,users:I}=h&&n&&await K(e,t,"kicked")||{},{members:P,users:C}=h&&n&&await K(e,t,"admin")||{};return{fullInfo:{about:o,onlineCount:c,inviteLink:_,slowMode:d?{seconds:d,nextSendDate:f}:void 0,migratedFrom:p?{chatId:Object(r.j)({chatId:p}),maxMessageId:g}:void 0,canViewMembers:h,isPreHistoryHidden:y,members:w,kickedMembers:A,adminMembers:P,groupCallId:b?b.id.toString():void 0,linkedChatId:m?Object(r.j)({chatId:m}):void 0},users:[...v||[],...I||[],...C||[]]}}(t,n,i):async function(e){const t=await Object(a.g)(new s.Api.messages.GetFullChat({chatId:Object(l.g)(e)}));if(!(t&&t.fullChat instanceof s.Api.ChatFull))return;Z(t);const{about:n,participants:i,exportedInvite:o}=t.fullChat,u=Object(r.g)(i),d=u?u.filter(({isAdmin:e,isOwner:t})=>e||t):void 0;return{fullInfo:{about:n,members:u,adminMembers:d,canViewMembers:!0,...o&&{inviteLink:o.link}},users:t.users.map(c.a).filter(Boolean)}}(t)}async function y({query:e}){const t=await Object(a.g)(new s.Api.contacts.Search({q:e}));if(!t)return;Z(t);const n=t.myResults.map(r.j),i=[...t.chats,...t.users].map(e=>Object(r.d)(e)).filter(Boolean),o=t.users.map(c.a).filter(e=>!!e&&!e.isSelf);return{localChats:i.filter(e=>n.includes(e.id)),localUsers:o.filter(e=>n.includes(e.id)),globalChats:i.filter(e=>!n.includes(e.id)),globalUsers:o.filter(e=>!n.includes(e.id))}}async function b({type:e,user:t}){let n;if("self"===e||"user"===e){const i=await Object(a.g)(new s.Api.users.GetUsers({id:["user"===e&&t?Object(l.g)(t.id,t.accessHash):new s.Api.InputUserSelf]}));if(!i||!i.length)return;[n]=i}else if("support"===e){const e=await Object(a.g)(new s.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const i=Object(r.d)(n,"support"===e);if(i)return p({"@type":"updateChat",id:i.id,chat:i}),{chatId:i.id}}async function _(e){const{id:t,accessHash:n}=e,i=await Object(a.g)(new s.Api.messages.GetPeerDialogs({peers:[new s.Api.InputDialogPeer({peer:Object(l.i)(t,n)})]}));if(!i)return;const c=i.dialogs[0];if(!(c&&c instanceof s.Api.Dialog))return;const u=J(i)[Object(r.k)(c.peer)];if(!u)return;Z(i);const d=Object(o.b)(i.messages[0]);p({"@type":"updateChat",id:t,chat:{...Object(r.c)(c,u),lastMessage:d}})}function w({chat:e,text:t,entities:n,replyToMsgId:i}){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:t,...n&&{entities:n.map(l.n)},replyToMsgId:i}))}function v(e){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:""}))}async function A({chat:e,isMuted:t}){await Object(a.g)(new s.Api.account.UpdateNotifySettings({peer:new s.Api.InputNotifyPeer({peer:Object(l.i)(e.id,e.accessHash)}),settings:new s.Api.InputPeerNotifySettings({muteUntil:t?2**31-1:void 0})})),_(e)}async function I({title:e,about:t,users:n}){const o=await Object(a.g)(new s.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(o instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected channel creation update",o));const c=o.chats[0];if(!(c&&c instanceof s.Api.Channel))return void(i.g&&console.error("Created channel not found",o));const u=Object(r.d)(c);return await Object(a.g)(new s.Api.channels.InviteToChannel({channel:Object(l.g)(u.id,u.accessHash),users:n.map(({id:e,accessHash:t})=>Object(l.g)(e,t))})),u}function P({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.JoinChannel({channel:Object(l.g)(e,t)}),!0)}function C({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.LeaveChannel({channel:Object(l.g)(e,t)}),!0)}function S({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.DeleteChannel({channel:Object(l.g)(e,t)}),!0)}async function M({title:e,users:t}){const n=await Object(a.g)(new s.Api.messages.CreateChat({title:e,users:t.map(({id:e,accessHash:t})=>Object(l.g)(e,t))}),!0);if(!(n instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected chat creation update",n));const o=n.chats[0];if(o&&o instanceof s.Api.Chat)return Object(r.d)(o);i.g&&console.error("Created chat not found",n)}async function k({chatId:e,accessHash:t,photo:n}){const i=await Object(a.i)(n),r=Object(l.g)(e,t);return Object(a.g)(r instanceof s.Api.InputChannel?new s.Api.channels.EditPhoto({channel:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}):new s.Api.messages.EditChatPhoto({chatId:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}),!0)}async function E({chat:e,shouldBePinned:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.ToggleDialogPin({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),pinned:t||void 0}))&&p({"@type":"updateChatPinned",id:e.id,isPinned:t})}function R({chat:e,folderId:t}){const{id:n,accessHash:i}=e;return Object(a.g)(new s.Api.folders.EditPeerFolders({folderPeers:[new s.Api.InputFolderPeer({peer:Object(l.i)(n,i),folderId:t})]}),!0)}async function U(){const e=await Object(a.g)(new s.Api.messages.GetDialogFilters);if(e)return{byId:Object(u.a)(e.map(r.a),"id"),orderedIds:e.map(({id:e})=>e)}}async function O(){const e=await Object(a.g)(new s.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(r.b)}async function T({id:e,folderUpdate:t}){const n=Object(l.d)(t);await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&p({"@type":"updateChatFolder",id:e,folder:t})}async function D(e){const t=await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await O();t&&p({"@type":"updateChatFolder",id:e,folder:void 0}),n&&p({"@type":"updateRecommendedChatFolders",folders:n})}async function B({chat:e,hasUnreadMark:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.MarkDialogUnread({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),unread:t||void 0}))&&p({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function x(e){const t=await Object(a.g)(new s.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:i}=t,o=i.length?Object(r.d)(i[0]):Object(r.d)(n[0]);return o?(Z(t),o):void 0}function j({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.TogglePreHistoryHidden({channel:r,enabled:t}),!0)}function N({chat:e,bannedRights:t}){const{id:n,accessHash:i}=e,r=Object(l.i)(n,i);return Object(a.g)(new s.Api.messages.EditChatDefaultBannedRights({peer:r,bannedRights:Object(l.b)(t)}),!0)}function V({chat:e,user:t,bannedRights:n}){const i=Object(l.g)(e.id,e.accessHash),r=Object(l.i)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditBanned({channel:i,participant:r,bannedRights:Object(l.b)(n)}),!0)}function F({chat:e,user:t,adminRights:n,customTitle:i=""}){const r=Object(l.g)(e.id,e.accessHash),o=Object(l.g)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditAdmin({channel:r,userId:o,adminRights:Object(l.a)(n),rank:i}),!0)}async function L(e,t){const n=Object(l.g)(e.id,e.accessHash);await Object(a.g)(n instanceof s.Api.InputChannel?new s.Api.channels.EditTitle({channel:n,title:t}):new s.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function q(e,t){await Object(a.g)(new s.Api.messages.EditChatAbout({peer:Object(l.i)(e.id,e.accessHash),about:t}))&&p({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function H({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.ToggleSignatures({channel:r,enabled:t}),!0)}async function K(e,t,n="recent",o){let u;switch(n){case"kicked":u=new s.Api.ChannelParticipantsKicked({q:""});break;case"admin":u=new s.Api.ChannelParticipantsAdmins;break;default:u=new s.Api.ChannelParticipantsRecent}const d=await Object(a.g)(new s.Api.channels.GetParticipants({channel:Object(l.g)(e,t),filter:u,offset:o,limit:i.r}));if(d&&!(d instanceof s.Api.channels.ChannelParticipantsNotModified))return Z(d),{members:Object(r.g)(d),users:d.users.map(c.a).filter(Boolean)}}async function z(){const e=await Object(a.g)(new s.Api.channels.GetGroupsForDiscussion);if(e)return Z(e),e.chats.map(e=>Object(r.d)(e))}function G({channel:e,chat:t}){return Object(a.g)(new s.Api.channels.SetDiscussionGroup({broadcast:Object(l.i)(e.id,e.accessHash),group:t?Object(l.i)(t.id,t.accessHash):new s.Api.InputChannelEmpty}))}async function W(e){const t=await Object(a.g)(new s.Api.messages.MigrateChat({chatId:Object(l.g)(e.id)}),!0);if(t&&t instanceof s.Api.Updates)return Z(t),Object(r.d)(t.chats[1]);i.g&&console.error("Unexpected channel creation update",t)}async function $(e){const t=await Object(a.g)(new s.Api.messages.CheckChatInvite({hash:e}));if(t)return t instanceof s.Api.ChatInvite?void await Object(a.g)(new s.Api.messages.ImportChatInvite({hash:e}),!0):Object(r.d)(t.chat)}function J(e){const t={};return e.chats.forEach(e=>{t["chat"+e.id]=e}),e.users.forEach(e=>{t["user"+e.id]=e}),t}function Z(e){"users"in e&&e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),"chats"in e&&e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),"messages"in e&&e.messages.forEach(e=>{e instanceof s.Api.Message&&Object(l.t)(e)&&Object(f.a)(e)})}},function(e,t,n){(function(t){const s=n(15),i=n(35);function a(e,n=!0,i=!1){let a=t.from(e);const r=a.length;n&&(a=a.reverse());let o=s(a.toString("hex"),16);return i&&Math.floor(o.toString("2").length/8)>=r&&(o=o.subtract(s(2).pow(s(8*r)))),o}function r(e,n=8){const i=s(e),a=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0},generateRandomBytes:c,generateKeyDataFromNonce:async function(e,n){e=r(e,16),n=r(n,32);const[s,i,a]=await Promise.all([u(t.concat([n,e])),u(t.concat([e,n])),u(t.concat([n,n]))]);return{key:t.concat([s,i.slice(0,12)]),iv:t.concat([i.slice(12,20),a,n.slice(0,4)])}},sha1:u,sha256:function(e){const t=i.createHash("sha256");return t.update(e),t.digest()},bigIntMod:function(e,t){return e.remainder(t).add(t).remainder(t)},modExp:function(e,t,n){e=e.remainder(n);let i=s.one,a=e;for(;t.greater(s.zero);){const e=t.remainder(s(2));t=t.divide(s(2)),e.eq(s.one)&&(i=i.multiply(a),i=i.remainder(n)),a=a.multiply(a),a=a.remainder(n)}return i},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise(t=>setTimeout(t,e)),getByteArray:function(e,t=!1){const n=e.toString(2).length,i=Math.floor((n+8-1)/8);return o(s(e),i,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const n=t.alloc(4*e.length);for(let t=0;t1?"s":""})`}}else if(e instanceof s.Api.MessageActionContactSignUp)o="%action_origin% joined Telegram";else if(e instanceof s.Api.MessageActionPaymentSent){const t=l(e.currency),n=(Number(e.totalAmount)/100).toFixed(2);o=`You successfully transferred ${t}${n} to shop for %product%`}else if(e instanceof s.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);o=`Voice chat ended (${t} min${t>1?"s":""})`}else o="Voice chat started";else o="%ACTION_NOT_IMPLEMENTED%";"photo"in e&&e.photo instanceof s.Api.Photo&&(Object(p.b)(e.photo),a=Object(c.a)(e.photo));return{text:o,type:u,targetUserId:d,targetChatId:f,photo:a}}(t.action,n,Boolean(t.post),a);u&&(o.action=u);const{replyToMsgId:d,replyToTopId:f}=t.replyTo||{},h=t.editDate&&!t.editHide,{inlineButtons:m,keyboardButtons:y}=function(e){const{id:t,replyMarkup:n,media:i}=e;if(!n)return i instanceof s.Api.MessageMediaWebPage&&i.webpage instanceof s.Api.WebPage&&"telegram_message"===i.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:i.webpage.url}]]}:void 0;if(!(n instanceof s.Api.ReplyKeyboardMarkup||n instanceof s.Api.ReplyInlineMarkup))return;const a=n.rows.map(({buttons:e})=>e.map(e=>{let n,a,{text:r}=e;return e instanceof s.Api.KeyboardButton?(n="command",a=r):e instanceof s.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof s.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof s.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof s.Api.KeyboardButtonBuy?(i instanceof s.Api.MessageMediaInvoice&&i.receiptMsgId&&(r="Receipt",a=i.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:r,messageId:t,value:a}}));return{[n instanceof s.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a}}(t)||{},b=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&Object(r.j)(e.savedFromPeer),s=e.fromId&&Object(r.j)(e.fromId);return{isChannelPost:Boolean(e.channelPost),isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,i),{replies:_,mediaUnread:w,postAuthor:v}=t,I=t.groupedId&&t.groupedId.toString(),C=Boolean(I)&&!(o.document||o.audio),S=t.replyMarkup instanceof s.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:a,content:o,date:t.date,senderId:n||t.out&&t.post&&g||e,views:t.views,isFromScheduled:t.fromScheduled,...d&&{replyToMessageId:d},...f&&{replyToTopMessageId:f},...b&&{forwardInfo:b},...h&&{isEdited:h},...w&&{isMediaUnread:w},...t.mentioned&&w&&{hasUnreadMention:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:m,...y&&{keyboardButtons:y},...S&&{shouldHideKeyboardButtons:S},...t.viaBotId&&{viaBotId:t.viaBotId},..._&&_.comments&&{threadInfo:B(_,t.id,e)},...v&&{adminTitle:v}}}function A(e,t){return{text:e,...t&&{entities:t.map(D)}}}function I(e){if(!(e instanceof s.Api.DraftMessageEmpty)&&e.message)return{formattedText:A(e.message,e.entities),replyingToId:e.replyToMsgId}}function P(e){const t=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;return Object(o.a)(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(!(e instanceof s.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof s.Api.Photo))return;if(e.ttlSeconds)return;return Object(c.a)(e.photo)}(e);if(n)return{photo:n};const i=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document instanceof s.Api.Document&&e.document.mimeType.startsWith("video")))return;return C(e.document)}(e);if(i)return{video:i};const r=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||t.voice)return;return{fileName:R(e.document,"audio"),...Object(a.b)(e.document,["size","mimeType"]),...Object(a.b)(t,["duration","performer","title"])}}(e);if(r)return{audio:r};const u=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||!t.voice)return;const{duration:n,waveform:i}=t;return{duration:n,waveform:i?Array.from(i):void 0}}(e);if(u)return{voice:u};const d=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document))return;if(e.ttlSeconds)return;return S(e.document)}(e);if(d)return{document:d};const f=function(e){if(!(e instanceof s.Api.MessageMediaContact))return;return Object(a.b)(e,["firstName","lastName","phoneNumber","userId"])}(e);if(f)return{contact:f};const p=function(e){if(!(e instanceof s.Api.MessageMediaPoll))return;return M(e.poll,e.results)}(e);if(p)return{poll:p};const g=E(e);if(g)return{webPage:g};const h=function(e){if(!(e instanceof s.Api.MessageMediaInvoice))return;return function(e){const{description:t,title:n,photo:s,test:i,totalAmount:a,currency:r,receiptMsgId:o}=e,c=l(r);return{text:t,title:n,photoUrl:s&&s.url,receiptMsgId:o,description:`${c}${(Number(a)/100).toFixed(2)} ${i?"TEST INVOICE":""}`}}(e)}(e);return h?{invoice:h}:void 0}function C(e){if(e instanceof s.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:i,size:a,attributes:r}=e,o=r.find(e=>e instanceof s.Api.DocumentAttributeVideo);if(!o)return;const u=r.find(e=>e instanceof s.Api.DocumentAttributeAnimated),{duration:d,w:l,h:f,supportsStreaming:p=!1,roundMessage:g=!1}=o;return{id:String(t),mimeType:n,duration:d,fileName:R(e,"video"),width:l,height:f,supportsStreaming:p,isRound:g,isGif:Boolean(u),thumbnail:Object(c.e)(i),size:a}}function S(e){if(!(e instanceof s.Api.Document))return;const{id:t,size:n,mimeType:i,date:a,thumbs:r}=e,o=r&&Object(c.e)(r);return{id:String(t),size:n,mimeType:i,timestamp:a,fileName:R(e),thumbnail:o}}function M(e,t){const{id:n,answers:s}=e,i=s.map(e=>({text:e.text,option:String.fromCharCode(...e.option)}));return{id:n.toString(),summary:{isPublic:e.publicVoters,...Object(a.b)(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:i},results:k(t)}}function k(e){const{results:t,totalVoters:n,recentVoters:s,solution:i,solutionEntities:a}=e;return{totalVoters:n,recentVoterIds:s,results:t&&t.map(({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})),solution:i,...a&&{solutionEntities:a.map(D)}}}function E(e){if(!(e instanceof s.Api.MessageMediaWebPage&&e.webpage instanceof s.Api.WebPage))return;const{id:t,photo:n,document:i}=e.webpage;return{id:Number(t),...Object(a.b)(e.webpage,["url","displayUrl","siteName","title","description"]),photo:n&&n instanceof s.Api.Photo?{id:String(n.id),thumbnail:Object(c.e)(n.sizes),sizes:n.sizes.filter(e=>e instanceof s.Api.PhotoSize).map(c.b)}:void 0,...i&&{hasDocument:!0}}}function R(e,t="file"){const{mimeType:n,attributes:i}=e,a=i.find(e=>e instanceof s.Api.DocumentAttributeFilename);if(a)return a.fileName;const r=n.split("/")[1];return`${t}${String(e.id)}.${r}`}function U(e,t,n,s,i,a,r,o,c,d){const l=h++,f=i&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:i,size:a}=e;if(e.quick){const{width:r,height:o,duration:c}=e.quick;return i.startsWith("image/")?{photo:{id:"temp",sizes:[],thumbnail:{width:r,height:o,dataUri:""},blobUrl:n}}:{video:{id:"temp",mimeType:i,duration:c||0,fileName:t,width:r,height:o,blobUrl:n,...s&&{thumbnail:{width:r,height:o,dataUri:s}},size:a}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=Object(u.a)(n,63);return{voice:{duration:t,waveform:s}}}return i.startsWith("audio/")?{audio:{mimeType:i,fileName:t,size:a,duration:200}}:{document:{mimeType:i,fileName:t,size:a,...s&&{previewBlobUrl:s}}}}(i),p="chatTypeChannel"===e.type;return{id:l,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...a&&{sticker:a},...r&&{video:r},...o&&T(o,l)},date:d||Math.round(Date.now()/1e3),isOutgoing:!p,senderId:g,...s&&{replyToMessageId:s},...c&&{groupedId:c,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}function O(e,t){const n=h++,{content:s,chatId:i,id:a,senderId:r,groupedId:o,isInAlbum:c}=t,u=s.audio,d=e.id===g&&(i!==e.id||t.forwardInfo)&&!u;return{id:n,chatId:e.id,content:s,date:Math.round(Date.now()/1e3),isOutgoing:!d&&"chatTypeChannel"!==e.type,senderId:g,sendingState:"messageSendingStatePending",...r!==g&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:i,fromMessageId:a,senderUserId:r}},groupedId:o,isInAlbum:c}}function T(e,t){return{poll:{id:t.toString(),summary:Object(a.b)(e.summary,["question","answers"]),results:{}}}}function D(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function B(e,t,n){const{channelId:s,replies:a,maxId:o,readMaxId:c,recentRepliers:u}=e;if(s===i.j)return;return{threadId:t,...n!==s?{chatId:Object(r.j)({channelId:s}),originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:o,lastReadInboxMessageId:c,...u&&{recentReplierIds:u.map(r.j)}}}},function(e,t,n){"use strict";(function(e){n.d(t,"m",(function(){return y})),n.d(t,"g",(function(){return b})),n.d(t,"e",(function(){return _})),n.d(t,"v",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"s",(function(){return P})),n.d(t,"q",(function(){return S})),n.d(t,"y",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"c",(function(){return E})),n.d(t,"a",(function(){return R})),n.d(t,"o",(function(){return U})),n.d(t,"p",(function(){return O})),n.d(t,"r",(function(){return T})),n.d(t,"u",(function(){return D})),n.d(t,"t",(function(){return B})),n.d(t,"j",(function(){return x})),n.d(t,"w",(function(){return j})),n.d(t,"n",(function(){return N})),n.d(t,"l",(function(){return V})),n.d(t,"k",(function(){return F})),n.d(t,"i",(function(){return L})),n.d(t,"x",(function(){return q})),n.d(t,"f",(function(){return H})),n.d(t,"h",(function(){return z}));var s=n(0),i=n(11),a=n(4),r=n(1),o=n(9),c=n(13),u=n(2),d=n(5),l=n(3),f=n(34),p=n(16),g=n(33),h=n(7);let m;function y(e){m=e}async function b({chat:e,threadId:t,...n}){const a=t===i.MAIN_THREAD_ID?s.Api.messages.GetHistory:s.Api.messages.GetReplies;let d;try{d=await Object(r.g)(new a({peer:Object(u.i)(e.id,e.accessHash),...t!==i.MAIN_THREAD_ID&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&m({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!d||d instanceof s.Api.messages.MessagesNotModified||!d.messages)return;K(d);const f=d.messages.map(o.b).filter(Boolean),p=d.users.map(c.a).filter(Boolean),g=d.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=f.map(({threadInfo:e})=>e).filter(Boolean);return{messages:f,users:p,chats:g,threadInfos:h}}async function _({chat:e,messageId:t}){const n="channel"===Object(u.s)(e.id),a=await Object(r.g)(n?new s.Api.channels.GetMessages({channel:Object(u.g)(e.id,e.accessHash),id:[new s.Api.InputMessageID({id:t})]}):new s.Api.messages.GetMessages({id:[new s.Api.InputMessageID({id:t})]}));if(!a||a instanceof s.Api.messages.MessagesNotModified)return;const d=a.messages[0];if(!d)return;if(d instanceof s.Api.MessageEmpty)return i.MESSAGE_DELETED;const l=d&&Object(o.b)(d);if(!l)return;d instanceof s.Api.Message&&Object(p.a)(d);return{message:l,users:a.users.map(c.a).filter(Boolean)}}let w=Promise.resolve();function v({chat:e,text:t,entities:n,replyingTo:i,attachment:c,sticker:l,gif:f,poll:p,isSilent:g,scheduledAt:h,groupedId:y,noWebPage:b},_){const v=Object(o.g)(e,t,n,i,c,l,f,p,y,h);m({"@type":v.isScheduled?"newScheduledMessage":"newMessage",id:v.id,chatId:e.id,message:v}),setTimeout(()=>{m({"@type":v.isScheduled?"updateScheduledMessage":"updateMessage",id:v.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})},1e3);const I=Object(u.r)();if(d.a.localMessages[I.toString()]=v,y)return function({chat:e,text:t,entities:n,replyingTo:i,attachment:o,groupedId:c,isSilent:d,scheduledAt:l},f,p,g){let h=-1;A[c]||(A[c]={counter:0,singleMediaByIndex:{}});h=A[c].counter++;const m=w;return w=(async()=>{let y;try{y=await C(p,o,g)}catch(e){return a.g&&console.warn(e),A[c].counter--,void await m}const b=await async function(e,t){const n=await Object(r.g)(new s.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof s.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof s.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaPhoto({id:new s.Api.InputPhoto({id:e,accessHash:t,fileReference:i})})}if(n instanceof s.Api.MessageMediaDocument&&n.document&&n.document instanceof s.Api.Document){const{document:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaDocument({id:new s.Api.InputDocument({id:e,accessHash:t,fileReference:i})})}return}(Object(u.i)(e.id,e.accessHash),y);if(await m,!b)return A[c].counter--,void(a.g&&console.warn("Failed to upload grouped media"));if(A[c].singleMediaByIndex[h]=new s.Api.InputSingleMedia({media:b,randomId:f,message:t||"",entities:n?n.map(u.n):void 0}),Object.keys(A[c].singleMediaByIndex).length{let o;if(c)try{o=await C(v,c,_)}catch(e){return a.g&&console.warn(e),void await P}else l?o=Object(u.h)(l):f?o=Object(u.h)(f):p&&(o=Object(u.j)(p,I));await P;const d=o?s.Api.messages.SendMedia:s.Api.messages.SendMessage;await Object(r.g)(new d({clearDraft:!0,message:t||"",entities:n?n.map(u.n):void 0,peer:Object(u.i)(e.id,e.accessHash),randomId:I,...g&&{silent:g},...h&&{scheduleDate:h},...i&&{replyToMsgId:i},...o&&{media:o},...b&&{noWebpage:b}}),!0)})(),w}const A={};async function I({chat:e,message:t,text:n,entities:i,noWebPage:a}){const o=1e3*t.date>Date.now(),c={content:{...t.content,...n&&{text:{text:n,entities:i}}}};m({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:c}),d.a.localMessages[t.id]={...t,...c};const l=i&&i.map(u.n);await Object(r.g)(new s.Api.messages.EditMessage({message:n||"",entities:l,peer:Object(u.i)(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function P({chat:e,message:t,scheduledAt:n}){await Object(r.g)(new s.Api.messages.EditMessage({peer:Object(u.i)(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function C(t,n,i){const{filename:a,blobUrl:o,mimeType:c,quick:u,voice:d}=n,l=await Object(f.b)(o,a),p=e=>{i.isCanceled?p.isCanceled=!0:i(e,t.id)},h=await Object(r.i)(l,p),m=[new s.Api.DocumentAttributeFilename({fileName:a})];if(u){if(c.startsWith("image/"))return new s.Api.InputMediaUploadedPhoto({file:h});{const{width:e,height:t,duration:n}=u;void 0!==n&&m.push(new s.Api.DocumentAttributeVideo({duration:n,w:e,h:t}))}}if(d){const{duration:t,waveform:n}=d,{data:i}=Object(g.a)(n,63);m.push(new s.Api.DocumentAttributeAudio({voice:!0,duration:t,waveform:e.from(i)}))}return new s.Api.InputMediaUploadedDocument({file:h,mimeType:c,attributes:m})}async function S({chat:e,messageId:t,isUnpin:n,isOneSide:i,isSilent:a}){await Object(r.g)(new s.Api.messages.UpdatePinnedMessage({peer:Object(u.i)(e.id,e.accessHash),id:t,...n&&{unpin:!0},...i&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function M({chat:e}){await Object(r.g)(new s.Api.messages.UnpinAllMessages({peer:Object(u.i)(e.id,e.accessHash)}),!0)}async function k({chat:e,messageIds:t,shouldDeleteForAll:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteMessages({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&m({"@type":"deleteMessages",ids:t,...i&&{chatId:e.id}})}async function E({chat:e,messageIds:t}){await Object(r.g)(new s.Api.messages.DeleteScheduledMessages({peer:Object(u.i)(e.id,e.accessHash),id:t}))&&m({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function R({chat:e,shouldDeleteForAll:t,maxId:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n}):new s.Api.messages.DeleteHistory({peer:Object(u.i)(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&m({"@type":"deleteHistory",chatId:e.id})}async function U({chat:e,threadId:t,maxId:n}){const a="channel"===Object(u.s)(e.id);a&&t===i.MAIN_THREAD_ID?await Object(r.g)(new s.Api.channels.ReadHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n})):a?await Object(r.g)(new s.Api.messages.ReadDiscussion({peer:Object(u.i)(e.id,e.accessHash),msgId:t,readMaxId:n})):await Object(r.g)(new s.Api.messages.ReadHistory({peer:Object(u.i)(e.id,e.accessHash),maxId:n})),t===i.MAIN_THREAD_ID?Object(h.u)(e):T({chat:e,threadId:t})}async function O({chat:e,messageIds:t}){const n="channel"===Object(u.s)(e.id);await Object(r.g)(n?new s.Api.channels.ReadMessageContents({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.ReadMessageContents({id:t})),m({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function T({chat:e,threadId:t}){const[n,i]=await Promise.all([Object(r.g)(new s.Api.messages.GetDiscussionMessage({peer:Object(u.i)(e.id,e.accessHash),msgId:t})),Object(r.g)(new s.Api.messages.GetReplies({peer:Object(u.i)(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=Object(p.c)(n.messages[0]);if(!a)return;m({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:i instanceof s.Api.messages.ChannelMessages?i.count:void 0},firstMessageId:i&&"messages"in i&&i.messages.length?i.messages[0].id:void 0});n.chats.map(e=>Object(l.d)(e)).filter(Boolean).forEach(e=>{m({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})}async function D({chatOrUser:e,type:t,query:n,topMessageId:i,minDate:a,maxDate:d,...l}){let f;switch(t){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"profilePhoto":f=new s.Api.InputMessagesFilterChatPhotos;break;case"text":default:f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:f,q:n||"",topMsgId:i,minDate:a,maxDate:d,...l}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K(p);const g=p.messages.map(o.b).filter(Boolean),h=p.users.map(c.a).filter(Boolean);let m,y=g.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(y=p.count,g.length&&(m=g[g.length-1].id)),{messages:g,users:h,totalCount:y,nextOffsetId:m}}async function B({query:e,offsetRate:t=0,limit:n,type:i="text",minDate:u,maxDate:d}){let f;switch(i){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"text":default:if(!(e||d&&u))return;f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new s.Api.InputPeerEmpty,limit:n,filter:f,folderId:a.a,minDate:u,maxDate:d}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K({chats:p.chats,users:p.users,messages:p.messages});const g=p.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=p.users.map(c.a).filter(Boolean),m=p.messages.map(o.b).filter(Boolean);let y,b=m.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(b=p.count,m.length&&(y=m[m.length-1].id)),{messages:m,users:h,chats:g,totalCount:b,nextRate:"nextRate"in p&&p.nextRate?p.nextRate:y}}async function x({message:e}){const t=await Object(r.g)(new s.Api.messages.GetWebPagePreview({message:e}));return t&&Object(o.n)(t)}async function j({chat:t,messageId:n,options:i}){const{id:a,accessHash:o}=t;await Object(r.g)(new s.Api.messages.SendVote({peer:Object(u.i)(a,o),msgId:n,options:i.map(t=>e.from(t))}),!0)}async function N({chat:t,messageId:n,option:i,offset:a,limit:o,shouldResetVoters:d}){const{id:l,accessHash:f}=t,p=await Object(r.g)(new s.Api.messages.GetPollVotes({peer:Object(u.i)(l,f),id:n,...i&&{option:e.from(i)},...a&&{offset:a},...o&&{limit:o}}));if(!p)return;K({chats:[],users:p.users,messages:[]});const g=p.users.map(c.a).filter(Boolean),h=p.votes.map(e=>({userId:e.userId,date:e.date}));return{count:p.count,votes:h,users:g,nextOffset:p.nextOffset,shouldResetVoters:d}}async function V({fromChat:e,toChat:t,messages:n}){const i=n.map(({id:e})=>e),a=n.map(u.r);n.forEach((e,n)=>{const s=Object(o.f)(t,e);d.a.localMessages[String(a[n])]=s,m({"@type":"newMessage",id:s.id,chatId:t.id,message:s})}),await Object(r.g)(new s.Api.messages.ForwardMessages({fromPeer:Object(u.i)(e.id,e.accessHash),toPeer:Object(u.i)(t.id,t.accessHash),randomId:a,id:i}),!0)}async function F({chat:e,timestamp:t}){const n=await Object(r.g)(new s.Api.messages.GetHistory({peer:Object(u.i)(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof s.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function L({chat:e,hash:t=0}){const{id:n,accessHash:i}=e,a=await Object(r.g)(new s.Api.messages.GetScheduledHistory({peer:Object(u.i)(n,i),hash:t}));if(!a||a instanceof s.Api.messages.MessagesNotModified||!a.messages)return;K(a);const c=a.messages.map(o.b).filter(Boolean);return{messages:c,hash:Object(u.q)(c.map(e=>e.id))}}async function q({chat:e,ids:t}){const{id:n,accessHash:i}=e;await Object(r.g)(new s.Api.messages.SendScheduledMessages({peer:Object(u.i)(n,i),id:t}),!0)}function H({chat:e,message:t}){return Object(r.g)(new s.Api.channels.ExportMessageLink({id:t.id,channel:Object(u.g)(e.id,e.accessHash),...t.isInAlbum&&{grouped:!0},...t.threadInfo&&t.threadInfo.topMessageId!==t.id&&{thread:!0}}))}function K(e){e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),e.messages.forEach(e=>{(e instanceof s.Api.Message&&Object(u.t)(e)||e instanceof s.Api.MessageService&&Object(u.u)(e))&&Object(p.a)(e)})}async function z({chat:e}){const t=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:new s.Api.InputMessagesFilterPinned,q:"",limit:a.t}));if(!t||t instanceof s.Api.messages.MessagesNotModified||!t.messages)return;K(t);return{messages:t.messages.map(o.b).filter(Boolean),users:t.users.map(c.a).filter(Boolean),chats:t.chats.map(e=>Object(l.d)(e)).filter(Boolean)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";var s=n(64);n.o(s,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return s.ApiMediaFormat})),n.o(s,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return s.ApiMessageEntityTypes})),n.o(s,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return s.MAIN_THREAD_ID})),n.o(s,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return s.MESSAGE_DELETED}));var i=n(65);n.o(i,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return i.ApiMediaFormat})),n.o(i,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return i.ApiMessageEntityTypes})),n.o(i,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return i.MAIN_THREAD_ID})),n.o(i,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return i.MESSAGE_DELETED}));var a=n(66);n.d(t,"ApiMessageEntityTypes",(function(){return a.a})),n.d(t,"MAIN_THREAD_ID",(function(){return a.b})),n.d(t,"MESSAGE_DELETED",(function(){return a.c}));var r=n(67);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat}));var o=n(68);n.d(t,"ApiMediaFormat",(function(){return o.a}));n(69),n(70),n(71)},function(e,t,n){"use strict";(function(e){var s=n(73),i=n(74),a=n(75);function r(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(r()=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(s)return F(e).length;t=(""+t).toLowerCase(),s=!0}}function h(e,t,n){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function m(e,t,n){var s=e[t];e[t]=e[n],e[n]=s}function y(e,t,n,s,i){if(0===e.length)return-1;if("string"==typeof n?(s=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,s)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,s,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,s,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,s,i){var a,r=1,o=e.length,c=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;r=2,o/=2,c/=2,n/=2}function u(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(i){var d=-1;for(a=n;ao&&(n=o-c),a=n;a>=0;a--){for(var l=!0,f=0;fi&&(s=i):s=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");s>a/2&&(s=a/2);for(var r=0;r>8,i=n%256,a.push(i),a.push(s);return a}(t,e.length-n),e,n,s)}function C(e,t,n){return 0===t&&n===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,n))}function S(e,t,n){n=Math.min(e.length,n);for(var s=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+l<=n)switch(l){case 1:u<128&&(d=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(d=c);break;case 3:a=e[i+1],r=e[i+2],128==(192&a)&&128==(192&r)&&(c=(15&u)<<12|(63&a)<<6|63&r)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:a=e[i+1],r=e[i+2],o=e[i+3],128==(192&a)&&128==(192&r)&&128==(192&o)&&(c=(15&u)<<18|(63&a)<<12|(63&r)<<6|63&o)>65535&&c<1114112&&(d=c)}null===d?(d=65533,l=1):d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|1023&d),s.push(d),i+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",s=0;for(;s0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,s,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||n>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=n)return 0;if(s>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(i>>>=0)-(s>>>=0),r=(n>>>=0)-(t>>>=0),o=Math.min(a,r),u=this.slice(s,i),d=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var a=!1;;)switch(s){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return v(this,e,t,n);case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(e,t,n){var s="";n=Math.min(e.length,n);for(var i=t;is)&&(n=s);for(var i="",a=t;an)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,s,i,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function T(e,t,n,s){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-n,2);i>>8*(s?i:1-i)}function D(e,t,n,s){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-n,4);i>>8*(s?i:3-i)&255}function B(e,t,n,s,i,a){if(n+s>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function x(e,t,n,s,a){return a||B(e,0,n,4),i.write(e,t,n,s,23,4),n+4}function j(e,t,n,s,a){return a||B(e,0,n,8),i.write(e,t,n,s,52,8),n+8}c.prototype.slice=function(e,t){var n,s=this.length;if((e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(t=void 0===t?s:~~t)<0?(t+=s)<0&&(t=0):t>s&&(t=s),t0&&(i*=256);)s+=this[e+--t]*i;return s},c.prototype.readUInt8=function(e,t){return t||U(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||U(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||U(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=this[e],i=1,a=0;++a=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=t,i=1,a=this[e+--s];s>0&&(i*=256);)a+=this[e+--s]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||U(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||U(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,s){(e=+e,t|=0,n|=0,s)||O(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=0,r=1,o=0;for(this[t]=255&e;++a>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=n-1,r=1,o=0;for(this[t+a]=255&e;--a>=0&&(r*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/r>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,s){if(n||(n=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(a<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(r+1===s){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function L(e){return s.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,s){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(43))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return o}));var s=n(0);function i(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:i}=e;return{...a(e.user),fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,...i&&{botDescription:i.description}}}}function a(e){if(!(e instanceof s.Api.User))return;const{id:t,firstName:n,lastName:i}=e,a=e.photo instanceof s.Api.UserProfilePhoto?String(e.photo.photoId):void 0;return{id:t,isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:r(e),...n&&{firstName:n},...i&&{lastName:i},username:e.username||"",phoneNumber:e.phone||"",status:o(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a}}}function r(e){return e.bot?"userTypeBot":e.deleted?"userTypeDeleted":"userTypeRegular"}function o(e){return!e||e instanceof s.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof s.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof s.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof s.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof s.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}},function(e,t,n){"use strict";function s(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function i(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function a(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a}))},function(e,t,n){(function(e){var s,i=function(e){"use strict";var t=1e7,n=9007199254740992,s=l(n),a="function"==typeof BigInt;function r(e,t,n,s){return void 0===e?r[0]:void 0!==t&&(10!=+t||n)?F(e,t,n,s):z(e)}function o(e,t){this.value=e,this.sign=t,this.isSmall=!1}function c(e){this.value=e,this.sign=e<0,this.isSmall=!0}function u(e){this.value=e}function d(e){return-n0?Math.floor(e):Math.ceil(e)}function m(e,n){var s,i,a=e.length,r=n.length,o=new Array(a),c=0,u=t;for(i=0;i=u?1:0,o[i]=s-c*u;for(;i0&&o.push(c),o}function y(e,t){return e.length>=t.length?m(e,t):m(t,e)}function b(e,n){var s,i,a=e.length,r=new Array(a),o=t;for(i=0;i0;)r[i++]=n%o,n=Math.floor(n/o);return r}function _(e,t){var n,s,i=e.length,a=t.length,r=new Array(i),o=0;for(n=0;n0;)r[i++]=c%o,c=Math.floor(c/o);return r}function I(e,t){for(var n=[];t-- >0;)n.push(0);return n.concat(e)}function P(e,n,s){return new o(e=0;--n)i=(a=1e7*i+e[n])-(s=h(a/t))*t,o[n]=0|s;return[o,0|i]}function M(e,n){var s,i=z(n);if(a)return[new u(e.value/i.value),new u(e.value%i.value)];var d,m=e.value,y=i.value;if(0===y)throw new Error("Cannot divide by zero");if(e.isSmall)return i.isSmall?[new c(h(m/y)),new c(m%y)]:[r[0],e];if(i.isSmall){if(1===y)return[e,r[0]];if(-1==y)return[e.negate(),r[0]];var b=Math.abs(y);if(b=0;i--){for(s=p-1,b[i+l]!==m&&(s=Math.floor((b[i+l]*p+b[i+l-1])/m)),a=0,r=0,c=_.length,o=0;oc&&(i=1e7*(i+1)),n=Math.ceil(i/a);do{if(k(r=A(t,n),d)<=0)break;n--}while(n);u.push(n),d=_(d,r)}return u.reverse(),[f(u),f(d)]}(m,y))[0];var I=e.sign!==i.sign,P=s[1],C=e.sign;return"number"==typeof d?(I&&(d=-d),d=new c(d)):d=new o(d,I),"number"==typeof P?(C&&(P=-P),P=new c(P)):P=new o(P,C),[d,P]}function k(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}function E(e){var t=e.abs();return!t.isUnit()&&(!!(t.equals(2)||t.equals(3)||t.equals(5))||!(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))&&(!!t.lesser(49)||void 0))}function R(e,t){for(var n,s,a,r=e.prev(),o=r,c=0;o.isEven();)o=o.divide(2),c++;e:for(s=0;s=0?s=_(e,t):(s=_(t,e),n=!n),"number"==typeof(s=f(s))?(n&&(s=-s),new c(s)):new o(s,n)}(n,s,this.sign)},o.prototype.minus=o.prototype.subtract,c.prototype.subtract=function(e){var t=z(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var s=t.value;return t.isSmall?new c(n-s):w(s,Math.abs(n),n>=0)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(e){return new u(this.value-z(e).value)},u.prototype.minus=u.prototype.subtract,o.prototype.negate=function(){return new o(this.value,!this.sign)},c.prototype.negate=function(){var e=this.sign,t=new c(-this.value);return t.sign=!e,t},u.prototype.negate=function(){return new u(-this.value)},o.prototype.abs=function(){return new o(this.value,!1)},c.prototype.abs=function(){return new c(Math.abs(this.value))},u.prototype.abs=function(){return new u(this.value>=0?this.value:-this.value)},o.prototype.multiply=function(e){var n,s,i,a=z(e),c=this.value,u=a.value,d=this.sign!==a.sign;if(a.isSmall){if(0===u)return r[0];if(1===u)return this;if(-1===u)return this.negate();if((n=Math.abs(u))0?function e(t,n){var s=Math.max(t.length,n.length);if(s<=30)return v(t,n);s=Math.ceil(s/2);var i=t.slice(s),a=t.slice(0,s),r=n.slice(s),o=n.slice(0,s),c=e(a,o),u=e(i,r),d=e(y(a,i),y(o,r)),l=y(y(c,I(_(_(d,c),u),s)),I(u,2*s));return p(l),l}(c,u):v(c,u),d)},o.prototype.times=o.prototype.multiply,c.prototype._multiplyBySmall=function(e){return d(e.value*this.value)?new c(e.value*this.value):P(Math.abs(e.value),l(Math.abs(this.value)),this.sign!==e.sign)},o.prototype._multiplyBySmall=function(e){return 0===e.value?r[0]:1===e.value?this:-1===e.value?this.negate():P(Math.abs(e.value),this.value,this.sign!==e.sign)},c.prototype.multiply=function(e){return z(e)._multiplyBySmall(this)},c.prototype.times=c.prototype.multiply,u.prototype.multiply=function(e){return new u(this.value*z(e).value)},u.prototype.times=u.prototype.multiply,o.prototype.square=function(){return new o(C(this.value),!1)},c.prototype.square=function(){var e=this.value*this.value;return d(e)?new c(e):new o(C(l(Math.abs(this.value))),!1)},u.prototype.square=function(e){return new u(this.value*this.value)},o.prototype.divmod=function(e){var t=M(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=c.prototype.divmod=o.prototype.divmod,o.prototype.divide=function(e){return M(this,e)[0]},u.prototype.over=u.prototype.divide=function(e){return new u(this.value/z(e).value)},c.prototype.over=c.prototype.divide=o.prototype.over=o.prototype.divide,o.prototype.mod=function(e){return M(this,e)[1]},u.prototype.mod=u.prototype.remainder=function(e){return new u(this.value%z(e).value)},c.prototype.remainder=c.prototype.mod=o.prototype.remainder=o.prototype.mod,o.prototype.pow=function(e){var t,n,s,i=z(e),a=this.value,o=i.value;if(0===o)return r[1];if(0===a)return r[0];if(1===a)return r[1];if(-1===a)return i.isEven()?r[1]:r[-1];if(i.sign)return r[0];if(!i.isSmall)throw new Error("The exponent "+i.toString()+" is too large.");if(this.isSmall&&d(t=Math.pow(a,o)))return new c(h(t));for(n=this,s=r[1];!0&o&&(s=s.times(n),--o),0!==o;)o/=2,n=n.square();return s},c.prototype.pow=o.prototype.pow,u.prototype.pow=function(e){var t=z(e),n=this.value,s=t.value,i=BigInt(0),a=BigInt(1),o=BigInt(2);if(s===i)return r[1];if(n===i)return r[0];if(n===a)return r[1];if(n===BigInt(-1))return t.isEven()?r[1]:r[-1];if(t.isNegative())return new u(i);for(var c=this,d=r[1];(s&a)===a&&(d=d.times(c),--s),s!==i;)s/=o,c=c.square();return d},o.prototype.modPow=function(e,t){if(e=z(e),(t=z(t)).isZero())throw new Error("Cannot take modPow with modulus 0");var n=r[1],s=this.mod(t);for(e.isNegative()&&(e=e.multiply(r[-1]),s=s.modInv(t));e.isPositive();){if(s.isZero())return r[0];e.isOdd()&&(n=n.multiply(s).mod(t)),e=e.divide(2),s=s.square().mod(t)}return n},u.prototype.modPow=c.prototype.modPow=o.prototype.modPow,o.prototype.compareAbs=function(e){var t=z(e),n=this.value,s=t.value;return t.isSmall?1:k(n,s)},c.prototype.compareAbs=function(e){var t=z(e),n=Math.abs(this.value),s=t.value;return t.isSmall?n===(s=Math.abs(s))?0:n>s?1:-1:-1},u.prototype.compareAbs=function(e){var t=this.value,n=z(e).value;return(t=t>=0?t:-t)===(n=n>=0?n:-n)?0:t>n?1:-1},o.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:k(n,s)*(this.sign?-1:1)},o.prototype.compareTo=o.prototype.compare,c.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return t.isSmall?n==s?0:n>s?1:-1:n<0!==t.sign?n<0?-1:1:n<0?1:-1},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,n=z(e).value;return t===n?0:t>n?1:-1},u.prototype.compareTo=u.prototype.compare,o.prototype.equals=function(e){return 0===this.compare(e)},u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals=o.prototype.eq=o.prototype.equals,o.prototype.notEquals=function(e){return 0!==this.compare(e)},u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals=o.prototype.neq=o.prototype.notEquals,o.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater=o.prototype.gt=o.prototype.greater,o.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser=o.prototype.lt=o.prototype.lesser,o.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals=o.prototype.geq=o.prototype.greaterOrEquals,o.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals=o.prototype.leq=o.prototype.lesserOrEquals,o.prototype.isEven=function(){return 0==(1&this.value[0])},c.prototype.isEven=function(){return 0==(1&this.value)},u.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},o.prototype.isOdd=function(){return 1==(1&this.value[0])},c.prototype.isOdd=function(){return 1==(1&this.value)},u.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},o.prototype.isPositive=function(){return!this.sign},c.prototype.isPositive=function(){return this.value>0},u.prototype.isPositive=c.prototype.isPositive,o.prototype.isNegative=function(){return this.sign},c.prototype.isNegative=function(){return this.value<0},u.prototype.isNegative=c.prototype.isNegative,o.prototype.isUnit=function(){return!1},c.prototype.isUnit=function(){return 1===Math.abs(this.value)},u.prototype.isUnit=function(){return this.abs().value===BigInt(1)},o.prototype.isZero=function(){return!1},c.prototype.isZero=function(){return 0===this.value},u.prototype.isZero=function(){return this.value===BigInt(0)},o.prototype.isDivisibleBy=function(e){var t=z(e);return!t.isZero()&&(!!t.isUnit()||(0===t.compareAbs(2)?this.isEven():this.mod(t).isZero()))},u.prototype.isDivisibleBy=c.prototype.isDivisibleBy=o.prototype.isDivisibleBy,o.prototype.isPrime=function(e){var t=E(this);if(void 0!==t)return t;var n=this.abs(),s=n.bitLength();if(s<=64)return R(n,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var a=Math.log(2)*s.toJSNumber(),r=Math.ceil(!0===e?2*Math.pow(a,2):a),o=[],c=0;c-n?new c(e-1):new o(s,!0)},u.prototype.prev=function(){return new u(this.value-BigInt(1))};for(var U=[1];2*U[U.length-1]<=t;)U.push(2*U[U.length-1]);var O=U.length,T=U[O-1];function D(e){return Math.abs(e)<=t}function B(e,t,n){t=z(t);for(var s=e.isNegative(),a=t.isNegative(),r=s?e.not():e,o=a?t.not():t,c=0,u=0,d=null,l=null,f=[];!r.isZero()||!o.isZero();)c=(d=M(r,T))[1].toJSNumber(),s&&(c=T-1-c),u=(l=M(o,T))[1].toJSNumber(),a&&(u=T-1-u),r=d[0],o=l[0],f.push(n(c,u));for(var p=0!==n(s?1:0,a?1:0)?i(-1):i(0),g=f.length-1;g>=0;g-=1)p=p.multiply(T).add(i(f[g]));return p}o.prototype.shiftLeft=function(e){var t=z(e).toJSNumber();if(!D(t))throw new Error(String(t)+" is too large for shifting.");if(t<0)return this.shiftRight(-t);var n=this;if(n.isZero())return n;for(;t>=O;)n=n.multiply(T),t-=O-1;return n.multiply(U[t])},u.prototype.shiftLeft=function(e){return e=z(e),new u(this.value<=O;){if(s.isZero()||s.isNegative()&&s.isUnit())return s;s=(t=M(s,T))[1].isNegative()?t[0].prev():t[0],n-=O-1}return(t=M(s,U[n]))[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=function(e){return e=z(e),new u(this.value>>e.value)},c.prototype.shiftRight=o.prototype.shiftRight,o.prototype.not=function(){return this.negate().prev()},u.prototype.not=c.prototype.not=o.prototype.not,o.prototype.and=function(e){return B(this,e,(function(e,t){return e&t}))},u.prototype.and=c.prototype.and=o.prototype.and,o.prototype.or=function(e){return B(this,e,(function(e,t){return e|t}))},u.prototype.or=c.prototype.or=o.prototype.or,o.prototype.xor=function(e){return B(this,e,(function(e,t){return e^t}))},u.prototype.xor=c.prototype.xor=o.prototype.xor;function x(e){var n=e.value,s="number"==typeof n?n|1<<30:"bigint"==typeof n?n|BigInt(1<<30):n[0]+n[1]*t|1073758208;return s&-s}function j(e,t){return e=z(e),t=z(t),e.greater(t)?e:t}function N(e,t){return e=z(e),t=z(t),e.lesser(t)?e:t}function V(e,t){if(e=z(e).abs(),t=z(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var n,s,i=r[1];e.isEven()&&t.isEven();)n=N(x(e),x(t)),e=e.divide(n),t=t.divide(n),i=i.multiply(n);for(;e.isEven();)e=e.divide(x(e));do{for(;t.isEven();)t=t.divide(x(t));e.greater(t)&&(s=t,t=e,e=s),t=t.subtract(e)}while(!t.isZero());return i.isUnit()?e:e.multiply(i)}o.prototype.bitLength=function(){var e=this;return e.compareTo(i(0))<0&&(e=e.negate().subtract(i(1))),0===e.compareTo(i(0))?i(0):i(function e(t,n){if(n.compareTo(t)<=0){var s=e(t,n.square(n)),a=s.p,r=s.e,o=a.multiply(n);return o.compareTo(t)<=0?{p:o,e:2*r+1}:{p:a,e:2*r}}return{p:i(1),e:0}}(e,i(2)).e).add(i(1))},u.prototype.bitLength=c.prototype.bitLength=o.prototype.bitLength;var F=function(e,t,n,s){n=n||"0123456789abcdefghijklmnopqrstuvwxyz",e=String(e),s||(e=e.toLowerCase(),n=n.toLowerCase());var i,a=e.length,r=Math.abs(t),o={};for(i=0;i=r)){if("1"===d&&1===r)continue;throw new Error(d+" is not a valid digit in base "+t+".")}}t=z(t);var c=[],u="-"===e[0];for(i=u?1:0;i"!==e[i]&&i=0;s--)i=i.add(e[s].times(a)),a=a.times(t);return n?i.negate():i}function q(e,t){if((t=i(t)).isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var n=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return n.unshift([1]),{value:[].concat.apply([],n),isNegative:!1}}var s=!1;if(e.isNegative()&&t.isPositive()&&(s=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:s};for(var a,r=[],o=e;o.isNegative()||o.compareAbs(t)>=0;){a=o.divmod(t),o=a.quotient;var c=a.remainder;c.isNegative()&&(c=t.minus(c).abs(),o=o.next()),r.push(c.toJSNumber())}return r.push(o.toJSNumber()),{value:r.reverse(),isNegative:s}}function H(e,t,n){var s=q(e,t);return(s.isNegative?"-":"")+s.value.map((function(e){return function(e,t){return e<(t=t||"0123456789abcdefghijklmnopqrstuvwxyz").length?t[e]:"<"+e+">"}(e,n)})).join("")}function K(e){if(d(+e)){var t=+e;if(t===h(t))return a?new u(BigInt(t)):new c(t);throw new Error("Invalid integer: "+e)}var n="-"===e[0];n&&(e=e.slice(1));var s=e.split(/e/i);if(s.length>2)throw new Error("Invalid integer: "+s.join("e"));if(2===s.length){var i=s[1];if("+"===i[0]&&(i=i.slice(1)),(i=+i)!==h(i)||!d(i))throw new Error("Invalid integer: "+i+" is not a valid exponent.");var r=s[0],l=r.indexOf(".");if(l>=0&&(i-=r.length-l-1,r=r.slice(0,l)+r.slice(l+1)),i<0)throw new Error("Cannot include negative exponent part for integers");e=r+=new Array(i+1).join("0")}if(!/^([0-9][0-9]*)$/.test(e))throw new Error("Invalid integer: "+e);if(a)return new u(BigInt(n?"-"+e:e));for(var f=[],g=e.length,m=g-7;g>0;)f.push(+e.slice(m,g)),(m-=7)<0&&(m=0),g-=7;return p(f),new o(f,n)}function z(e){return"number"==typeof e?function(e){if(a)return new u(BigInt(e));if(d(e)){if(e!==h(e))throw new Error(e+" is not an integer.");return new c(e)}return K(e.toString())}(e):"string"==typeof e?K(e):"bigint"==typeof e?new u(e):e}o.prototype.toArray=function(e){return q(this,e)},c.prototype.toArray=function(e){return q(this,e)},u.prototype.toArray=function(e){return q(this,e)},o.prototype.toString=function(e,t){if(void 0===e&&(e=10),10!==e)return H(this,e,t);for(var n,s=this.value,i=s.length,a=String(s[--i]);--i>=0;)n=String(s[i]),a+="0000000".slice(n.length)+n;return(this.sign?"-":"")+a},c.prototype.toString=function(e,t){return void 0===e&&(e=10),10!=e?H(this,e,t):String(this.value)},u.prototype.toString=c.prototype.toString,u.prototype.toJSON=o.prototype.toJSON=c.prototype.toJSON=function(){return this.toString()},o.prototype.valueOf=function(){return parseInt(this.toString(),10)},o.prototype.toJSNumber=o.prototype.valueOf,c.prototype.valueOf=function(){return this.value},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=u.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var G=0;G<1e3;G++)r[G]=z(G),G>0&&(r[-G]=z(-G));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=j,r.min=N,r.gcd=V,r.lcm=function(e,t){return e=z(e).abs(),t=z(t).abs(),e.divide(V(e,t)).multiply(t)},r.isInstance=function(e){return e instanceof o||e instanceof c||e instanceof u},r.randBetween=function(e,n,s){e=z(e),n=z(n);var i=s||Math.random,a=N(e,n),o=j(e,n).subtract(a).add(1);if(o.isSmall)return a.add(Math.floor(i()*o));for(var c=q(o,t).value,u=[],d=!0,l=0;l{r.resolve=e,r.reject=t})}function d(e=!1){return o({...y("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise((e,t)=>{r.resolve=e,r.reject=t})}function l(e){return o({...y("authorizationStateWaitPassword"),hint:e}),new Promise(e=>{r.resolve=e})}function f(){return o(y("authorizationStateWaitRegistration")),new Promise(e=>{r.resolve=e})}function p(e){return o({...y("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise((e,t)=>{r.reject=t})}function g(e){let t;if(e instanceof s.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?n+" hours":"an hour")}else t=a[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),o({"@type":"updateAuthorizationError",message:t})}function h(){o(y("authorizationStateReady"))}function m(e){o({"@type":"updateCurrentUser",currentUser:e})}function y(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function b(e){r.resolve&&r.resolve(e)}function _(e){r.resolve&&r.resolve(e)}function w(e){r.resolve&&r.resolve(e)}function v(e){const{firstName:t,lastName:n}=e;r.resolve&&r.resolve([t,n])}function A(){r.reject&&r.reject(new Error("RESTART_AUTH"))}function I(){r.reject&&r.reject(new Error("RESTART_AUTH_WITH_QR"))}},function(e,t,n){"use strict";function s(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function i(e){if(!e)return;const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:i,classType:a,...r}=e;return r}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i}))},function(e,t,n){"use strict";n.d(t,"e",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return f}));var s=n(0),i=n(20),a=n(18);function r(e,t,n){return''.replace("{{path}}",function(e){let t="M";const n=e.length;for(let s=0;s=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[n-128-64]:(n>=128?t+=",":n>=64&&(t+="-"),t+=String(63&n))}return t+="z",t}(e)).replace("{{width}}",String(t)).replace("{{height}}",String(n))}const o={w:100,h:100};function c(e,t){if(!e||!e.length)return;const n=e.find(e=>e instanceof s.Api.PhotoStrippedSize);if(!n)return;const r=e.filter(e=>e instanceof s.Api.PhotoSize),{w:c,h:u}=r&&r.length?r[r.length-1]:o,{bytes:d}=n;return{dataUri:Object(a.a)(t&&"image/jpeg"!==t?d:Object(i.strippedPhotoToJpg)(d),void 0,t),width:c,height:u}}function u(e){const{w:t,h:n,bytes:s}=e;return{dataUri:Object(a.a)(s,void 0,"image/webp"),width:t,height:n}}function d(e,t){const{w:n,h:s}=t;return{dataUri:"data:image/svg+xml;utf8,"+r(e.bytes,n,s),width:n,height:s}}function l(e){const t=e.sizes.filter(e=>e instanceof s.Api.PhotoSize||e instanceof s.Api.PhotoSizeProgressive).map(f);return{id:String(e.id),thumbnail:c(e.sizes),sizes:t}}function f(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}},function(e,t,n){(function(t){const{constructors:s}=n(21),i=t.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),a=t.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error("Invalid message type: "+e.constructor.name)}},getInputPeer:function e(t,n=!0,i=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof s.User){if(t.isSelf&&n)return new s.InputPeerSelf;if(void 0===t.accessHash&&i)throw new Error("User without accessHash or min info cannot be input");return new s.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof s.Chat||t instanceof s.ChatEmpty||t instanceof s.ChatForbidden)return new s.InputPeerChat({chatId:t.id});if(t instanceof s.Channel){if(void 0===t.accessHash&&i)throw new TypeError("Channel without accessHash or min info cannot be input");return new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof s.ChannelForbidden?new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof s.InputUser?new s.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof s.InputChannel?new s.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof s.UserEmpty?new s.InputPeerEmpty:t instanceof s.UserFull?e(t.user):t instanceof s.ChatFull?new s.InputPeerChat({chatId:t.id}):t instanceof s.PeerChat?new s.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof s.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof s.Chat||e instanceof s.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=1572864e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const n=t.from(i);return n[164]=e[1],n[166]=e[2],t.concat([n,e.slice(3),a])},getDC:function(e){switch(e){case 1:return{id:1,ipAddress:"pluto.web.telegram.org",port:443};case 2:return{id:2,ipAddress:"venus.web.telegram.org",port:443};case 3:return{id:3,ipAddress:"aurora.web.telegram.org",port:443};case 4:return{id:4,ipAddress:"vesta.web.telegram.org",port:443};case 5:return{id:5,ipAddress:"flora.web.telegram.org",port:443};default:throw new Error("Cannot find the DC with the ID of "+e)}}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(6),{serializeBytes:i,serializeDate:a}=n(44);e.exports={constructors:s,requests:s,serializeBytes:i,serializeDate:a}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return u}));var s=n(0),i=n(4),a=n(19),r=n(5);function o(e){if(e instanceof s.Api.DocumentEmpty)return;const t=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeSticker);if(!t)return;const n=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeImageSize),r=t.stickerset,o=t.alt,c="application/x-tgsticker"===e.mimeType,u=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoCachedSize),d=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoPathSize),l=u?Object(a.c)(u):d&&n?Object(a.d)(d,n):void 0,{w:f,h:p}=u||n||{};return{id:String(e.id),stickerSetId:r.id?String(r.id):i.s,stickerSetAccessHash:String(r.accessHash),emoji:o,isAnimated:c,width:f,height:p,thumbnail:l}}function c(e){const{archived:t,animated:n,installedDate:s,id:i,accessHash:a,title:r,thumbs:o,count:c,hash:u}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(i),accessHash:String(a),title:r,hasThumbnail:Boolean(o&&o.length),count:c,hash:u}}function u(e){const t=c(e.set),n=e instanceof s.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach(e=>{if(e instanceof s.Api.Document){const n=o(e);n&&(t.covers.push(n),r.a.documents[String(e.id)]=e)}}),t}},function(e,t){class n extends Error{constructor(){super("The read operation was cancelled.")}}class s extends Error{constructor(e,t){super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${e}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${t.length}`),"undefined"!=typeof alert&&alert("Missing MTProto Entity: Please, make sure to add TL definition for ID "+e),this.invalidConstructorId=e,this.remaining=t}}class i extends Error{constructor(e,t){super(`Invalid checksum (${e} when ${t} was expected). This packet should be skipped.`),this.checksum=e,this.validChecksum=t}}class a extends Error{constructor(e){let t;4===e.length?(t=-e.readInt32LE(0),super(`Invalid response buffer (HTTP code ${t})`)):super(`Invalid response buffer (too short ${e})`),this.code=t,this.payload=e}}class r extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=" Caused by "+e.className,super(n),this.message=n,this.code=t}}var c,u,d;d={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).",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).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",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).",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).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",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).",64:"Invalid container."},(u="ErrorMessages")in(c=o)?Object.defineProperty(c,u,{value:d,enumerable:!0,configurable:!0,writable:!0}):c[u]=d,e.exports={ReadCancelledError:n,TypeNotFoundError:s,InvalidChecksumError:i,InvalidBufferError:a,SecurityError:r,CdnFileTamperedError:class extends r{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return u}));var s=n(0),i=n(9),a=n(14);function r(e){if(e instanceof s.Api.WallPaperNoFile)return;const{slug:t}=e,n=Object(i.a)(e.document);return n?{slug:t,document:n}:void 0}function o(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...Object(a.b)(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function c(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}function u(e){let t,n,i,a,r;return e.forEach(e=>{e instanceof s.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof s.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof s.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof s.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof s.Api.PrivacyValueAllowUsers?n=e.users:e instanceof s.Api.PrivacyValueDisallowUsers?a=e.users:e instanceof s.Api.PrivacyValueAllowChatParticipants?i=e.chats.map(e=>-e):e instanceof s.Api.PrivacyValueDisallowChatParticipants&&(r=e.chats.map(e=>-e))}),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:i||[],blockUserIds:a||[],blockChatIds:r||[]}}},function(e,t,n){const{TypeNotFoundError:s}=n(23),{coreObjects:i}=n(54),{tlobjects:a}=n(49),{readBigIntFromBuffer:r}=n(8);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return r(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error("Invalid boolean code "+e.toString("16"))}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=a[e];if(void 0===t){if(2574415285===e)return!0;if(3162085175===e)return!1;if(481674261===e){const e=[],t=this.readInt();for(let n=0;ne instanceof s.Api.User).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}),n.filter(e=>e instanceof s.Api.Chat||e instanceof s.Api.Channel).map(e=>Object(r.d)(e)).forEach(e=>{e&&h({"@type":"updateChat",id:e.id,chat:e})})),e instanceof s.Api.UpdateNewScheduledMessage?h({"@type":y.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):h({"@type":y.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t}),e.message instanceof s.Api.MessageService){const{action:n}=e.message;if(n instanceof s.Api.MessageActionChatEditTitle)h({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof s.Api.MessageActionChatEditPhoto){const i=Object(c.c)(n.photo),a=Object(r.e)(i),o=Math.abs(Object(f.c)(e.message));u.a.chats[o]&&(u.a.chats[o].photo=i),Object(f.b)(n.photo),a&&h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof s.Api.Photo&&{newProfilePhoto:Object(g.a)(n.photo)}})}else if(n instanceof s.Api.MessageActionChatDeletePhoto){const n=Math.abs(Object(f.c)(e.message));u.a.chats[n]&&(u.a.chats[n].photo=new s.Api.ChatPhotoEmpty),h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof s.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&e.id===n.userId)&&h({"@type":"updateChatLeave",id:t.chatId}):n instanceof s.Api.MessageActionChatAddUser&&e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&n.users.includes(e.id))&&h({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof s.Api.UpdateEditMessage||e instanceof s.Api.UpdateEditChannelMessage){if(e.message instanceof s.Api.MessageEmpty)return void(l.g&&console.error("Unexpected update:",e.className,e));e.message instanceof s.Api.Message&&Object(c.t)(e.message)&&Object(f.a)(e.message);const t=Object(a.b)(e.message);h({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof s.Api.UpdateDeleteMessages)h({"@type":"deleteMessages",ids:e.messages});else if(e instanceof s.Api.UpdateDeleteScheduledMessages)h({"@type":"deleteScheduledMessages",ids:e.messages,chatId:Object(r.i)(e.peer)});else if(e instanceof s.Api.UpdateDeleteChannelMessages){const t=Object(r.j)({channelId:e.channelId}),n=e.messages,i=n.filter(e=>u.a.messages[`${t}-${e}`]),a=n.filter(e=>!u.a.messages[`${t}-${e}`]),o=n.map(e=>{const n=u.a.messages[`${t}-${e}`];return n&&n instanceof s.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0}).filter(Boolean);i.length&&h({"@type":"deleteMessages",ids:i,chatId:t}),o.length&&h({"@type":"deleteProfilePhotos",ids:o,chatId:t}),a.length&&setTimeout(()=>{h({"@type":"deleteMessages",ids:a,chatId:t})},1e3)}else if((t instanceof s.Api.messages.SendMessage||t instanceof s.Api.messages.SendMedia||t instanceof s.Api.messages.SendMultiMedia||t instanceof s.Api.messages.ForwardMessages)&&(e instanceof s.Api.UpdateMessageID||e instanceof s.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const i=n&&u.a.localMessages[n.toString()];if(!i)throw new Error("Local message not found");let r;if(e instanceof s.Api.UpdateShortSentMessage){i.content.text&&e.entities&&(r={text:Object(a.j)(i.content.text.text,e.entities)}),e.media&&(r={...r,...Object(a.i)(e.media)});const t=Object(c.m)(e.id,i.chatId,e);Object(c.t)(t)&&Object(f.a)(t)}y.add(e.id);const o="date"in e&&1e3*e.dateString.fromCharCode(...e))});else if(e instanceof s.Api.UpdateChannelMessageViews)h({"@type":"updateMessage",chatId:Object(r.j)({channelId:e.channelId}),id:e.id,message:{views:e.views}});else if(e instanceof s.Api.UpdateReadHistoryInbox)h({"@type":"updateChatInbox",id:Object(r.j)(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadHistoryOutbox)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateReadChannelInbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadChannelOutbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateDialogPinned&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChatPinned",id:Object(r.j)(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof s.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter(e=>e instanceof s.Api.DialogPeer).map(e=>Object(r.j)(e.peer)):[];h({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof s.Api.UpdateFolderPeers)e.folderPeers.forEach(e=>{const{folderId:t,peer:n}=e;h({"@type":"updateChatListType",id:Object(r.j)(n),folderId:t})});else if(e instanceof s.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Object(r.a)(n):void 0;h({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof s.Api.UpdateDialogFilterOrder)h({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof s.Api.UpdateChatParticipants){const t=Object(r.g)(e.participants);h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.participants.chatId}),replacedMembers:t})}else if(e instanceof s.Api.UpdateChatParticipantAdd){const t=Object(r.f)(Object(i.b)(e,["userId","inviterId","date"]));h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),addedMember:t})}else if(e instanceof s.Api.UpdateChatParticipantDelete){const{userId:t}=e;h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),deletedMemberId:t})}else if(e instanceof s.Api.UpdatePinnedMessages||e instanceof s.Api.UpdatePinnedChannelMessages){const t=e instanceof s.Api.UpdatePinnedMessages?e.peer:{channelId:e.channelId},n=Object(r.j)(t);h({"@type":"updatePinnedIds",chatId:n,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof s.Api.UpdateNotifySettings&&e.peer instanceof s.Api.NotifyPeer){const{silent:t,muteUntil:n,showPreviews:s,sound:i}=e.notifySettings,a=t||"number"==typeof n&&Date.now()<1e3*n;h({"@type":"updateNotifyExceptions",id:Object(r.j)(e.peer.peer),isMuted:a,...""===i&&{isSilent:!0},...void 0!==s&&{shouldShowPreviews:Boolean(s)}})}else if(e instanceof s.Api.UpdateUserTyping||e instanceof s.Api.UpdateChatUserTyping){const t=e instanceof s.Api.UpdateUserTyping?e.userId:Object(r.j)({chatId:e.chatId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannelUserTyping){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find(e=>e instanceof s.Api.Channel||e instanceof s.Api.ChannelForbidden);if(n instanceof s.Api.Channel){const t=Object(r.d)(n);t&&(h({"@type":"updateChat",id:t.id,chat:t}),h({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:Object(r.j)({channelId:e.channelId})}))}else if(n instanceof s.Api.ChannelForbidden){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),h({"@type":"updateChatLeave",id:t})}else 0===t.length&&h({"@type":"resetMessages",id:Object(r.j)({chatId:e.channelId})})}else if(e instanceof s.Api.UpdateDialogUnreadMark&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChat",id:Object(r.j)(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof s.Api.UpdateChatDefaultBannedRights)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{defaultBannedRights:Object(d.b)(e.defaultBannedRights)}});else if(e instanceof s.Api.UpdateUserStatus){const{userId:t,status:n}=e;h({"@type":"updateUserStatus",userId:t,status:Object(o.c)(n)})}else if(e instanceof s.Api.UpdateUserName){const t=u.a.users[e.userId],n=t&&t.mutualContact&&!t.self?Object(i.b)(e,["username"]):Object(i.b)(e,["firstName","lastName","username"]);h({"@type":"updateUser",id:e.userId,user:n})}else if(e instanceof s.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=Object(r.e)(n);u.a.users[t]&&(u.a.users[t].photo=n),h({"@type":"updateUser",id:t,user:{avatarHash:s}})}else if(e instanceof s.Api.UpdateUserPhone){const{userId:t,phone:n}=e;h({"@type":"updateUser",id:t,user:{phoneNumber:n}})}else if(e instanceof s.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;t&&t.length&&(t.filter(e=>e instanceof s.Api.User&&!e.contact).forEach(e=>{h({"@type":"deleteUser",id:e.id})}),t.filter(e=>e instanceof s.Api.User&&e.contact).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}))}else if(e instanceof s.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:i}}=e,a="NotifyUsers"===i?"contact":"NotifyChats"===i?"group":"NotifyBroadcasts"===i?"broadcast":void 0;if(!a)return;h({"@type":"updateNotifySettings",peerType:a,isSilent:Boolean(n||"number"==typeof s&&Date.now()<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof s.Api.UpdatePeerBlocked)h({"@type":"updatePeerBlocked",id:Object(r.j)(e.peerId),isBlocked:e.blocked});else if(e instanceof s.Api.UpdatePrivacy){const t=Object(p.c)(e.key);t&&h({"@type":"updatePrivacy",key:t,rules:Object(p.d)(e.rules)})}else if(e instanceof s.Api.UpdateContactsReset)h({"@type":"updateResetContactList"});else if(e instanceof s.Api.UpdateFavedStickers)h({"@type":"updateFavoriteStickers"});else if(l.g){const t="object"==typeof e&&"className"in e?e.className:e;console.warn("[GramJs/updater] Unexpected update:",t)}}},function(e,t,n){const s=n(48);e.exports=class extends s{constructor(){super(),this._serverAddress=void 0,this._dcId=0,this._port=void 0,this._takeoutId=void 0,this._entities=new Set,this._updateStates={}}get dcId(){return this._dcId}get serverAddress(){return this._serverAddress}get port(){return this._port}get authKey(){return this._authKey}set authKey(e){this._authKey=e}setDC(e,t,n){this._dcId=0|e,this._serverAddress=t,this._port=n}}},function(e,t,n){(function(t){const{sha1:s,toSignedLittleBuffer:i,readBufferFromBigInt:a,readBigIntFromBuffer:r}=n(8),o=n(25),{sleep:c}=n(8);class u{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new o(t);this.auxHash=n.readLong(!1),n.read(4),this.keyId=n.readLong(!1)}async setKey(e){if(!e)return this._key=void 0,this.auxHash=void 0,this.keyId=void 0,void(this._hash=void 0);if(e instanceof u)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await s(this._key);const t=new o(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await c(20)}getKey(){return this._key}async calcNewNonceHash(e,n){e=i(e,32);const o=t.alloc(1);o.writeUInt8(n,0);const c=t.concat([e,t.concat([o,a(this.auxHash,8,!0)])]),u=(await s(c)).slice(4,20);return r(u,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=u}).call(this,n(12).Buffer)},function(e,t,n){const{RPCError:s}=n(36),{rpcErrorRe:i}=n(47);const a=n(23),r=n(36),o=n(47);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of i){const i=e.errorMessage.match(n);if(i){return new s({request:t,capture:2===i.length?parseInt(i[1],10):void 0})}}return new s(e.errorMessage,t)},...a,...r,...o}},function(e,t,n){"use strict";function s(e,t,n=!0){let s,i,a;return(...r)=>{i=!0,a=r,s||(n&&(i=!1,e(...a)),s=self.setInterval(()=>{if(!i)return self.clearInterval(s),void(s=void 0);i=!1,e(...a)},t))}}function i(e){return a(r,e)}function a(e,t){let n,s=!1;return(...i)=>{n=i,s||(s=!0,e(()=>{s=!1,t(...n)}))}}function r(e){Promise.resolve().then(e)}n.d(t,"b",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const o=e=>new Promise(t=>{setTimeout(()=>t(),e)})},function(e,t,n){(function(t){const s=n(15),{constructors:i}=n(21),{readBigIntFromBuffer:a,readBufferFromBigInt:r,sha256:o,bigIntMod:c,modExp:u,generateRandomBytes:d}=n(8),l=n(35);function f(e,n){if(!t.from([199,28,174,185,198,177,201,4,142,108,82,47,112,241,63,115,152,13,64,35,142,62,33,193,73,52,208,55,86,61,147,15,72,25,138,10,167,193,64,88,34,148,147,210,37,48,244,219,250,51,111,110,10,201,37,19,149,67,174,212,76,206,124,55,32,253,81,246,148,88,112,90,198,140,212,254,107,107,19,171,220,151,70,81,41,105,50,132,84,241,143,175,140,89,95,100,36,119,254,150,187,42,148,29,91,205,29,74,200,204,73,136,7,8,250,155,55,142,60,79,58,144,96,190,230,124,249,164,164,166,149,129,16,81,144,126,22,39,83,181,107,15,107,65,13,186,116,216,168,75,42,20,179,20,78,14,241,40,71,84,253,23,237,149,13,89,101,180,185,221,70,88,45,177,23,141,22,156,107,196,101,176,214,255,156,163,146,143,239,91,154,228,228,24,252,21,232,62,190,160,248,127,169,255,94,237,112,5,13,237,40,73,244,123,249,89,217,86,133,12,233,41,133,31,13,129,21,246,53,177,5,238,46,78,21,208,75,36,84,191,111,79,173,240,52,177,4,3,17,156,216,227,185,47,204,91]).equals(e)||![3,4,5,7].includes(n))throw new Error("Changing passwords unsupported")}function p(e){return t.concat([t.alloc(256-e.length),e])}function g(e){return r(e,256,!1)}function h(e,t){const n=t.subtract(e);return!(n.lesser(s(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function m(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=d(256),n=a(e,!1),i=u(s(_),n,b);if(h(i,b)){const e=g(i),r=a(await o(t.concat([e,P])),!1);if(r.greater(s(0)))return[n,e,r]}}})(),U=c(w.subtract(M),b);if(!h(U,b))throw new Error("bad gB");const O=R.multiply(v),T=k.add(O),D=u(U,T,b),[B,x,j,N,V]=await Promise.all([o(g(D)),o(A),o(I),o(r.salt1),o(r.salt2)]),F=await o(t.concat([m(x,j),N,V,E,P,B]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:t.from(E),M1:F})},computeDigest:async function(e,t){try{f(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return g(u(s(e.g),a(await y(e,t),!1),a(e.p,!1)))}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{inflate:i}=n(41),{serializeBytes:a}=n(21);class r{constructor(e){this.data=e,this.CONSTRUCTOR_ID=812830625,this.classType="constructor"}static async gzipIfSmaller(e,t){if(e&&t.length>512){const e=await new r(t).toBytes();if(e.length{const s=new FileReader;s.onload=e=>{const{result:s}=e.target||{};"string"==typeof s&&t(s),n(new Error("Failed to read blob"))},s.onerror=n,s.readAsDataURL(e)})}async function a(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}},function(e,t,n){(function(t){const s=n(45).default,{i2ab:i,ab2i:a}=n(77),{getWords:r}=n(78);class o{constructor(e){this.setBytes(e)}setBytes(e){e=t.from(e),this._counter=e}increment(){for(let e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}}}class c{constructor(e,t){t instanceof o||(t=new o(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new s(r(e))}update(e){return this.encrypt(e)}encrypt(e){const n=t.from(e);for(let e=0;e{s[e]&&r[e]&&(this._authKeys[e]=new i(t.from(s[e].data),t.from(r[e].data)))})}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey="GramJs-session-"+Date.now()),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(n=>{const s=this._authKeys[n];s._key&&(t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash)}),t}async _loadFromSessionString(){const[,e,n]=this._sessionString.split(":"),s=Number(e),{ipAddress:r,port:o}=a.getDC(s);this.setDC(s,r,o);const c=new i;await c.setKey(t.from(n,"hex"),!0),this.setAuthKey(c,s)}async _updateStorage(){if(this._storageKey)try{await this._saveToCache(JSON.stringify(this.getSessionData()))}catch(e){console.warn("Failed to update session in storage"),console.warn(e)}}async delete(){try{return await this._delete()}catch(e){console.warn("Failed to delete session from storage"),console.warn(e)}}_delete(){throw new Error("Not Implemented")}_fetchFromCache(){throw new Error("Not Implemented")}_saveToCache(e){throw new Error("Not Implemented")}}}).call(this,n(12).Buffer)},function(e,t,n){e.exports=function e(t,n,s){function i(r,o){if(!n[r]){if(!t[r]){if(a)return a(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[r]={exports:{}};t[r][0].call(u.exports,(function(e){return i(t[r][1][e]||e)}),u,u.exports,e,t,n,s)}return n[r].exports}for(var a=!1,r=0;r=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&a||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r>>6,t[r++]=128|63&n):n<65536?(t[r++]=224|n>>>12,t[r++]=128|n>>>6&63,t[r++]=128|63&n):(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63,t[r++]=128|n>>>6&63,t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n4)u[s++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?u[s++]=65533:i<65536?u[s++]=i:(i-=65536,u[s++]=55296|i>>10&1023,u[s++]=56320|1023&i)}return c(u,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,s){for(var i=65535&e|0,a=e>>>16&65535|0,r=0;0!==n;){n-=r=n>2e3?2e3:n;do{a=a+(i=i+t[s++]|0)|0}while(--r);i%=65521,a%=65521}return i|a<<16|0}},{}],4:[function(e,t,n){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){"use strict";var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=s,r=i+n;e^=-1;for(var o=i;o>>8^a[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,n){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){"use strict";t.exports=function(e,t){var n,s,i,a,r,o,c,u,d,l,f,p,g,h,m,y,b,_,w,v,A,I,P,C,S;n=e.state,s=e.next_in,C=e.input,i=s+(e.avail_in-5),a=e.next_out,S=e.output,r=a-(t-e.avail_out),o=a+(e.avail_out-257),c=n.dmax,u=n.wsize,d=n.whave,l=n.wnext,f=n.window,p=n.hold,g=n.bits,h=n.lencode,m=n.distcode,y=(1<>>=w=_>>>24,g-=w,0==(w=_>>>16&255))S[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=h[(65535&_)+(p&(1<>>=w,g-=w),g<15&&(p+=C[s++]<>>=w=_>>>24,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<c){e.msg="invalid distance too far back",n.mode=30;break e}if(p>>>=w,g-=w,A>(w=a-r)){if((w=A-w)>d&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(I=0,P=f,0===l){if(I+=u-w,w2;)S[a++]=P[I++],S[a++]=P[I++],S[a++]=P[I++],v-=3;v&&(S[a++]=P[I++],v>1&&(S[a++]=P[I++]))}else{I=a-A;do{S[a++]=S[I++],S[a++]=S[I++],S[a++]=S[I++],v-=3}while(v>2);v&&(S[a++]=S[I++],v>1&&(S[a++]=S[I++]))}break}}break}}while(s>3,p&=(1<<(g-=v<<3))-1,e.next_in=s,e.next_out=a,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(852),t.distcode=t.distdyn=new s.Buf32(592),t.sane=1,t.back=-1,0):-2}function l(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,d(e)):-2}function f(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?-2:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,l(e))):-2}function p(e,t){var n,s;return e?(s=new u,e.state=s,s.window=null,0!==(n=f(e,t))&&(e.state=null),n):-2}var g,h,m=!0;function y(e){if(m){var t;for(g=new s.Buf32(512),h=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(1,e.lens,0,288,g,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(2,e.lens,0,32,h,0,e.work,{bits:5}),m=!1}e.lencode=g,e.lenbits=9,e.distcode=h,e.distbits=5}function b(e,t,n,i){var a,r=e.state;return null===r.window&&(r.wsize=1<=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):((a=r.wsize-r.wnext)>i&&(a=i),s.arraySet(r.window,t,n-i,a,r.wnext),(i-=a)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,n.check=a(n.check,B,2,0),h=0,m=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&h)){e.msg="unknown compression method",n.mode=30;break}if(m-=4,R=8+(15&(h>>>=4)),0===n.wbits)n.wbits=R;else if(R>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=3;case 3:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>8&255,B[2]=h>>>16&255,B[3]=h>>>24&255,n.check=a(n.check,B,4,0)),h=0,m=0,n.mode=4;case 4:for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>8),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=5;case 5:if(1024&n.flags){for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((v=n.length)>p&&(v=p),v&&(n.head&&(R=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,u,l,v,R)),512&n.flags&&(n.check=a(n.check,u,v,l)),p-=v,l+=v,n.length-=v),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===p)break e;v=0;do{R=u[l+v++],n.head&&R&&n.length<65536&&(n.head.name+=String.fromCharCode(R))}while(R&&v>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>=7&m,m-=7&m,n.mode=27;break}for(;m<3;){if(0===p)break e;p--,h+=u[l++]<>>=1)){case 0:n.mode=14;break;case 1:if(y(n),n.mode=20,6===t){h>>>=2,m-=2;break e}break;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}h>>>=2,m-=2;break;case 14:for(h>>>=7&m,m-=7&m;m<32;){if(0===p)break e;p--,h+=u[l++]<>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&h,h=0,m=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(v=n.length){if(v>p&&(v=p),v>g&&(v=g),0===v)break e;s.arraySet(d,u,l,v,f),p-=v,l+=v,g-=v,f+=v,n.length-=v;break}n.mode=12;break;case 17:for(;m<14;){if(0===p)break e;p--,h+=u[l++]<>>=5,m-=5,n.ndist=1+(31&h),h>>>=5,m-=5,n.ncode=4+(15&h),h>>>=4,m-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,m-=3}for(;n.have<19;)n.lens[x[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,O={bits:n.lenbits},U=o(0,n.lens,0,19,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=P,m-=P,n.lens[n.have++]=S;else{if(16===S){for(T=P+2;m>>=P,m-=P,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}R=n.lens[n.have-1],v=3+(3&h),h>>>=2,m-=2}else if(17===S){for(T=P+3;m>>=P)),h>>>=3,m-=3}else{for(T=P+7;m>>=P)),h>>>=7,m-=7}if(n.have+v>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;v--;)n.lens[n.have++]=R}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,O={bits:n.lenbits},U=o(1,n.lens,0,n.nlen,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,O={bits:n.distbits},U=o(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,O),n.distbits=O.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(p>=6&&g>=258){e.next_out=f,e.avail_out=g,e.next_in=l,e.avail_in=p,n.hold=h,n.bits=m,r(e,w),f=e.next_out,d=e.output,g=e.avail_out,l=e.next_in,u=e.input,p=e.avail_in,h=n.hold,m=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;C=(D=n.lencode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,n.length=S,0===C){n.mode=26;break}if(32&C){n.back=-1,n.mode=12;break}if(64&C){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&C,n.mode=22;case 22:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;C=(D=n.distcode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,64&C){e.msg="invalid distance code",n.mode=30;break}n.offset=S,n.extra=15&C,n.mode=24;case 24:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===g)break e;if(v=w-g,n.offset>v){if((v=n.offset-v)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}v>n.wnext?(v-=n.wnext,A=n.wsize-v):A=n.wnext-v,v>n.length&&(v=n.length),I=n.window}else I=d,A=f-n.offset,v=n.length;v>g&&(v=g),g-=v,n.length-=v;do{d[f++]=I[A++]}while(--v);0===n.length&&(n.mode=21);break;case 26:if(0===g)break e;d[f++]=n.length,g--,n.mode=21;break;case 27:if(n.wrap){for(;m<32;){if(0===p)break e;p--,h|=u[l++]<=1&&0===B[S];S--);if(M>S&&(M=S),0===S)return u[d++]=20971520,u[d++]=20971520,f.bits=1,0;for(C=1;C0&&(0===e||1!==S))return-1;for(x[1]=0,I=1;I<15;I++)x[I+1]=x[I]+B[I];for(P=0;P852||2===e&&U>592)return 1;for(;;){_=I-E,l[P]b?(w=j[N+l[P]],v=T[D+l[P]]):(w=96,v=0),p=1<>E)+(g-=p)]=_<<24|w<<16|v|0}while(0!==g);for(p=1<>=1;if(0!==p?(O&=p-1,O+=p):O=0,P++,0==--B[I]){if(I===S)break;I=t[n+l[P]]}if(I>M&&(O&m)!==h){for(0===E&&(E=M),y+=C,R=1<<(k=I-E);k+E852||2===e&&U>592)return 1;u[h=O&m]=M<<24|k<<16|y-d|0}}return 0!==O&&(u[y+O]=I-E<<24|64<<16|0),f.bits=M,0}},{"../utils/common":1}],10:[function(e,t,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){"use strict";var s=e("./zlib/inflate"),i=e("./utils/common"),a=e("./utils/strings"),r=e("./zlib/constants"),o=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),d=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(o[n]);if(this.header=new u,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=a.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(o[n])}function f(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}l.prototype.push=function(e,t){var n,o,c,u,l,f=this.strm,p=this.options.chunkSize,g=this.options.dictionary,h=!1;if(this.ended)return!1;o=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?f.input=a.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?f.input=new Uint8Array(e):f.input=e,f.next_in=0,f.avail_in=f.input.length;do{if(0===f.avail_out&&(f.output=new i.Buf8(p),f.next_out=0,f.avail_out=p),(n=s.inflate(f,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===h&&(n=r.Z_OK,h=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),this.ended=!0,!1;f.next_out&&(0!==f.avail_out&&n!==r.Z_STREAM_END&&(0!==f.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=a.utf8border(f.output,f.next_out),u=f.next_out-c,l=a.buf2string(f.output,c),f.next_out=u,f.avail_out=p-u,u&&i.arraySet(f.output,f.output,c,u,0),this.onData(l)):this.onData(i.shrinkBuf(f.output,f.next_out)))),0===f.avail_in&&0===f.avail_out&&(h=!0)}while((f.avail_in>0||0===f.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),f.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=l,n.inflate=f,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},n.ungzip=f},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")},function(e,t,n){const s=n(46),i=n(58),a=n(25),r=n(60),o=n(57),c=n(61);e.exports={BinaryWriter:i,BinaryReader:a,MessagePacker:o,AsyncQueue:c,Logger:s,PromisedWebSockets:r}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){(function(t){const n=e=>e.replace(/(?:^|_)([a-z])/g,(e,t)=>t.toUpperCase()).replace(/_/g,""),s=e=>e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_","")),i=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),a=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let r;function o(e){r||(r=function(){let e;const t=[];for(let n=0;n<256;n++){e=n;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0}const c=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),c(e,t,n)),n},u=(e,i)=>{const a=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!a)throw new Error("Cannot parse TLObject "+e);const r=c(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),u={name:a[1],constructorId:parseInt(a[2],16),argsConfig:{},subclassOfId:o(a[3]),result:a[3],isFunction:i,namespace:void 0};if(!u.constructorId){const e="";let n;n=Object.values(u.argsConfig).length?" "+Object.keys(u.argsConfig).map(e=>e.toString()).join(" "):"";const s=`${u.name}${e}${n} = ${u.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===u.name&&u.name,u.constructorId=o(t.from(s,"utf8"))}for(const[e,t,n]of r)void 0===e&&(u.argsConfig[s(t)]=d(t,n));return u.name.includes(".")&&([u.namespace,u.name]=u.name.split(/\.(.+)/)),u.name=n(u.name),u};function d(e,t){e="self"===e?"is_self":e;const n={isVector:!1,isFlag:!1,skipConstructorId:!1,flagIndex:-1,flagIndicator:!0,type:void 0,useVectorId:void 0};if("#"!==t){n.flagIndicator=!1,n.type=t.replace(/^!+/,"");const e=n.type.match(/flags.(\d+)\?([\w<>.]+)/);e&&(n.isFlag=!0,n.flagIndex=Number(e[1]),[,,n.type]=e);const s=n.type.match(/[Vv]ector<([\w\d.]+)>/);s&&(n.isVector=!0,n.useVectorId="V"===n.type.charAt(0),[,n.type]=s),/^[a-z]$/.test(n.type.split(".").pop().charAt(0))&&(n.skipConstructorId=!0)}return n}e.exports={findAll:c,parseTl:function*(e,t,n=[],s=i){(n||[]).reduce((e,t)=>({...e,[t.name]:t}),{});const r=[],o={},c={},d=e;let l=!1;for(let e of d.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;l="functions"===e}else try{const t=u(e,l);if(s.has(t.constructorId))continue;r.push(t),t.isFunction||(c[t.result]||(c[t.result]=[]),o[t.name]=t,c[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of r)if(a.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of r)yield e},buildArgConfig:d,fromLine:u,CORE_TYPES:i,serializeDate:function(e){if(!e)return t.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const n=t.alloc(4);return n.writeInt32LE(e,0),n}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof t)){if("string"!=typeof e)throw Error("Bytes or str expected, not "+e.constructor.name);e=t.from(e)}const n=[];let s;return e.length<254?(s=(e.length+1)%4,0!==s&&(s=4-s),n.push(t.from([e.length])),n.push(e)):(s=e.length%4,0!==s&&(s=4-s),n.push(t.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),n.push(e)),n.push(t.alloc(s).fill(0)),t.concat(n)},snakeToCamelCase:n,variableSnakeToCamelCase:s}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"CTR",(function(){return y})),n.d(t,"IGE",(function(){return m}));var s=new Uint8Array(256),i=new Uint8Array(256),a=new Uint32Array(256),r=new Uint32Array(256),o=new Uint32Array(256),c=new Uint32Array(256),u=new Uint32Array(256),d=new Uint32Array(256),l=new Uint32Array(256),f=new Uint32Array(256);function p(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(var t=e.length%4;t<=4;t++)e+="\0x00";var n=new Uint32Array(e.length/4);for(t=0;t>7),m[h[_]^_]=_;for(;!s[y];y^=e||1)n=(n=b^b<<1^b<<2^b<<3^b<<4)>>8^255&n^99,s[y]=n,i[n]=y,g=16843009*h[t=h[e=h[y]]]^65537*t^257*e^16843008*y,p=257*h[n]^16843008*n,a[y]=p=p<<24^p>>>8,r[y]=p=p<<24^p>>>8,o[y]=p=p<<24^p>>>8,c[y]=p=p<<24^p>>>8,u[n]=g=g<<24^g>>>8,d[n]=g=g<<24^g>>>8,l[n]=g=g<<24^g>>>8,f[n]=g=g<<24^g>>>8,b=m[b]||1}();var h=function(){function e(e){var t=p(e);if(4!==t.length&&6!==t.length&&8!==t.length)throw new Error("Invalid key size");this.encKey=new Uint32Array(4*t.length+28),this.decKey=new Uint32Array(4*t.length+28),this.encKey.set(t);for(var n,i=1,a=t.length;a<4*t.length+28;a++)n=this.encKey[a-1],(a%t.length==0||8===t.length&&a%t.length==4)&&(n=s[n>>>24]<<24^s[n>>16&255]<<16^s[n>>8&255]<<8^s[255&n],a%t.length==0&&(n=n<<8^n>>>24^i<<24,i=i<<1^283*(i>>7))),this.encKey[a]=this.encKey[a-t.length]^n;for(var r=0;a;r++,a--)n=this.encKey[3&r?a:a-4],this.decKey[r]=a<=4||r<4?n:u[s[n>>>24]]^d[s[n>>16&255]]^l[s[n>>8&255]]^f[s[255&n]]}return e.prototype.encrypt=function(e){for(var t,n,i,u=p(e),d=new Uint32Array(4),l=u[0]^this.encKey[0],f=u[1]^this.encKey[1],g=u[2]^this.encKey[2],h=u[3]^this.encKey[3],m=this.encKey.length/4-2,y=4,b=0;b>>24]^r[f>>16&255]^o[g>>8&255]^c[255&h]^this.encKey[y],n=a[f>>>24]^r[g>>16&255]^o[h>>8&255]^c[255&l]^this.encKey[y+1],i=a[g>>>24]^r[h>>16&255]^o[l>>8&255]^c[255&f]^this.encKey[y+2],h=a[h>>>24]^r[l>>16&255]^o[f>>8&255]^c[255&g]^this.encKey[y+3],l=t,f=n,g=i,y+=4;for(b=0;b<4;b++)d[b]=s[l>>>24]<<24^s[f>>16&255]<<16^s[g>>8&255]<<8^s[255&h]^this.encKey[y++],t=l,l=f,f=g,g=h,h=t;return d},e.prototype.decrypt=function(e){for(var t,n,s,a=p(e),r=new Uint32Array(4),o=a[0]^this.decKey[0],c=a[3]^this.decKey[1],g=a[2]^this.decKey[2],h=a[1]^this.decKey[3],m=this.decKey.length/4-2,y=4,b=0;b>>24]^d[c>>16&255]^l[g>>8&255]^f[255&h]^this.decKey[y],n=u[c>>>24]^d[g>>16&255]^l[h>>8&255]^f[255&o]^this.decKey[y+1],s=u[g>>>24]^d[h>>16&255]^l[o>>8&255]^f[255&c]^this.decKey[y+2],h=u[h>>>24]^d[o>>16&255]^l[c>>8&255]^f[255&g]^this.decKey[y+3],o=t,c=n,g=s,y+=4;for(b=0;b<4;b++)r[3&-b]=i[o>>>24]<<24^i[c>>16&255]<<16^i[g>>8&255]<<8^i[255&h]^this.decKey[y++],t=o,o=c,c=g,g=h,h=t;return r},e}(),m=function(){function e(e,t,n){void 0===n&&(n=16),this.key=p(e),this.iv=p(t),this.cipher=new h(e),this.blockSize=n/4}return e.prototype.encrypt=function(e,t){for(var n=p(e),s=t||new Uint32Array(n.length),i=this.iv.subarray(this.blockSize,this.iv.length),a=this.iv.subarray(0,this.blockSize),r=new Uint32Array(this.blockSize),o=0;o=this.blockSize&&this.incrementCounter(),i&&(a-=i,i=0)}return this.offset=(this.offset+n.length%4)%4,s},e.prototype.decrypt=function(e,t){return this.encrypt(e,t)},e.prototype.incrementCounter=function(){for(var e=this.counter.length-1;e>=0&&!(++this.counter[e]<4294967295);e--);},e}();t.default=h},function(e,t,n){(function(t){let n;class s{constructor(e){n||(n=e||"debug"),this.isBrowser=void 0===t||"renderer"===t.type||!0===t.browser||t.__nwjs,this.isBrowser?this.colors={start:"%c",warn:"color : #ff00ff",info:"color : #ffff00",debug:"color : #00ffff",error:"color : #ff0000",end:""}:this.colors={start:"",warn:"",info:"",debug:"",error:"",end:""},this.messageFormat="[%t] [%l] - [%m]"}static setLevel(e){n=e}canSend(e){return s.levels.indexOf(n)>=s.levels.indexOf(e)}warn(e){this._log("warn",e,this.colors.warn)}info(e){this._log("info",e,this.colors.info)}debug(e){this._log("debug",e,this.colors.debug)}error(e){this._log("error",e,this.colors.error)}format(e,t){return this.messageFormat.replace("%t",(new Date).toISOString()).replace("%l",t.toUpperCase()).replace("%m",e)}_log(e,t,s){n&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(t,e),s):console.log(s+this.format(t,e)+this.colors.end))}}var i,a,r;r=["error","warn","info","debug"],(a="levels")in(i=s)?Object.defineProperty(i,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[a]=r,e.exports=s}).call(this,n(83))},function(e,t,n){const{RPCError:s,InvalidDCError:i,FloodError:a,BadRequestError:r}=n(36);class o extends i{constructor(e){const t=Number(e.capture||0);super(`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class c extends i{constructor(e){const t=Number(e.capture||0);super(`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class u extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`,this.seconds=t}}class d extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`,this.seconds=t}}class l extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`,this.seconds=t}}class f extends i{constructor(e){const t=Number(e.capture||0);super(`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`),this.message=`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class p extends i{constructor(e){const t=Number(e.capture||0);super(`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class g extends r{constructor(e){const t=Number(e.capture||0);super(`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`),this.message=`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`,this.codeLength=t}}const h=[[/FILE_MIGRATE_(\d+)/,f],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,l],[/FLOOD_WAIT_(\d+)/,d],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,u],[/USER_MIGRATE_(\d+)/,o],[/NETWORK_MIGRATE_(\d+)/,p],[/EMAIL_UNCONFIRMED_(\d+)/,g]];e.exports={rpcErrorRe:h,FileMigrateError:f,FloodTestPhoneWaitError:l,FloodWaitError:d,PhoneMigrateError:c,SlowModeWaitError:u,UserMigrateError:o,NetworkMigrateError:p,EmailUnconfirmedError:g}},function(e,t){e.exports=class{get dcId(){throw new Error("Not Implemented")}get serverAddress(){throw new Error("Not Implemented")}get port(){throw new Error("Not Implemented")}get authKey(){throw new Error("Not Implemented")}set authKey(e){throw new Error("Not Implemented")}setDC(e,t,n){throw new Error("Not implemented")}save(){throw new Error("Not Implemented")}delete(){throw new Error("Not Implemented")}}},function(e,t,n){const s=n(6),i={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)i[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))i[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:128,tlobjects:i}},function(e,t,n){const s=n(51),i=n(52),a=n(8),r=n(28),o=n(56),c=n(55),u=n(38),d=n(32),l=n(86),{MsgsAck:f,upload:p,MsgsStateInfo:g,Pong:h}=n(21).constructors,m=n(57),y=n(25),{UpdateConnectionState:b}=n(59),{BadMessageError:_}=n(23),{BadServerSalt:w,BadMsgNotification:v,MsgDetailedInfo:A,MsgNewDetailedInfo:I,NewSessionCreated:P,FutureSalts:C,MsgsStateReq:S,MsgResendReq:M,MsgsAllInfo:k}=n(21).constructors,{SecurityError:E}=n(23),{InvalidBufferError:R}=n(23),{LogOut:U}=n(21).requests.auth,{RPCMessageToError:O}=n(29),{TypeNotFoundError:T}=n(23);class D{constructor(e,t){const n={...D.DEFAULT_OPTIONS,...t};this._connection=void 0,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new r,this._state=new i(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[u.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[d.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[w.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[I.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[f.CONSTRUCTOR_ID]:this._handleAck.bind(this),[C.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[S.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this._connection=e;for(let e=0;e1024)throw new u("Server replied with the wrong message padding");const y=f.tgReadObject();return new c(p,g,y)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=s(Math.floor(e)).shiftLeft(s(32)).or(s(t).shiftLeft(s(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(s(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,i=Math.floor((new Date).getTime()/1e3),a=e.shiftRight(s(32));return this.timeOffset=a-i,this.timeOffset!==n&&(this._lastMsgId=s(0),this._log.debug(`Updated time offset (old offset ${n}, bad ${t}, good ${e}, new ${this.timeOffset})`)),this.timeOffset}_getSeqNo(e){if(e){const e=2*this._sequence+1;return this._sequence+=1,e}return 2*this._sequence}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const{IGE:s}=n(45),i=n(8);e.exports=class{constructor(e,t){this.ige=new s(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const n=e.length%16;return n&&(e=t.concat([e,i.generateRandomBytes(16-n)])),i.convertToLittle(this.ige.encrypt(e))}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(37),i=n(55),a=n(38),r=n(32),o={[i.CONSTRUCTOR_ID]:i,[r.CONSTRUCTOR_ID]:r,[a.CONSTRUCTOR_ID]:a};e.exports={TLMessage:s,RPCResult:i,MessageContainer:a,GZIPPacked:r,coreObjects:o}},function(e,t,n){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{RpcError:i}=n(21).constructors,a=n(32);class r{constructor(e,t,n){this.CONSTRUCTOR_ID=4082920705,this.reqMsgId=e,this.body=t,this.error=n,this.classType="constructor"}static async fromReader(e){const t=e.readLong(),n=e.readInt(!1);return n===i.CONSTRUCTOR_ID?new r(t,void 0,i.fromReader(e)):n===a.CONSTRUCTOR_ID?new r(t,(await a.fromReader(e)).data):(e.seek(-4),new r(t,e.read(),void 0))}}s(r,"CONSTRUCTOR_ID",4082920705),s(r,"classType","constructor"),e.exports=r},function(e,t,n){(function(t){const s=n(15),i=n(53),a=n(28),r=n(84),o=n(85),c=n(8),{constructors:u,requests:d}=n(21),l=n(25),{SecurityError:f}=n(23);e.exports=async function(e,n){let p=c.generateRandomBytes(16);const g=c.readBigIntFromBuffer(p,!1,!0),h=await e.send(new d.ReqPqMulti({nonce:g}));if(n.debug("Starting authKey generation step 1"),!(h instanceof u.ResPQ))throw new Error("Step 1 answer was "+h);if(h.nonce.neq(g))throw new f("Step 1 invalid nonce from server");const m=c.readBigIntFromBuffer(h.pq,!1,!0);n.debug("Finished authKey generation step 1"),n.debug("Starting authKey generation step 2");let{p:y,q:b}=r.factorize(m);y=c.getByteArray(y),b=c.getByteArray(b),p=c.generateRandomBytes(32);const _=c.readBigIntFromBuffer(p,!0,!0),w=new u.PQInnerData({pq:c.getByteArray(m),p:y,q:b,nonce:h.nonce,serverNonce:h.serverNonce,newNonce:_});let v,A;for(const e of h.serverPublicKeyFingerprints)if(v=await o.encrypt(e.toString(),w.getBytes()),void 0!==v){A=e;break}if(void 0===v)throw new f("Step 2 could not find a valid key for fingerprints");const I=await e.send(new d.ReqDHParams({nonce:h.nonce,serverNonce:h.serverNonce,p:y,q:b,publicKeyFingerprint:A,encryptedData:v}));if(!(I instanceof u.ServerDHParamsOk||I instanceof u.ServerDHParamsFail))throw new Error("Step 2.1 answer was "+I);if(I.nonce.neq(h.nonce))throw new f("Step 2 invalid nonce from server");if(I.serverNonce.neq(h.serverNonce))throw new f("Step 2 invalid server nonce from server");if(I instanceof u.ServerDHParamsFail){const e=await c.sha1(c.toSignedLittleBuffer(_,32).slice(4,20)),t=c.readBigIntFromBuffer(e,!0,!0);if(I.newNonceHash.neq(t))throw new f("Step 2 invalid DH fail nonce from server")}if(!(I instanceof u.ServerDHParamsOk))throw new Error("Step 2.2 answer was "+I);n.debug("Finished authKey generation step 2"),n.debug("Starting authKey generation step 3");const{key:P,iv:C}=await c.generateKeyDataFromNonce(h.serverNonce,_);if(I.encryptedAnswer.length%16!=0)throw new f("Step 3 AES block size mismatch");const S=new i(P,C),M=S.decryptIge(I.encryptedAnswer),k=new l(M);k.read(20);const E=k.tgReadObject();if(!(E instanceof u.ServerDHInnerData))throw new Error("Step 3 answer was "+E);if(E.nonce.neq(h.nonce))throw new f("Step 3 Invalid nonce in encrypted answer");if(E.serverNonce.neq(h.serverNonce))throw new f("Step 3 Invalid server nonce in encrypted answer");const R=c.readBigIntFromBuffer(E.dhPrime,!1,!1),U=c.readBigIntFromBuffer(E.gA,!1,!1),O=E.serverTime-Math.floor((new Date).getTime()/1e3),T=c.readBigIntFromBuffer(c.generateRandomBytes(256),!1,!1),D=c.modExp(s(E.g),T,R),B=c.modExp(U,T,R),x=new u.ClientDHInnerData({nonce:h.nonce,serverNonce:h.serverNonce,retryId:0,gB:c.getByteArray(D,!1)}).getBytes(),j=t.concat([await c.sha1(x),x]),N=S.encryptIge(j),V=await e.send(new d.SetClientDHParams({nonce:h.nonce,serverNonce:h.serverNonce,encryptedData:N})),F=[u.DhGenOk,u.DhGenRetry,u.DhGenFail];if(!(V instanceof F[0]||V instanceof F[1]||V instanceof F[2]))throw new Error("Step 3.1 answer was "+V);const{name:L}=V.constructor;if(V.nonce.neq(h.nonce))throw new f(`Step 3 invalid ${L} nonce from server`);if(V.serverNonce.neq(h.serverNonce))throw new f(`Step 3 invalid ${L} server nonce from server`);const q=new a;await q.setKey(c.getByteArray(B));const H=1+F.indexOf(V.constructor),K=await q.calcNewNonceHash(_,H);if(V["newNonceHash"+H].neq(K))throw new f("Step 3 invalid new nonce hash");if(!(V instanceof u.DhGenOk))throw new Error("Step 3.2 answer was "+V);return n.debug("Finished authKey generation step 3"),{authKey:q,timeOffset:O}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const s=n(38),i=n(37),a=n(58);e.exports=class{constructor(e,t){this._state=e,this._queue=[],this._pendingStates=[],this._ready=new Promise(e=>{this.setReady=e}),this._log=t}values(){return this._queue}append(e){this._queue.push(e),this.setReady(!0),e&&(this._pendingStates.push(e),e.promise.catch(()=>{}).finally(()=>{this._pendingStates=this._pendingStates.filter(t=>t!==e)}))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise(e=>{this.setReady=e}),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,n=new a(t.alloc(0));const r=[];let o=0;for(;this._queue.length&&r.length<=s.MAXIMUM_LENGTH;){const e=this._queue.shift();if(o+=e.data.length+i.SIZE_OVERHEAD,o<=s.MAXIMUM_SIZE){let t;e.after&&(t=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(n,e.data,"request"===e.request.classType,t),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),r.push(e)}else{if(r.length){this._queue.unshift(e);break}this._log.warn(`Message payload for ${e.request.className||e.request.constructor.name} is too long ${e.data.length} and cannot be sent`),e.reject("Request Payload is too big"),o=0}}if(r.length){if(r.length>1){const i=t.alloc(8);i.writeUInt32LE(s.CONSTRUCTOR_ID,0),i.writeInt32LE(r.length,4),e=t.concat([i,n.getValue()]),n=new a(t.alloc(0));const o=await this._state.writeDataAsMessage(n,e,!1);for(const e of r)e.containerId=o}return e=n.getValue(),{batch:r,data:e}}}rejectAll(){this._pendingStates.forEach(e=>{e.reject(new Error("Disconnect"))})}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){e.exports=class{constructor(e){this._stream=e}write(e){this._stream=t.concat([this._stream,e])}getValue(){return this._stream}}}).call(this,n(12).Buffer)},function(e,t,n){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(51),a=n(56),r=n(50);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(87);e.exports={Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:i,doAuthentication:a,MTProtoSender:r,UpdateConnectionState:o}},function(e,t,n){(function(t){const{Mutex:s}=n(88),i=new s,a=n(90).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(){this.client=void 0,this.closed=!0}async readExactly(e){let n=t.alloc(0);for(;;){const s=await this.read(e);if(n=t.concat([n,s]),!(e-=s.length))return n}}async read(e){if(this.closed)throw r;if(await this.canRead,this.closed)throw r;const t=this.stream.slice(0,e);return this.stream=this.stream.slice(e),0===this.stream.length&&(this.canRead=new Promise(e=>{this.resolveRead=e})),t}async readAll(){if(this.closed||!await this.canRead)throw r;const e=this.stream;return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),e}getWebSocketLink(e,t){return 443===t?`wss://${e}:${t}/apiws`:`ws://${e}:${t}/apiws`}connect(e,n){return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),this.closed=!1,this.website=this.getWebSocketLink(n,e),this.client=new a(this.website,"binary"),new Promise((e,t)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{t(e)},this.client.onclose=()=>{this.resolveRead(!1),this.closed=!0},self.addEventListener("offline",async()=>{await this.close(),this.resolveRead(!1)})})}write(e){if(this.closed)throw r;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}receive(){this.client.onmessage=async e=>{const n=await i.acquire();try{const s=e.data instanceof ArrayBuffer?t.from(e.data):t.from(await new Response(e.data).arrayBuffer());this.stream=t.concat([this.stream,s]),this.resolveRead(!0)}finally{n()}}}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(){this._queue=[],this.canGet=new Promise(e=>{this.resolveGet=e}),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise(e=>{this.resolvePush=e})}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise(e=>{this.resolveGet=e}),e}}},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(15),{readBufferFromBigInt:a}=n(8),{Connection:r,PacketCodec:o}=n(39);class c extends o{constructor(e){super(e),this.tag=c.tag,this.obfuscateTag=c.obfuscateTag}encodePacket(e){let n=e.length>>2;if(n<127){const e=t.alloc(1);e.writeUInt8(n,0),n=e}else n=t.concat([t.from("7f","hex"),a(i(n),3)]);return t.concat([n,e])}async readPacket(e){let n=(await e.read(1))[0];return n>=127&&(n=t.concat([await e.read(3),t.alloc(1)]).readInt32LE(0)),e.read(n<<2)}}s(c,"tag",t.from("ef","hex")),s(c,"obfuscateTag",t.from("efefefef","hex"));e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),s(this,"PacketCodecClass",c)}},AbridgedPacketCodec:c}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{generateRandomBytes:i}=n(8),{ObfuscatedConnection:a}=n(39),{AbridgedPacketCodec:r}=n(62),o=n(94);class c{constructor(e){s(this,"header",void 0),this.connection=e.socket;const t=this.initHeader(e.PacketCodecClass);this.header=t.random,this._encrypt=t.encryptor,this._decrypt=t.decryptor}initHeader(e){const n=[t.from("50567247","hex"),t.from("474554","hex"),t.from("504f5354","hex"),t.from("eeeeeeee","hex")];let s;for(;;)if(s=i(64),239!==s[0]&&!s.slice(4,8).equals(t.alloc(4))){let e=!0;for(const t of n)if(t.equals(s.slice(0,4))){e=!1;break}if(e)break}s=s.toJSON().data;const a=t.from(s.slice(8,56)).reverse(),r=t.from(s.slice(8,40)),c=t.from(s.slice(40,56)),u=t.from(a.slice(0,32)),d=t.from(a.slice(32,48)),l=new o(r,c),f=new o(u,d);return s=t.concat([t.from(s.slice(0,56)),e.obfuscateTag,t.from(s.slice(60))]),s=t.concat([t.from(s.slice(0,56)),t.from(l.encrypt(s).slice(56,64)),t.from(s.slice(64))]),{random:s,encryptor:l,decryptor:f}}async read(e){const t=await this.connection.readExactly(e);return this._decrypt.encrypt(t)}write(e){this.connection.write(this._encrypt.encrypt(e))}}e.exports={ConnectionTCPObfuscated:class extends a{constructor(...e){super(...e),s(this,"ObfuscatedIO",c),s(this,"PacketCodecClass",r)}}}}).call(this,n(12).Buffer)},function(e,t){},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(s||(s={}));const i=-1,a="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(s||(s={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return r}));var s=n(1),i=n(0),a=n(2);async function r({chatId:t,accessHash:n,messageId:r,data:o}){const c=await Object(s.g)(new i.Api.messages.GetBotCallbackAnswer({peer:Object(a.i)(t,n),msgId:r,data:e.from(o)}));if(c)return c}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";t.byteLength=function(e){var t=u(e),n=t[0],s=t[1];return 3*(n+s)/4-s},t.toByteArray=function(e){var t,n,s=u(e),r=s[0],o=s[1],c=new a(function(e,t,n){return 3*(t+n)/4-n}(0,r,o)),d=0,l=o>0?r-4:r;for(n=0;n>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===o&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[d++]=255&t);1===o&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,a=[],r=0,o=n-i;ro?o:r+16383));1===i?(t=e[n-1],a.push(s[t>>2]+s[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],a.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return a.join("")};for(var s=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=r.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e,t,n){for(var i,a,r=[],o=t;o>18&63]+s[a>>12&63]+s[a>>6&63]+s[63&a]);return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,s,i){var a,r,o=8*i-s-1,c=(1<>1,d=-7,l=n?i-1:0,f=n?-1:1,p=e[t+l];for(l+=f,a=p&(1<<-d)-1,p>>=-d,d+=o;d>0;a=256*a+e[t+l],l+=f,d-=8);for(r=a&(1<<-d)-1,a>>=-d,d+=s;d>0;r=256*r+e[t+l],l+=f,d-=8);if(0===a)a=1-u;else{if(a===c)return r?NaN:1/0*(p?-1:1);r+=Math.pow(2,s),a-=u}return(p?-1:1)*r*Math.pow(2,a-s)},t.write=function(e,t,n,s,i,a){var r,o,c,u=8*a-i-1,d=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:a-1,g=s?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,r=d):(r=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-r))<1&&(r--,c*=2),(t+=r+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(r++,c/=2),r+l>=d?(o=0,r=d):r+l>=1?(o=(t*c-1)*Math.pow(2,i),r+=l):(o=t*Math.pow(2,l-1)*Math.pow(2,i),r=0));i>=8;e[n+p]=255&o,p+=g,o/=256,i-=8);for(r=r<0;e[n+p]=255&r,p+=g,r/=256,u-=8);e[n+p-g]|=128*h}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";function s(e){const t=new Uint8Array(4*e.length);let n=0;for(let s=0;s>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=255&i}return t.buffer}function i(e){return e.buffer}function a(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;enew p.InvokeWithLayer({layer:l,query:new p.InitConnection({apiId:this.apiId,deviceModel:r.deviceModel||s.type().toString()||"Unknown",systemVersion:r.systemVersion||s.release().toString()||"1.0",appVersion:r.appVersion||"1.0",langCode:r.langCode,langPack:"",systemLangCode:r.systemLangCode,query:e,proxy:void 0})}),this._args=r,this._config=void 0,this.phoneCodeHashes=[],this._borrowedSenderPromises={},this._additionalDcsDisabled=r.additionalDcsDisabled}async connect(){await this._initSession(),this._sender=new g(this.session.getAuthKey(),{logger:this._log,dcId:this.session.dcId,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),updateCallback:this._handleUpdate.bind(this),isMainSender:!0});const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log);await this._sender.connect(e),this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new p.help.GetConfig({}))),this._updateLoop()}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"venus.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;this.isConnected();){await c.sleep(3e3);try{await S(()=>{return e=this._sender.send(new p.Ping({pingId:c.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)})),t=1500,Promise.race([e,c.sleep(t).then(()=>Promise.reject(new Error("TIMEOUT")))]);var e,t},3,100)}catch(e){return await this.disconnect(),void this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new p.updates.GetState)}catch(e){}}}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._borrowedSenderPromises).map(e=>e.then(e=>{if(e)return e.disconnect()}))),this._borrowedSenderPromises={}}async destroy(){await this.disconnect(),this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info("Reconnecting to new data center "+e);const t=u.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}_cleanupBorrowedSender(e){delete this._borrowedSenderPromises[e]}_borrowExportedSender(e){if(this._additionalDcsDisabled)return;let t=this._borrowedSenderPromises[e];return t||(t=this._createExportedSender(e),this._borrowedSenderPromises[e]=t,t.then(t=>{t||delete this._borrowedSenderPromises[e]})),t}async _createExportedSender(e){const t=u.getDC(e),n=new g(this.session.getAuthKey(e),{logger:this._log,dcId:e,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),isMainSender:e===this.session.dcId,onConnectionBreak:this._cleanupBorrowedSender.bind(this)});for(let s=0;s<5;s++)try{if(await n.connect(new this._connection(t.ipAddress,t.port,e,this._log)),this.session.dcId!==e){this._log.info("Exporting authorization for data center "+t.ipAddress);const s=await this.invoke(new p.auth.ExportAuthorization({dcId:e})),i=this._initWith(new p.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await n.send(i)}return n.dcId=e,n}catch(e){await n.disconnect()}}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof f.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof f.MessageMediaWebPage&&n.webpage instanceof f.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof f.MessageMediaPhoto||n instanceof f.Photo?this._downloadPhoto(n,t):n instanceof f.MessageMediaDocument||n instanceof f.Document?this._downloadDocument(n,t):n instanceof f.MessageMediaContact?this._downloadContact(n,t):n instanceof f.WebDocument||n instanceof f.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,i,a;if([765557111,3316604308,524706233,3566872215].includes(e.SUBCLASS_OF_ID)){if(!e.photo){if(!e.chatPhoto)return;return this._downloadPhoto(e.chatPhoto,{sizeType:n})}s=e.photo}else s=e;if(s instanceof f.UserProfilePhoto||s instanceof f.ChatPhoto)return i=s.dcId,a=new f.InputPeerPhotoFileLocation({peer:u.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(a,{dcId:i})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new f.InputStickerSetThumb({stickerset:new f.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=v.indexOf(t);se.type===v[s]),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof f.PhotoStrippedSize?u.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof f.MessageMediaPhoto&&(e=e.photo),!(e instanceof f.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof f.PhotoSizeEmpty?void 0:n instanceof f.PhotoCachedSize||n instanceof f.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new f.InputPhotoFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n.type}),{dcId:e.dcId,fileSize:n.size,progressCallback:t.progressCallback})}_downloadDocument(e,t){if(e instanceof f.MessageMediaDocument&&(e=e.document),!(e instanceof f.Document))return;let n;if(t.sizeType){if(n=e.thumbs?this._pickFileSize(e.thumbs,t.sizeType):void 0,!n&&e.mimeType.startsWith("video/"))return;if(n&&(n instanceof f.PhotoCachedSize||n instanceof f.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new f.InputDocumentFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n?n.type:""}),{fileSize:n?n.size:e.size,progressCallback:t.progressCallback,start:t.start,end:t.end,dcId:e.dcId,workers:t.workers})}_downloadContact(e,t){throw new Error("not implemented")}_downloadWebDocument(e,t){throw new Error("not implemented")}async invoke(e){if("request"!==e.classType)throw new Error("You can only invoke MTProtoRequests");this._lastRequest=(new Date).getTime();let t=0;for(t=0;t1)for(var n=1;n{d[i(e.slice(-8),!0,!0)]=t}),e.exports={encrypt:async function(e,n){const u=d[e];if(!u)return;const l=o(235-n.length),f=t.concat([await r(n),n,l]),p=i(f,!1),g=c(p,s(u.e),u.n);return a(g,256,!1)}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(e,t){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}},function(e,t,n){const{Connection:s}=n(39),{ConnectionTCPFull:i}=n(93),{ConnectionTCPAbridged:a}=n(62),{ConnectionTCPObfuscated:r}=n(63);e.exports={Connection:s,ConnectionTCPFull:i,ConnectionTCPAbridged:a,ConnectionTCPObfuscated:r}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n(89);t.Mutex=s.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(){this._queue=[],this._pending=!1}return e.prototype.isLocked=function(){return this._pending},e.prototype.acquire=function(){var e=this,t=new Promise((function(t){return e._queue.push(t)}));return this._pending||this._dispatchNext(),t},e.prototype.runExclusive=function(e){return this.acquire().then((function(t){var n;try{n=e()}catch(e){throw t(),e}return Promise.resolve(n).then((function(e){return t(),e}),(function(e){throw t(),e}))}))},e.prototype._dispatchNext=function(){this._queue.length>0?(this._pending=!0,this._queue.shift()(this._dispatchNext.bind(this))):this._pending=!1},e}();t.default=s},function(e,t,n){(function(t){var s=function(){return this||void 0===t?this:t}(),i=s.WebSocket||s.MozWebSocket,a=n(91);function r(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(r,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?r:null,version:a}}).call(this,n(43))},function(e,t,n){e.exports=n(92).version},function(e){e.exports=JSON.parse('{"_args":[["websocket@1.0.30","/Users/alexander/dev/telegram-tt"]],"_from":"websocket@1.0.30","_id":"websocket@1.0.30","_inBundle":false,"_integrity":"sha512-aO6klgaTdSMkhfl5VVJzD5fm+Srhh5jLYbS15+OiI1sN6h/RU/XW6WN9J1uVIpUKNmsTvT3Hs35XAFjn9NMfOw==","_location":"/websocket","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"websocket@1.0.30","name":"websocket","escapedName":"websocket","rawSpec":"1.0.30","saveSpec":null,"fetchSpec":"1.0.30"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/websocket/-/websocket-1.0.30.tgz","_spec":"1.0.30","_where":"/Users/alexander/dev/telegram-tt","author":{"name":"Brian McKelvey","email":"theturtle32@gmail.com","url":"https://github.com/theturtle32"},"browser":"lib/browser.js","bugs":{"url":"https://github.com/theturtle32/WebSocket-Node/issues"},"config":{"verbose":false},"contributors":[{"name":"Iñaki Baz Castillo","email":"ibc@aliax.net","url":"http://dev.sipdoc.net"}],"dependencies":{"debug":"^2.2.0","nan":"^2.14.0","typedarray-to-buffer":"^3.1.5","yaeti":"^0.0.6"},"description":"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.","devDependencies":{"buffer-equal":"^1.0.0","faucet":"^0.0.1","gulp":"^4.0.2","gulp-jshint":"^2.0.4","jshint":"^2.0.0","jshint-stylish":"^2.2.1","tape":"^4.9.1"},"directories":{"lib":"./lib"},"engines":{"node":">=0.10.0"},"homepage":"https://github.com/theturtle32/WebSocket-Node","keywords":["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],"license":"Apache-2.0","main":"index","name":"websocket","repository":{"type":"git","url":"git+https://github.com/theturtle32/WebSocket-Node.git"},"scripts":{"gulp":"gulp","install":"(node-gyp rebuild 2> builderror.log) || (exit 0)","test":"faucet test/unit"},"version":"1.0.30"}')},function(e,t){},function(e,t,n){(function(t){const s=n(35);e.exports=class{constructor(e,n){if(!t.isBuffer(e)||!t.isBuffer(n)||16!==n.length)throw new Error("Key and iv need to be a buffer");this.cipher=s.createCipheriv("AES-256-CTR",e,n)}encrypt(e){return t.from(this.cipher.update(e))}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"authFlow",(function(){return u})),n.d(t,"checkAuthorization",(function(){return d}));var s=n(6),i=n.n(s),a=n(20),r=n.n(a),o=n(8),c=n(31);async function u(e,t,n){const s="phoneNumber"in n?await l(e,t,n):await async function(e,t,n){const{apiId:s,apiHash:a}=t,{botAuthToken:r}=n,{user:o}=await e.invoke(new i.a.auth.ImportBotAuthorization({apiId:s,apiHash:a,botAuthToken:r}));return o}(e,t,n);e._log.info("Signed in successfully as",r.a.getDisplayName(s))}async function d(e){try{return await e.invoke(new i.a.updates.GetState),!0}catch(e){return!1}}async function l(e,t,n){let s,a,r,o=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return f(e,t,n);throw s}else s=n.phoneNumber;const i=await p(e,t,s,n.forceSMS);if(a=i.phoneCodeHash,o=i.isCodeViaApp,"string"!=typeof a)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,u=!1;for(;;)try{try{r=await n.phoneCode(o)}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n)}if(!r)throw new Error("Code is empty");const d=await e.invoke(new i.a.auth.SignIn({phoneNumber:s,phoneCodeHash:a,phoneCode:r}));if(d instanceof i.a.auth.AuthorizationSignUpRequired){u=!0,c=d.termsOfService;break}return d.user}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);n.onError(s)}if(u)for(;;)try{const[t,r]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:o}=await e.invoke(new i.a.auth.SignUp({phoneNumber:s,phoneCodeHash:a,firstName:t,lastName:r}));return c&&await e.invoke(new i.a.help.AcceptTermsOfService({id:c.id})),o}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),l(e,t,n)}async function f(e,t,n){let s=!1;const a=(async()=>{for(;!s;){const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("739222"),apiHash:"60d1e1063c72d4bc4cfdda99e8906f94",exceptIds:[]}));if(!(t instanceof i.a.auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:a}=t;await Promise.race([n.qrCode({token:s,expires:a}),Object(o.sleep)(3e4)])}})(),r=new Promise(t=>{e.addEventHandler(e=>{e instanceof i.a.UpdateLoginToken&&t()},{build:e=>e})});try{await Promise.race([r,a])}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("739222"),apiHash:"60d1e1063c72d4bc4cfdda99e8906f94",exceptIds:[]}));if(t instanceof i.a.auth.LoginTokenSuccess&&t.authorization instanceof i.a.auth.Authorization)return t.authorization.user;if(t instanceof i.a.auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new i.a.auth.ImportLoginToken({token:t.token}));if(n instanceof i.a.auth.LoginTokenSuccess&&n.authorization instanceof i.a.auth.Authorization)return n.authorization.user}}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);throw s}throw void 0}async function p(e,t,n,s=!1){try{const{apiId:a,apiHash:r}=t,o=await e.invoke(new i.a.auth.SendCode({phoneNumber:n,apiId:a,apiHash:r,settings:new i.a.CodeSettings}));if(!s||o.type instanceof i.a.auth.SentCodeTypeSms)return{phoneCodeHash:o.phoneCodeHash,isCodeViaApp:o.type instanceof i.a.auth.SentCodeTypeApp};const c=await e.invoke(new i.a.auth.ResendCode({phoneNumber:n,phoneCodeHash:o.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof i.a.auth.SentCodeTypeApp}}catch(i){if("AUTH_RESTART"===i.message)return p(e,t,n,s);throw i}}async function g(e,t,n){for(;;)try{const t=await e.invoke(new i.a.account.GetPassword),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const a=await Object(c.computeCheck)(t,s),{user:r}=await e.invoke(new i.a.auth.CheckPassword({password:a}));return r}catch(e){n.onError(e)}}},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"downloadFile",(function(){return u}));var s=n(6),i=n.n(s),a=n(20),r=n(8);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class c{constructor(e){this.maxWorkers=e,o(this,"deferred",void 0),o(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=function(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function u(t,n,s){let{partSizeKb:o,end:u}=s;const{fileSize:d,workers:l=1}=s,{dcId:f,progressCallback:p,start:g=0}=s;u=u&&u{try{const s=await Promise.race([await y.send(new i.a.upload.GetFile({location:n,offset:w,limit:e,precise:t||void 0})),Object(r.sleep)(15e3).then(()=>Promise.reject(new Error("REQUEST_TIMEOUT")))]);if(p){if(p.isCanceled)throw new Error("USER_CANCELED");A+=1/m,p(A)}return!u&&s.bytes.lengthu)break}const I=(await Promise.all(_)).filter(Boolean),P=u?u+1-g:void 0;return e.concat(I,P)}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"uploadFile",(function(){return o}));var s=n(6),i=n.n(s),a=n(8),r=n(20);async function o(t,n){const{file:s,onProgress:o}=n;let{workers:c}=n;const{name:u,size:d}=s,l=Object(a.readBigIntFromBuffer)(Object(a.generateRandomBytes)(8),!0,!0),f=d>10485760,p=1024*Object(r.getAppropriatedPartSize)(d),g=Math.floor((d+p-1)/p),h=e.from(await function(e){return new Response(e).arrayBuffer()}(s)),m=await t._borrowExportedSender(t.session.dcId);c&&d||(c=1),c>=g&&(c=g);let y=0;o&&o(y);for(let e=0;eg&&(n=g);for(let s=e;s{if(await m.send(f?new i.a.upload.SaveBigFilePart({fileId:l,filePart:s,fileTotalParts:g,bytes:e}):new i.a.upload.SaveFilePart({fileId:l,filePart:s,bytes:e})),o){if(o.isCanceled)throw new Error("USER_CANCELED");y+=1/g,o(y)}})())}try{await Promise.race([await Promise.all(t),Object(a.sleep)(15e3*c).then(()=>Promise.reject(new Error("TIMEOUT")))])}catch(t){if("TIMEOUT"===t.message){console.warn("Upload timeout. Retrying..."),e-=c;continue}throw t}}return f?new i.a.InputFileBig({id:l,parts:g,name:u}):new i.a.InputFile({id:l,parts:g,name:u,md5Checksum:""})}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"updateTwoFaSettings",(function(){return u}));var s=n(6),i=n.n(s),a=n(8),r=n(31),o=n(29),c=n.n(o);async function u(t,{isCheckPassword:n,currentPassword:s,newPassword:o,hint:u="",email:d,emailCodeCallback:l,onEmailCodeError:f}){if(!o&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(d&&(!l||!f))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await t.invoke(new i.a.account.GetPassword);p.newAlgo instanceof i.a.PasswordKdfAlgoUnknown||(p.newAlgo.salt1=e.concat([p.newAlgo.salt1,Object(a.generateRandomBytes)(32)])),!p.hasPassword&&s&&(s=void 0);const g=s?await Object(r.computeCheck)(p,s):new i.a.InputCheckPasswordEmpty;if(n)await t.invoke(new i.a.auth.CheckPassword({password:g}));else try{await t.invoke(new i.a.account.UpdatePasswordSettings({password:g,newSettings:new i.a.account.PasswordInputSettings({newAlgo:p.newAlgo,newPasswordHash:o?await Object(r.computeDigest)(p.newAlgo,o):e.alloc(0),hint:u,email:d,newSecureSettings:void 0})}))}catch(e){if(!(e instanceof c.a.EmailUnconfirmedError))throw e;for(;;)try{const n=await l(e.codeLength);if(!n)throw new Error("Code is empty");await t.invoke(new i.a.account.ConfirmPasswordEmail({code:n}));break}catch(e){f(e)}}}}.call(this,n(12).Buffer)},function(e,t){e.exports="0.0.2"},function(e,t,n){const s=n(101),i=n(102);class a extends Error{}e.exports={NewMessage:s,StopPropagation:a,Raw:i}},function(e,t){},function(e,t,n){const{EventBuilder:s}=n(103);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},function(e,t){e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},function(e,t,n){const s=n(27),i=n(105),a=n(106),r=n(107),o=n(108),c=n(110);e.exports={Memory:s,StringSession:i,CacheApiSession:a,LocalStorageSession:r,IdbSession:o,CallbackSession:c}},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(25);class r extends s{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new a(t);this._dcId=n.read(1).readUInt8(0);const s=n.read(2).readInt16BE(0);this._serverAddress=String(n.read(s)),this._port=n.read(2).readInt16BE(0),this._key=n.read(-1)}}static encode(e){return e.toString("base64")}static decode(e){return t.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=t.from([this.dcId]),n=t.from(this.serverAddress),s=t.alloc(2);s.writeInt16BE(n.length,0);const i=t.alloc(2);return i.writeInt16BE(this.port,0),"1"+r.encode(t.concat([e,s,n,i,this.authKey.getKey()]))}getAuthKey(e){if(!e||e===this.dcId)return this.authKey}setAuthKey(e,t){t&&t!==this.dcId||(this.authKey=e)}}e.exports=r}).call(this,n(12).Buffer)},function(e,t,n){const s=n(40);e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open("GramJs")).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open("GramJs"),n=await t.match(e);return n?n.text():void 0}async _saveToCache(e){const t=new Request(this._storageKey),n=new Response(e);return(await self.caches.open("GramJs")).put(t,n)}}},function(e,t,n){const s=n(40);e.exports=class extends s{_delete(){return localStorage.removeItem(this._storageKey)}_fetchFromCache(){return localStorage.getItem(this._storageKey)}_saveToCache(e){return localStorage.setItem(this._storageKey,e)}}},function(e,t,n){const s=n(109),i=n(40);e.exports=class extends i{_delete(){return s.del("GramJs:"+this._storageKey)}_fetchFromCache(){return s.get("GramJs:"+this._storageKey)}_saveToCache(e){return s.set("GramJs:"+this._storageKey,e)}}},function(e,t,n){"use strict";function s(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function i(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const i=s(n);return(e,n)=>i.then(s=>n(s.transaction(t,e).objectStore(t)))}let a;function r(){return a||(a=i("keyval-store","keyval")),a}function o(e,t=r()){return t("readonly",t=>s(t.get(e)))}function c(e,t,n=r()){return n("readwrite",n=>(n.put(t,e),s(n.transaction)))}function u(e,t=r()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),s(t.transaction)))}function d(e,t=r()){return t("readonly",t=>Promise.all(e.map(e=>s(t.get(e)))))}function l(e,t,n=r()){return n("readwrite",n=>new Promise((i,a)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),i(s(n.transaction))}catch(e){a(e)}}}))}function f(e,t=r()){return t("readwrite",t=>(t.delete(e),s(t.transaction)))}function p(e=r()){return e("readwrite",e=>(e.clear(),s(e.transaction)))}function g(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},s(e.transaction)))}function h(e=r()){const t=[];return g(e,e=>t.push(e.key)).then(()=>t)}function m(e=r()){const t=[];return g(e,e=>t.push(e.value)).then(()=>t)}function y(e=r()){const t=[];return g(e,e=>t.push([e.key,e.value])).then(()=>t)}n.r(t),n.d(t,"clear",(function(){return p})),n.d(t,"createStore",(function(){return i})),n.d(t,"del",(function(){return f})),n.d(t,"entries",(function(){return y})),n.d(t,"get",(function(){return o})),n.d(t,"getMany",(function(){return d})),n.d(t,"keys",(function(){return h})),n.d(t,"promisifyRequest",(function(){return s})),n.d(t,"set",(function(){return c})),n.d(t,"setMany",(function(){return u})),n.d(t,"update",(function(){return l})),n.d(t,"values",(function(){return m}))},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(20);e.exports=class extends s{constructor(e,t){super(),this._sessionData=e,this._callback=t,this._authKeys={}}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(!this._sessionData)return;const{mainDcId:e,keys:n,hashes:s}=this._sessionData,{ipAddress:r,port:o}=a.getDC(e);this.setDC(e,r,o,!0),await Promise.all(Object.keys(n).map(async e=>{const a="string"==typeof n[e]?t.from(n[e],"hex"):t.from(n[e]);if(s[e]){const n="string"==typeof s[e]?t.from(s[e],"hex"):t.from(s[e]);this._authKeys[e]=new i(a,n)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)}))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(t=>{const n=this._authKeys[t];n._key&&(e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex"))}),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t);var s={};n.r(s),n.d(s,"destroy",(function(){return p.a})),n.d(s,"disconnect",(function(){return p.b})),n.d(s,"downloadMedia",(function(){return p.c})),n.d(s,"fetchCurrentUser",(function(){return p.d})),n.d(s,"provideAuthPhoneNumber",(function(){return o.l})),n.d(s,"provideAuthCode",(function(){return o.j})),n.d(s,"provideAuthPassword",(function(){return o.k})),n.d(s,"provideAuthRegistration",(function(){return o.m})),n.d(s,"restartAuth",(function(){return o.n})),n.d(s,"restartAuthWithQr",(function(){return o.o})),n.d(s,"fetchChats",(function(){return c.j})),n.d(s,"fetchFullChat",(function(){return c.k})),n.d(s,"searchChats",(function(){return c.w})),n.d(s,"requestChatUpdate",(function(){return c.u})),n.d(s,"saveDraft",(function(){return c.v})),n.d(s,"clearDraft",(function(){return c.a})),n.d(s,"fetchChat",(function(){return c.h})),n.d(s,"updateChatMutedState",(function(){return c.H})),n.d(s,"createChannel",(function(){return c.b})),n.d(s,"joinChannel",(function(){return c.q})),n.d(s,"leaveChannel",(function(){return c.r})),n.d(s,"deleteChannel",(function(){return c.d})),n.d(s,"createGroupChat",(function(){return c.c})),n.d(s,"editChatPhoto",(function(){return c.g})),n.d(s,"toggleChatPinned",(function(){return c.z})),n.d(s,"toggleChatArchived",(function(){return c.y})),n.d(s,"toggleDialogUnread",(function(){return c.A})),n.d(s,"fetchChatFolders",(function(){return c.i})),n.d(s,"editChatFolder",(function(){return c.f})),n.d(s,"deleteChatFolder",(function(){return c.e})),n.d(s,"fetchRecommendedChatFolders",(function(){return c.n})),n.d(s,"getChatByUsername",(function(){return c.o})),n.d(s,"togglePreHistoryHidden",(function(){return c.B})),n.d(s,"updateChatDefaultBannedRights",(function(){return c.F})),n.d(s,"updateChatMemberBannedRights",(function(){return c.G})),n.d(s,"updateChatTitle",(function(){return c.I})),n.d(s,"updateChatAbout",(function(){return c.D})),n.d(s,"toggleSignatures",(function(){return c.C})),n.d(s,"updateChatAdmin",(function(){return c.E})),n.d(s,"fetchGroupsForDiscussion",(function(){return c.l})),n.d(s,"setDiscussionGroup",(function(){return c.x})),n.d(s,"migrateChat",(function(){return c.s})),n.d(s,"openChatByInvite",(function(){return c.t})),n.d(s,"fetchMembers",(function(){return c.m})),n.d(s,"fetchMessages",(function(){return u.g})),n.d(s,"fetchMessage",(function(){return u.e})),n.d(s,"sendMessage",(function(){return u.v})),n.d(s,"pinMessage",(function(){return u.q})),n.d(s,"unpinAllMessages",(function(){return u.y})),n.d(s,"deleteMessages",(function(){return u.b})),n.d(s,"deleteHistory",(function(){return u.a})),n.d(s,"markMessageListRead",(function(){return u.o})),n.d(s,"markMessagesRead",(function(){return u.p})),n.d(s,"requestThreadInfoUpdate",(function(){return u.r})),n.d(s,"searchMessagesLocal",(function(){return u.u})),n.d(s,"searchMessagesGlobal",(function(){return u.t})),n.d(s,"fetchWebPagePreview",(function(){return u.j})),n.d(s,"editMessage",(function(){return u.d})),n.d(s,"forwardMessages",(function(){return u.l})),n.d(s,"loadPollOptionResults",(function(){return u.n})),n.d(s,"sendPollVote",(function(){return u.w})),n.d(s,"findFirstMessageIdAfterDate",(function(){return u.k})),n.d(s,"fetchPinnedMessages",(function(){return u.h})),n.d(s,"fetchScheduledHistory",(function(){return u.i})),n.d(s,"sendScheduledMessages",(function(){return u.x})),n.d(s,"rescheduleMessage",(function(){return u.s})),n.d(s,"deleteScheduledMessages",(function(){return u.c})),n.d(s,"fetchMessageLink",(function(){return u.f})),n.d(s,"fetchFullUser",(function(){return v})),n.d(s,"fetchNearestCountry",(function(){return A})),n.d(s,"fetchTopUsers",(function(){return I})),n.d(s,"fetchContactList",(function(){return P})),n.d(s,"fetchUsers",(function(){return C})),n.d(s,"updateContact",(function(){return S})),n.d(s,"deleteUser",(function(){return M})),n.d(s,"fetchProfilePhotos",(function(){return k})),n.d(s,"fetchStickerSets",(function(){return D})),n.d(s,"fetchRecentStickers",(function(){return B})),n.d(s,"fetchFavoriteStickers",(function(){return x})),n.d(s,"fetchFeaturedStickers",(function(){return j})),n.d(s,"faveSticker",(function(){return N})),n.d(s,"fetchStickers",(function(){return V})),n.d(s,"fetchSavedGifs",(function(){return q})),n.d(s,"searchStickers",(function(){return L})),n.d(s,"installStickerSet",(function(){return H})),n.d(s,"uninstallStickerSet",(function(){return K})),n.d(s,"searchGifs",(function(){return z})),n.d(s,"fetchAnimatedEmojis",(function(){return F})),n.d(s,"fetchStickersForEmoji",(function(){return G})),n.d(s,"fetchEmojiKeywords",(function(){return W})),n.d(s,"checkChatUsername",(function(){return Z})),n.d(s,"setChatUsername",(function(){return Y})),n.d(s,"updatePrivateLink",(function(){return Q})),n.d(s,"updateProfile",(function(){return ge})),n.d(s,"checkUsername",(function(){return he})),n.d(s,"updateUsername",(function(){return me})),n.d(s,"fetchBlockedContacts",(function(){return ve})),n.d(s,"blockContact",(function(){return Ae})),n.d(s,"unblockContact",(function(){return Ie})),n.d(s,"updateProfilePhoto",(function(){return ye})),n.d(s,"uploadProfilePhoto",(function(){return be})),n.d(s,"fetchWallpapers",(function(){return _e})),n.d(s,"uploadWallpaper",(function(){return we})),n.d(s,"fetchAuthorizations",(function(){return Pe})),n.d(s,"terminateAuthorization",(function(){return Ce})),n.d(s,"terminateAllAuthorizations",(function(){return Se})),n.d(s,"fetchNotificationExceptions",(function(){return Me})),n.d(s,"fetchNotificationSettings",(function(){return ke})),n.d(s,"updateContactSignUpNotification",(function(){return Ee})),n.d(s,"updateNotificationSettings",(function(){return Re})),n.d(s,"fetchLanguages",(function(){return Ue})),n.d(s,"fetchLangPack",(function(){return Oe})),n.d(s,"fetchPrivacySettings",(function(){return Te})),n.d(s,"setPrivacySettings",(function(){return xe})),n.d(s,"registerDevice",(function(){return De})),n.d(s,"unregisterDevice",(function(){return Be})),n.d(s,"getPasswordInfo",(function(){return ne})),n.d(s,"checkPassword",(function(){return ie})),n.d(s,"clearPassword",(function(){return ae})),n.d(s,"updatePassword",(function(){return re})),n.d(s,"updateRecoveryEmail",(function(){return oe})),n.d(s,"provideRecoveryEmailCode",(function(){return ce})),n.d(s,"answerCallbackButton",(function(){return Ne.a})),n.d(s,"validateRequestedInfo",(function(){return Fe})),n.d(s,"sendPaymentForm",(function(){return Le})),n.d(s,"getPaymentForm",(function(){return qe})),n.d(s,"getReceipt",(function(){return He}));var i=n(4),a=n(30),r=n(26),o=n(17),c=n(7),u=n(10),d=n(15),l=n.n(d),f=n(0),p=n(1),g=n(2),h=n(13),m=n(3),y=n(19),b=n(5),_=n(16);let w;async function v({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;const s=await Object(p.g)(new f.Api.users.GetFullUser({id:n}));if(!s)return;const i=Object(h.b)(s);w({"@type":"updateUser",id:e,user:{fullInfo:i.fullInfo}})}async function A(){const e=await Object(p.g)(new f.Api.help.GetNearestDc);return e?e.country:void 0}async function I({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetTopPeers({hash:e,correspondents:!0}));if(!(t instanceof f.Api.contacts.TopPeers))return;const n=t.users.map(h.a).filter(e=>!!e&&!e.isSelf),s=n.map(({id:e})=>e);return{hash:Object(g.q)(s),ids:s,users:n}}async function P({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetContacts({hash:e}));if(t&&!(t instanceof f.Api.contacts.ContactsNotModified))return t.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),{hash:Object(g.q)([t.savedCount,...t.contacts.map(({userId:e})=>e)]),users:t.users.map(h.a).filter(Boolean),chats:t.users.map(e=>Object(m.d)(e)).filter(Boolean)}}async function C({users:e}){const t=await Object(p.g)(new f.Api.users.GetUsers({id:e.map(({id:e,accessHash:t})=>Object(g.i)(e,t))}));if(t&&t.length)return t.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),t.map(h.a).filter(Boolean)}function S({phone:e,firstName:t,lastName:n}){return Object(p.g)(new f.Api.contacts.ImportContacts({contacts:[Object(g.e)({phone:e||"",firstName:t||"",lastName:n||""})]}))}async function M({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;await Object(p.g)(new f.Api.contacts.DeleteContacts({id:[n]}))&&w({"@type":"deleteUser",id:e})}async function k(e,t){if(e){const{id:t,accessHash:n}=e,s=await Object(p.g)(new f.Api.photos.GetUserPhotos({userId:Object(g.g)(t,n),limit:i.u,offset:0,maxId:l()("0")}));if(!s)return;return function(e){e.photos.forEach(_.b)}(s),{photos:s.photos.filter(e=>e instanceof f.Api.Photo).map(y.a)}}const n=await Object(u.u)({chatOrUser:t,type:"profilePhoto",limit:i.u});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map(e=>e.content.action.photo).filter(Boolean),users:a}}var E=n(22),R=n(9);let U,O,T;async function D({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetAllStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.AllStickersNotModified))return t.sets.forEach(e=>{e.thumbs&&e.thumbs.length&&(b.a.stickerSets[String(e.id)]=e)}),{hash:t.hash,sets:t.sets.map(E.b)}}async function B({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetRecentStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.RecentStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function x({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFavedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FavedStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function j({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFeaturedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FeaturedStickersNotModified))return{hash:t.hash,sets:t.sets.map(E.c)}}async function N({sticker:e,unfave:t}){const n=new f.Api.messages.FaveSticker({id:Object(g.f)(e),unfave:t});await Object(p.g)(n)&&U({"@type":"updateFavoriteStickers"})}async function V({stickerSetId:e,accessHash:t}){const n=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:Object(g.l)(e,t)}));var s;if(n)return{set:Object(E.b)(n.set),stickers:$(n.documents),packs:(s=n.packs,s.reduce((e,{emoticon:t,documents:n})=>(e[t]=n.map(e=>Object(E.a)(b.a.documents[String(e)])).filter(Boolean),e),{}))}}async function F(){const e=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:new f.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:Object(E.b)(e.set),stickers:$(e.documents)}}async function L({query:e,hash:t}){const n=await Object(p.g)(new f.Api.messages.SearchStickerSets({q:e,hash:t}));if(n&&!(n instanceof f.Api.messages.FoundStickerSetsNotModified))return{hash:n.hash,sets:n.sets.map(E.c)}}async function q({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetSavedGifs({hash:e}));if(t&&!(t instanceof f.Api.messages.SavedGifsNotModified))return{hash:t.hash,gifs:J(t.gifs)}}async function H({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.InstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function K({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.UninstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function z({query:e,offset:t=""}){if(!O){const e=await Object(p.g)(new f.Api.help.GetConfig);if(!e)return;const t=await Object(p.g)(new f.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof f.Api.User))return;O=new f.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await Object(p.g)(new f.Api.messages.GetInlineBotResults({bot:O,peer:new f.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map(e=>{if(e instanceof f.Api.BotInlineMediaResult)return e.document}).filter(Boolean);return{nextOffset:n.nextOffset,gifs:J(s)}}async function G({emoji:e,hash:t=0}){const n=await Object(p.g)(new f.Api.messages.GetStickers({emoticon:e,hash:t}));if(n&&!(n instanceof f.Api.messages.StickersNotModified))return{stickers:$(n.stickers),hash:n.hash}}async function W({language:e,fromVersion:t}){const n=await Object(p.g)(new f.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce((e,t)=>(e[t.keyword]=t.emoticons,e),{})}}function $(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(E.a)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}function J(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(R.m)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}async function Z({username:e}){try{return await Object(p.g)(new f.Api.channels.CheckUsername({channel:new f.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Y({chat:e,username:t}){await Object(p.g)(new f.Api.channels.UpdateUsername({channel:Object(g.g)(e.id,e.accessHash),username:t}))&&T({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Q({chat:e}){const t=await Object(p.g)(new f.Api.messages.ExportChatInvite({peer:Object(g.i)(e.id,e.accessHash)}));t&&t instanceof f.Api.ChatInviteExported&&T({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const X={EMAIL_UNCONFIRMED:"Email unconfirmed",EMAIL_HASH_EXPIRED:"Email hash expired",NEW_SALT_INVALID:"The new salt is invalid",NEW_SETTINGS_INVALID:"The new password settings are invalid",CODE_INVALID:"Invalid Code",PASSWORD_HASH_INVALID:"Invalid Password"},ee={};let te;async function ne(){const e=await Object(p.g)(new f.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function se(e){return te({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise((e,t)=>{ee.resolve=e,ee.reject=t})}async function ie(e){try{return await Object(p.h)({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return ue(e),!1}}async function ae(e){try{return await Object(p.h)({currentPassword:e}),!0}catch(e){return ue(e),!1}}async function re(e,t,n,s){try{return await Object(p.h)({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}async function oe(e,t){try{return await Object(p.h)({currentPassword:e,newPassword:e,email:t,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}function ce(e){ee.resolve(e)}function ue(e){let t;if(e instanceof f.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?n+" hours":"an hour")}else t=X[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),te({"@type":"updateTwoFaError",message:t})}var de=n(24),le=n(18),fe=n(14);const pe=["ar","fa"];function ge({firstName:e,lastName:t,about:n}){return Object(p.g)(new f.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function he(e){return Object(p.g)(new f.Api.account.CheckUsername({username:e}))}function me(e){return Object(p.g)(new f.Api.account.UpdateUsername({username:e}))}async function ye(e){const t=await Object(p.i)(e);return Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function be(e){const t=await Object(p.i)(e);await Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function _e(e){const t=await Object(p.g)(new f.Api.account.GetWallPapers({hash:e}));if(!t||t instanceof f.Api.account.WallPapersNotModified)return;const n=t.wallpapers.filter(e=>e instanceof f.Api.WallPaper&&e.document instanceof f.Api.Document&&(!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return n.forEach(e=>{b.a.documents[String(e.document.id)]=e.document}),{hash:t.hash,wallpapers:n.map(de.b).filter(Boolean)}}async function we(e){const t=await Object(p.i)(e),n=await Object(p.g)(new f.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new f.Api.WallPaperSettings}));if(!(n&&n instanceof f.Api.WallPaper))return;const s=Object(de.b)(n);return s?(b.a.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function ve(){const e=await Object(p.g)(new f.Api.contacts.GetBlocked({limit:i.f}));if(e)return je(e),{users:e.users.map(h.a).filter(Boolean),chats:e.chats.map(e=>Object(m.d)(e,void 0,!0)).filter(Boolean),blockedIds:e.blocked.map(e=>Object(m.j)(e.peerId)),totalCount:e instanceof f.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function Ae(e){return Object(p.g)(new f.Api.contacts.Block({id:Object(g.o)(e)}))}function Ie(e,t){return Object(p.g)(new f.Api.contacts.Unblock({id:Object(g.i)(e,t)}))}async function Pe(){const e=await Object(p.g)(new f.Api.account.GetAuthorizations);if(e)return e.authorizations.map(de.a)}function Ce(e){return Object(p.g)(new f.Api.account.ResetAuthorization({hash:l()(e)}))}function Se(){return Object(p.g)(new f.Api.auth.ResetAuthorizations)}async function Me(){const e=await Object(p.g)(new f.Api.account.GetNotifyExceptions({compareSound:!0}),!0);(e instanceof f.Api.Updates||e instanceof f.Api.UpdatesCombined)&&je(e)}async function ke(){const[e,t,n,s]=await Promise.all([Object(p.g)(new f.Api.account.GetContactSignUpNotification),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyUsers})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyChats})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyBroadcasts}))]);if(!t||!n||!s)return!1;const{silent:i,muteUntil:a,showPreviews:r}=t,{silent:o,muteUntil:c,showPreviews:u}=n,{silent:d,muteUntil:l,showPreviews:g}=s;return{hasContactJoinedNotifications:!e,hasPrivateChatsNotifications:!(i||"number"==typeof a&&Date.now()<1e3*a),hasPrivateChatsMessagePreview:r,hasGroupNotifications:!(o||"number"==typeof c&&Date.now()<1e3*c),hasGroupMessagePreview:u,hasBroadcastNotifications:!(d||"number"==typeof l&&Date.now()<1e3*l),hasBroadcastMessagePreview:g}}function Ee(e){return Object(p.g)(new f.Api.account.SetContactSignUpNotification({silent:e}))}function Re(e,{isSilent:t,shouldShowPreviews:n}){let s;s="contact"===e?new f.Api.InputNotifyUsers:"group"===e?new f.Api.InputNotifyChats:new f.Api.InputNotifyBroadcasts;const i={showPreviews:n,silent:t,muteUntil:t?2**31-1:void 0};return Object(p.g)(new f.Api.account.UpdateNotifySettings({peer:s,settings:new f.Api.InputPeerNotifySettings(i)}))}async function Ue(){const e=await Object(p.g)(new f.Api.langpack.GetLanguages({langPack:i.i}));if(e)return e.map(le.b)}async function Oe({sourceLangPacks:e,langCode:t}){const n=(await Promise.all(e.map(e=>Object(p.g)(new f.Api.langpack.GetLangPack({langPack:e,langCode:pe.includes(t)?t+"-raw":t}))))).filter(Boolean).map(e=>Object(fe.a)(e.strings.map(le.b),"key"));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function Te(e){const t=Object(g.k)(e),n=await Object(p.g)(new f.Api.account.GetPrivacy({key:t}));if(n)return je(n),Object(de.d)(n.rules)}function De(e){const t=Object(p.e)().session.getAuthKey().getKey();return Object(p.g)(new f.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Be(e){return Object(p.g)(new f.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function xe(e,t){const n=Object(g.k)(e),s=[];switch(t.allowedUsers&&s.push(new f.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.allowedChats&&s.push(new f.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map(({id:e})=>-e)})),t.blockedUsers&&s.push(new f.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.blockedChats&&s.push(new f.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map(({id:e})=>-e)})),t.visibility){case"everybody":s.push(new f.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new f.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new f.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new f.Api.InputPrivacyValueDisallowAll)}const i=await Object(p.g)(new f.Api.account.SetPrivacy({key:n,rules:s}));if(i)return je(i),Object(de.d)(i.rules)}function je(e){e.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof f.Api.Chat||e instanceof f.Api.Channel)&&(b.a.chats[e.id]=e)})}var Ne=n(72);function Ve(e){if(e)return Object.values(e).map(e=>({id:e.id,title:e.title,amount:e.prices.reduce((e,t)=>e+Number(t.amount.value),0),prices:e.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}))}))}async function Fe({messageId:e,requestInfo:t,shouldSave:n}){const s=await Object(p.g)(new f.Api.payments.ValidateRequestedInfo({msgId:e,save:n||void 0,info:Object(g.p)(t)}));if(!s)return;const{id:i,shippingOptions:a}=s;return i?{id:i,shippingOptions:Ve(a)}:void 0}function Le({messageId:e,requestedInfoId:t,shippingOptionId:n,credentials:s}){return Object(p.g)(new f.Api.payments.SendPaymentForm({msgId:e,requestedInfoId:t,shippingOptionId:n,credentials:new f.Api.InputPaymentCredentials({save:s.save,data:new f.Api.DataJSON({data:JSON.stringify(s.data)})})}),!0)}async function qe({messageId:e}){const t=await Object(p.g)(new f.Api.payments.GetPaymentForm({msgId:e}));if(t)return function(e){const{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,nativeParams:a,savedInfo:r,invoice:o}=e,{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:y}=o,b=y.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),_=a?JSON.parse(a.data):{};return{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,savedInfo:r,invoice:{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:b},nativeParams:{needCardholderName:_.need_cardholder_name,needCountry:_.need_country,needZip:_.need_zip,publishableKey:_.publishable_key}}}(t)}async function He(e){const t=await Object(p.g)(new f.Api.payments.GetPaymentReceipt({msgId:e}));if(t)return function(e){const{invoice:t,info:n,shipping:s,currency:i,totalAmount:a,credentialsTitle:r}=e,{shippingAddress:o,phone:c,name:u}=n||{},{prices:d}=t,l=d.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}));let f,p;return s&&(f=s.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),p=s.title),{currency:i,prices:l,info:{shippingAddress:o,phone:c,name:u},totalAmount:Number(a.value),credentialsTitle:r,shippingPrices:f,shippingMethod:p}}(t)}let Ke;async function ze(e,t){Ke=e,Object(r.a)(Ze),Object(o.a)(Ze),Object(c.p)(Ze),Object(u.m)(Ze),function(e){w=e}(Ze),function(e){U=e}(Ze),function(e){T=e}(Ze),function(e){te=e}(Ze),await Object(p.f)(Ze,t)}const Ge=Object(a.c)((function(e){if(!Je||e!==$e)return;const t=Je;Je=void 0,t.forEach(Ke)}));let We,$e,Je;function Ze(e){Je?Je.push(e):Je=[e],We&&!i.b.has(e["@type"])||(We=Object(a.b)(Ge,i.c,!0),$e=Math.random()),We($e)}self.onerror=e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const Ye=new Map;function Qe(e){Xe({type:"update",update:e})}function Xe(e,t){t?postMessage(e,[t]):postMessage(e)}i.g&&console.log(">>> FINISH LOAD WORKER"),onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await ze(Qe,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:a}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Xe({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ye.set(e,t),a.push(t)}const t=await function(e,...t){return s[e](...t)}(n,...a),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Xe({type:"methodResponse",messageId:e,response:t},i)}catch(t){i.g&&console.error(t),e&&Xe({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ye.delete(e);break}case"cancelProgress":{const e=Ye.get(t.messageId);e&&(e.isCanceled=!0);break}}}}]); +//# sourceMappingURL=3d0807b05cc1ab7d3c59.worker.js.map \ No newline at end of file diff --git a/dist/6b9e1c477ee38548ce72.worker.js.LICENSE.txt b/dist/3d0807b05cc1ab7d3c59.worker.js.LICENSE.txt similarity index 100% rename from dist/6b9e1c477ee38548ce72.worker.js.LICENSE.txt rename to dist/3d0807b05cc1ab7d3c59.worker.js.LICENSE.txt diff --git a/dist/3d0807b05cc1ab7d3c59.worker.js.map b/dist/3d0807b05cc1ab7d3c59.worker.js.map new file mode 100644 index 00000000..f3bbf6fa --- /dev/null +++ b/dist/3d0807b05cc1ab7d3c59.worker.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/gramjs/index.js","webpack:///./src/util/cacheApi.ts","webpack:///./src/api/gramjs/methods/media.ts","webpack:///./src/api/gramjs/methods/client.ts","webpack:///./src/api/gramjs/gramjsBuilders/index.ts","webpack:///./src/api/gramjs/apiBuilders/peers.ts","webpack:///./src/api/gramjs/apiBuilders/chats.ts","webpack:///./src/config.ts","webpack:///./src/api/gramjs/localDb.ts","webpack:///./src/lib/gramjs/tl/api.js","webpack:///./src/api/gramjs/methods/chats.ts","webpack:///./src/lib/gramjs/Helpers.js","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/api/gramjs/apiBuilders/messages.ts","webpack:///./src/api/gramjs/methods/messages.ts","webpack:///./src/api/types/index.ts","webpack:///./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack:///./src/api/gramjs/apiBuilders/users.ts","webpack:///./src/util/iteratees.ts","webpack:///./node_modules/big-integer/BigInteger.js","webpack:///./src/api/gramjs/helpers.ts","webpack:///./src/api/gramjs/methods/auth.ts","webpack:///./src/api/gramjs/apiBuilders/helpers.ts","webpack:///./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack:///./src/api/gramjs/apiBuilders/common.ts","webpack:///./src/lib/gramjs/Utils.js","webpack:///./src/lib/gramjs/tl/index.js","webpack:///./src/api/gramjs/apiBuilders/symbols.ts","webpack:///./src/lib/gramjs/errors/Common.js","webpack:///./src/api/gramjs/apiBuilders/misc.ts","webpack:///./src/lib/gramjs/extensions/BinaryReader.js","webpack:///./src/api/gramjs/updater.ts","webpack:///./src/lib/gramjs/sessions/Memory.js","webpack:///./src/lib/gramjs/crypto/AuthKey.js","webpack:///./src/lib/gramjs/errors/index.js","webpack:///./src/util/schedulers.ts","webpack:///./src/lib/gramjs/Password.js","webpack:///./src/lib/gramjs/tl/core/GZIPPacked.js","webpack:///./src/util/waveform.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/gramjs/crypto/crypto.js","webpack:///./src/lib/gramjs/errors/RPCBaseErrors.js","webpack:///./src/lib/gramjs/tl/core/TLMessage.js","webpack:///./src/lib/gramjs/tl/core/MessageContainer.js","webpack:///./src/lib/gramjs/network/connection/Connection.js","webpack:///./src/lib/gramjs/sessions/StorageSession.js","webpack:///./node_modules/pako/dist/pako_inflate.js","webpack:///./src/lib/gramjs/extensions/index.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/lib/gramjs/tl/generationHelpers.js","webpack:///./node_modules/@cryptography/aes/dist/es/aes.js","webpack:///./src/lib/gramjs/extensions/Logger.js","webpack:///./src/lib/gramjs/errors/RPCErrorList.js","webpack:///./src/lib/gramjs/sessions/Abstract.js","webpack:///./src/lib/gramjs/tl/AllTLObjects.js","webpack:///./src/lib/gramjs/network/MTProtoSender.js","webpack:///./src/lib/gramjs/network/MTProtoPlainSender.js","webpack:///./src/lib/gramjs/network/MTProtoState.js","webpack:///./src/lib/gramjs/crypto/IGE.js","webpack:///./src/lib/gramjs/tl/core/index.js","webpack:///./src/lib/gramjs/tl/core/RPCResult.js","webpack:///./src/lib/gramjs/network/Authenticator.js","webpack:///./src/lib/gramjs/extensions/MessagePacker.js","webpack:///./src/lib/gramjs/extensions/BinaryWriter.js","webpack:///./src/lib/gramjs/network/index.js","webpack:///./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack:///./src/lib/gramjs/extensions/AsyncQueue.js","webpack:///./src/lib/gramjs/network/connection/TCPAbridged.js","webpack:///./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/api/gramjs/methods/bots.ts","webpack:///./node_modules/base64-js/index.js","webpack:///./node_modules/ieee754/index.js","webpack:///./node_modules/isarray/index.js","webpack:///(webpack)/buildin/module.js","webpack:///./src/lib/gramjs/crypto/converters.ts","webpack:///./src/lib/gramjs/crypto/words.ts","webpack:///./src/lib/gramjs/tl/apiTl.js","webpack:///./src/lib/gramjs/tl/schemaTl.js","webpack:///./src/lib/gramjs/client/TelegramClient.js","webpack:///./node_modules/os-browserify/browser.js","webpack:///./node_modules/process/browser.js","webpack:///./src/lib/gramjs/crypto/Factorizator.js","webpack:///./src/lib/gramjs/crypto/RSA.js","webpack:///./src/lib/gramjs/network/RequestState.js","webpack:///./src/lib/gramjs/network/connection/index.js","webpack:///./node_modules/async-mutex/lib/index.js","webpack:///./node_modules/async-mutex/lib/Mutex.js","webpack:///./node_modules/websocket/lib/browser.js","webpack:///./node_modules/websocket/lib/version.js","webpack:///./src/lib/gramjs/crypto/CTR.js","webpack:///./src/lib/gramjs/client/auth.ts","webpack:///./src/lib/gramjs/client/downloadFile.ts","webpack:///./src/lib/gramjs/client/uploadFile.ts","webpack:///./src/lib/gramjs/client/2fa.ts","webpack:///./src/lib/gramjs/Version.js","webpack:///./src/lib/gramjs/events/index.js","webpack:///./src/lib/gramjs/events/Raw.js","webpack:///./src/lib/gramjs/events/common.js","webpack:///./src/lib/gramjs/sessions/index.js","webpack:///./src/lib/gramjs/sessions/StringSession.js","webpack:///./src/lib/gramjs/sessions/CacheApiSession.js","webpack:///./src/lib/gramjs/sessions/LocalStorageSession.js","webpack:///./src/lib/gramjs/sessions/IdbSession.js","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/lib/gramjs/sessions/CallbackSession.js","webpack:///./src/api/gramjs/methods/users.ts","webpack:///./src/api/gramjs/methods/symbols.ts","webpack:///./src/api/gramjs/methods/management.ts","webpack:///./src/api/gramjs/methods/twoFaSettings.ts","webpack:///./src/api/gramjs/methods/settings.ts","webpack:///./src/api/gramjs/apiBuilders/payments.ts","webpack:///./src/api/gramjs/methods/payments.ts","webpack:///./src/api/gramjs/provider.ts","webpack:///./src/api/gramjs/worker/worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Api","require","TelegramClient","connection","tl","version","events","utils","errors","sessions","extensions","helpers","cacheApi","self","caches","Type","async","fetch","cacheName","type","request","Request","cache","open","response","match","Text","text","Blob","blob","substr","contentType","headers","Json","json","err","console","warn","save","data","cacheData","JSON","stringify","Response","put","clear","delete","downloadMedia","url","mediaFormat","start","end","client","isConnected","onProgress","mimeType","fullSize","mediaMatch","arrayBuffer","Promise","reject","Error","entityType","entityId","sizeType","replace","undefined","entity","getEntityTypeById","Number","Math","abs","localDb","chats","users","messages","documents","photos","stickerSets","includes","ApiMediaFormat","Stream","acceptsBuffer","progressCallback","workers","DOWNLOAD_WORKERS","GramJs","Message","message","media","MessageMediaPhoto","MessageMediaDocument","document","Document","attributes","some","a","DocumentAttributeSticker","getMessageMediaMimeType","size","Photo","downloadStickerSetThumb","Lottie","getMimeType","downloadProfilePhoto","download","parsed","DataUri","blobToDataUri","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","MEDIA_CACHE_MAX_BYTES","MEDIA_CACHE_DISABLED","startsWith","MEDIA_CACHE_NAME_AVATARS","MEDIA_CACHE_NAME","prepared","mediaData","URL","createObjectURL","prepareMedia","fallbackMimeType","length","subarray","reduce","result","byte","toString","GramJsLogger","setLevel","DEBUG_GRAMJS","gramJsUpdateEventBuilder","build","update","onUpdate","init","_onUpdate","sessionData","DEBUG","log","CallbackSession","onSessionUpdate","process","deviceModel","navigator","userAgent","appVersion","APP_VERSION","useWSS","additionalDcsDisabled","IS_TEST","addEventHandler","handleGramJsUpdate","updater","phoneNumber","onRequestPhoneNumber","phoneCode","onRequestCode","password","onRequestPassword","firstAndLastNames","onRequestRegistration","qrCode","onRequestQrCode","onError","onAuthError","onAuthReady","fetchCurrentUser","destroy","invokeRequest","auth","LogOut","disconnect","getClient","UpdateConnectionState","state","connected","UpdatesTooLong","GetFullUser","id","InputUserSelf","connectionState","handleTerminatedSession","shouldHandleUpdates","shouldThrow","className","invoke","updatesContainer","Updates","UpdatesCombined","updates","entities","forEach","_entities","injectUpdateEntities","error","isSlowMode","SendMessage","SendMedia","SendMultiMedia","dispatchErrorUpdate","args","downloadMediaWithClient","uploadFile","file","UPLOAD_WORKERS","updateTwoFaSettings","params","userFull","user","User","currentUser","buildApiUserFromFull","setMessageBuilderCurrentUserId","onCurrentUserUpdate","chatOrUserId","buildPeer","PeerUser","userId","PeerChannel","channelId","PeerChat","chatId","buildInputPeer","accessHash","InputPeerUser","BigInt","InputPeerChannel","InputPeerChat","buildInputPeerFromLocalDb","buildInputEntity","InputUser","InputChannel","buildInputStickerSet","InputStickerSetID","buildInputDocument","InputDocument","pick","buildInputMediaDocument","inputDocument","InputMediaDocument","buildInputPoll","pollParams","randomId","summary","quiz","poll","Poll","publicVoters","isPublic","question","answers","map","option","PollAnswer","Buffer","from","multipleChoice","InputMediaPoll","correctAnswers","solution","solutionEntities","buildMtpMessageEntity","buildFilterFromApiFolder","folder","emoticon","contacts","nonContacts","groups","channels","bots","excludeArchived","excludeMuted","excludeRead","pinnedChatIds","includedChatIds","excludedChatIds","pinnedPeers","filter","Boolean","includePeers","excludePeers","DialogFilter","title","broadcasts","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","fromId","offset","ApiMessageEntityTypes","Bold","MessageEntityBold","Italic","MessageEntityItalic","Underline","MessageEntityUnderline","Strike","MessageEntityStrike","Code","MessageEntityCode","Pre","MessageEntityPre","language","Blockquote","MessageEntityBlockquote","TextUrl","MessageEntityTextUrl","Url","MessageEntityUrl","Hashtag","MessageEntityHashtag","MentionName","InputMessageEntityMentionName","MessageEntityUnknown","calculateResultHash","ids","hash","isMessageWithMedia","MessageMediaWebPage","webpage","WebPage","photo","isServiceMessageWithMedia","action","buildChatPhotoForLocalDb","PhotoEmpty","ChatPhotoEmpty","dcId","photoId","ChatPhoto","buildInputContact","phone","firstName","lastName","InputPhoneContact","clientId","buildChatBannedRights","bannedRights","untilDate","ChatBannedRights","buildChatAdminRights","adminRights","ChatAdminRights","buildShippingInfo","info","shippingAddress","PaymentRequestedInfo","PostAddress","buildInputPrivacyKey","privacyKey","InputPrivacyKeyPhoneNumber","InputPrivacyKeyStatusTimestamp","InputPrivacyKeyProfilePhoto","InputPrivacyKeyForwards","InputPrivacyKeyChatInvite","isPeerUser","peer","isPeerChat","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","String","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","Channel","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","Chat","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","Date","now","getApiChatIdFromMtpPeer","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","omitVirtualClassFields","currentUserBannedRights","defaultBannedRights","ChatForbidden","ChannelForbidden","isRestricted","restrictionReason","restricted","buildApiChatRestrictionReason","isNotJoined","left","kicked","reason","platform","migratedTo","InputChannelEmpty","restrictionReasons","targetReason","find","buildApiChatFromPreview","preview","withForbidden","getUserName","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","UserEmpty","ChatEmpty","megagroup","getPeerKey","buildChatMember","member","ChannelParticipantBanned","ChannelParticipantLeft","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","ChannelParticipantAdmin","ChatParticipantAdmin","isAdmin","ChannelParticipantCreator","ChatParticipantCreator","isOwner","buildChatMembers","participants","ChatParticipants","ChannelParticipants","buildChatTypingStatus","SendMessageCancelAction","SendMessageTypingAction","SendMessageRecordVideoAction","SendMessageUploadVideoAction","SendMessageRecordAudioAction","SendMessageUploadAudioAction","SendMessageUploadPhotoAction","SendMessageUploadDocumentAction","SendMessageGeoLocationAction","SendMessageChooseContactAction","SendMessageGamePlayAction","SendMessageRecordRoundAction","SendMessageUploadRoundAction","UpdateUserTyping","timestamp","buildApiChatFolder","pickTruthy","buildApiChatFolderFromSuggested","description","API_UPDATE_THROTTLE","API_THROTTLE_RESET_UPDATES","Set","MEMBERS_LOAD_SLICE","window","innerHeight","PINNED_MESSAGES_LIMIT","BLOCKED_LIST_LIMIT","PROFILE_PHOTOS_LIMIT","LOCAL_MESSAGE_ID_BASE","MEMOJI_STICKER_ID","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","DELETED_COMMENTS_CHANNEL_ID","DEFAULT_LANG_PACK","localMessages","parseTl","serializeBytes","serializeDate","toSignedLittleBuffer","tlContent","schemeContent","CACHING_SUPPORTED","localStorage","extractParams","fileContent","f","constructors","functions","isFunction","push","argToBytes","x","alloc","writeInt32LE","writeDoubleLE","getBytes","getArgFromReader","reader","arg","isVector","useVectorId","readInt","temp","len","flagIndicator","readLong","readLargeInt","readDouble","tgReadString","tgReadBool","tgReadBytes","tgReadDate","skipConstructorId","tgReadObject","createClasses","classesType","classes","classParams","constructorId","subclassOfId","argsConfig","namespace","fullName","join","VirtualClass","constructor","keys","argName","this","isFlag","flags","flagIndex","idForBytes","CONSTRUCTOR_ID","writeUInt32LE","buffers","concat","values","flagCalculate","boxed","charAt","indexOf","toUpperCase","shift","readResult","definitions","fromCache","jsonCache","getItem","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","requests","loadFromTlSchemas","setItem","obj1","obj2","assign","mergeWithNamespaces","buildApiFromTlSchema","fetchChats","limit","offsetDate","archived","withPinned","GetDialogs","offsetPeer","InputPeerEmpty","excludePinned","resultPinned","GetPinnedDialogs","DialogsNotModified","updateLocalDb","lastMessagesByChatId","buildCollectionByKey","buildApiMessage","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","Dialog","chat","lastMessage","pinned","draft","formattedText","replyingToId","buildMessageDraft","buildApiUser","chatIds","totalChatCount","DialogsSlice","count","fetchFullChat","GetFullChannel","channel","fullChat","ChannelFull","about","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","inviteLink","ChatInviteExported","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","fullInfo","slowMode","seconds","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","GetFullChat","ChatFull","getFullChatInfo","searchChats","query","Search","q","localPeerIds","myResults","allChats","allUsers","isSelf","localChats","localUsers","u","globalChats","globalUsers","fetchChat","mtpUser","GetUsers","help","GetSupport","requestChatUpdate","GetPeerDialogs","peers","InputDialogPeer","saveDraft","replyToMsgId","SaveDraft","clearDraft","updateChatMutedState","account","UpdateNotifySettings","InputNotifyPeer","settings","InputPeerNotifySettings","createChannel","CreateChannel","broadcast","newChannel","InviteToChannel","joinChannel","JoinChannel","leaveChannel","LeaveChannel","deleteChannel","DeleteChannel","createGroupChat","CreateChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","EditPhoto","InputChatUploadedPhoto","EditChatPhoto","toggleChatPinned","shouldBePinned","ToggleDialogPin","isPinned","toggleChatArchived","folders","EditPeerFolders","folderPeers","InputFolderPeer","fetchChatFolders","GetDialogFilters","byId","orderedIds","fetchRecommendedChatFolders","results","GetSuggestedDialogFilters","editChatFolder","folderUpdate","UpdateDialogFilter","deleteChatFolder","isActionSuccessful","recommendedChatFolders","toggleDialogUnread","MarkDialogUnread","unread","getChatByUsername","ResolveUsername","togglePreHistoryHidden","isEnabled","TogglePreHistoryHidden","enabled","updateChatDefaultBannedRights","EditChatDefaultBannedRights","updateChatMemberBannedRights","participant","EditBanned","updateChatAdmin","EditAdmin","updateChatTitle","EditTitle","EditChatTitle","updateChatAbout","EditChatAbout","toggleSignatures","ToggleSignatures","memberFilter","ChannelParticipantsKicked","ChannelParticipantsAdmins","ChannelParticipantsRecent","GetParticipants","ChannelParticipantsNotModified","fetchGroupsForDiscussion","GetGroupsForDiscussion","setDiscussionGroup","SetDiscussionGroup","group","migrateChat","MigrateChat","openChatByInvite","CheckChatInvite","ChatInvite","ImportChatInvite","store","addMessageToLocalDb","crypto","little","signed","randBuffer","bytesNumber","reverse","bigInt","floor","subtract","pow","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","ceil","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","generateRandomLong","mod","crc32","buf","k","makeCRCTable","isBuffer","crc","index","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","all","slice","iv","sha256","bigIntMod","remainder","add","modExp","b","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","max","random","sleep","ms","resolve","setTimeout","getByteArray","integer","bits","byteLength","convertToLittle","correct","writeUInt32BE","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","currentUserId","localMessageCounter","_currentUserId","mtpMessage","resolveMessageApiChatId","MessageService","buildApiMessageWithChatId","buildApiMessageFromShort","out","buildApiMessageFromShortChat","buildApiMessageFromNotification","notification","currentDate","localId","content","buildMessageMediaContent","sticker","contact","buildMessageTextContent","inboxDate","isOutgoing","isChatWithSelf","post","fwdFrom","senderId","isChannelPost","MessageActionEmpty","targetUserId","targetChatId","MessageActionChatCreate","MessageActionChatEditTitle","MessageActionChatEditPhoto","MessageActionChatDeletePhoto","MessageActionChatAddUser","MessageActionChatDeleteUser","MessageActionChatJoinedByLink","MessageActionChannelCreate","MessageActionChatMigrateTo","MessageActionChannelMigrateFrom","MessageActionPinMessage","MessageActionHistoryClear","MessageActionPhoneCall","video","duration","mins","round","MessageActionContactSignUp","MessageActionPaymentSent","currencySign","amount","totalAmount","toFixed","MessageActionGroupCall","addPhotoToLocalDb","buildApiPhoto","buildAction","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","messageId","replyMarkup","ReplyKeyboardMarkup","ReplyInlineMarkup","markup","rows","buttons","button","KeyboardButton","KeyboardButtonUrl","KeyboardButtonCallback","KeyboardButtonRequestPoll","KeyboardButtonBuy","MessageMediaInvoice","receiptMsgId","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","ReplyKeyboardHide","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","DraftMessageEmpty","buildStickerFromDocument","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","attr","DocumentAttributeAudio","voice","fileName","getFilenameFromDocument","buildAudio","waveform","Array","buildVoice","buildApiDocument","buildDocumentFromMedia","MessageMediaContact","buildContact","MessageMediaPoll","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","buildInvoice","buildInvoiceFromMedia","DocumentEmpty","thumbs","videoAttr","DocumentAttributeVideo","gifAttr","DocumentAttributeAnimated","w","width","h","height","supportsStreaming","roundMessage","isRound","isGif","thumbnail","buildApiThumbnailFromStripped","pollResults","rawAnswers","answer","fromCharCode","buildPollResults","rawResults","totalVoters","recentVoters","recentVoterIds","chosen","voters","isChosen","isCorrect","votersCount","sizes","PhotoSize","buildApiPhotoSize","hasDocument","defaultBase","filenameAttribute","DocumentAttributeFilename","extension","split","buildLocalMessage","replyingTo","attachment","gif","scheduledAt","filename","blobUrl","previewBlobUrl","quick","dataUri","inputWaveform","interpolateArray","buildUploadingMedia","isChannel","buildNewPoll","isScheduled","buildForwardedMessage","toChat","isAudio","asIncomingInChatWithSelf","sendingState","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","fetchMessages","pagination","RequestClass","MAIN_THREAD_ID","GetHistory","GetReplies","msgId","MessagesNotModified","threadInfos","fetchMessage","GetMessages","InputMessageID","MessageEmpty","MESSAGE_DELETED","queue","sendMessage","isSilent","noWebPage","localMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","UploadMedia","fileReference","InputMediaPhoto","InputPhoto","fetchInputMedia","InputSingleMedia","multiMedia","scheduleDate","sendGroupedMedia","noWebpage","editMessage","messageUpdate","mtpEntities","EditMessage","rescheduleMessage","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","InputMediaUploadedPhoto","InputMediaUploadedDocument","pinMessage","isUnpin","isOneSide","UpdatePinnedMessage","unpin","pmOneside","unpinAllMessages","UnpinAllMessages","deleteMessages","messageIds","shouldDeleteForAll","DeleteMessages","revoke","deleteScheduledMessages","DeleteScheduledMessages","deleteHistory","DeleteHistory","just_clear","markMessageListRead","ReadHistory","ReadDiscussion","requestThreadInfoUpdate","markMessagesRead","ReadMessageContents","topMessageResult","repliesResult","GetDiscussionMessage","offsetId","addOffset","discussionChatId","topMessageId","ChannelMessages","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","InputMessagesFilterPhotoVideo","InputMessagesFilterDocument","InputMessagesFilterUrl","InputMessagesFilterMusic","InputMessagesFilterVoice","InputMessagesFilterChatPhotos","InputMessagesFilterEmpty","topMsgId","nextOffsetId","totalCount","MessagesSlice","searchMessagesGlobal","offsetRate","SearchGlobal","nextRate","fetchWebPagePreview","GetWebPagePreview","sendPollVote","options","SendVote","loadPollOptionResults","shouldResetVoters","GetPollVotes","votes","vote","nextOffset","forwardMessages","fromChat","randomIds","ForwardMessages","fromPeer","toPeer","findFirstMessageIdAfterDate","fetchScheduledHistory","GetScheduledHistory","sendScheduledMessages","SendScheduledMessages","fetchMessageLink","ExportMessageLink","grouped","thread","fetchPinnedMessages","InputMessagesFilterPinned","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","write","fromString","obj","checked","copy","val","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parseInt","utf8Write","blitBuffer","asciiWrite","str","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","apply","decodeCodePointsArray","SlowBuffer","INSPECT_MAX_BYTES","global","foo","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","y","list","pos","swap16","swap32","swap64","arguments","equals","inspect","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","mtpUserFull","commonChatsCount","pinnedMsgId","botInfo","bio","pinnedMessageId","botDescription","UserProfilePhoto","mutualContact","isContact","buildApiUserType","status","buildApiUserStatus","bot","deleted","mtpStatus","UserStatusEmpty","UserStatusOnline","expires","UserStatusOffline","wasOnline","UserStatusRecently","UserStatusLastWeek","collection","byKey","BASE","MAX_INT","MAX_INT_ARR","smallToArray","supportsNativeBigInt","Integer","v","radix","alphabet","caseSensitive","parseBase","parseValue","BigInteger","sign","isSmall","SmallInteger","NativeBigInt","isPrecise","arrayToSmall","compareAbs","createArray","truncate","sum","l_a","l_b","carry","base","addAny","addSmall","difference","a_l","b_l","borrow","subtractSmall","multiplyLong","product","a_i","multiplySmall","shiftLeft","multiplySmallAndArray","square","divModSmall","lambda","divisor","quotient","divModAny","negate","comparison","quotientDigit","divisorMostSignificantDigit","divMod1","guess","xlen","highx","highy","check","part","unshift","divMod2","qSign","mSign","isBasicPrime","isUnit","isEven","isDivisibleBy","millerRabinTest","nPrev","prev","next","modPow","plus","subtractAny","minus","small","l1","l2","multiplyKaratsuba","ac","bd","abcd","times","_multiplyBySmall","divmod","over","_0","_1","_2","isNegative","exp","isZero","modInv","isPositive","isOdd","compareTo","notEquals","neq","gt","lt","greaterOrEquals","geq","lesserOrEquals","leq","isPrime","strict","logN","toJSNumber","isProbablePrime","iterations","rng","randBetween","lastT","lastR","newT","newR","powersOfTwo","powers2Length","highestPower2","shift_isSmall","bitwise","fn","xSign","ySign","xRem","not","yRem","xDigit","yDigit","xDivMod","yDivMod","remQuo","or","xor","roughLOB","gcd","integerLogarithm","tmp","absBase","alphabetValues","digits","parseBaseFromArray","toBase","valueOf","neg","digit","toBaseString","parseStringValue","decimalPlace","parseNumberValue","toArray","minusOne","lcm","isInstance","usedRNG","low","range","top","fromArray","messageFullId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","buildAuthStateUpdate","isCodeViaApp","hint","token","btoa","FloodWaitError","hours","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","bytesToDataUri","shouldOmitPrefix","instance","SUBCLASS_OF_ID","classType","rest","pathBytesToSvg","path","num","buildPath","DEFAULT_THUMB_SIZE","thumb","PhotoStrippedSize","realSizes","strippedPhotoToJpg","buildApiThumbnailFromCached","photoSize","buildApiThumbnailFromPath","sizeAttribute","PhotoSizeProgressive","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","InputPeerSelf","UserFull","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","ipAddress","port","api","stickerAttribute","DocumentAttributeImageSize","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","PhotoCachedSize","pathThumb","PhotoPathSize","stickerSetId","stickerSetAccessHash","buildStickerSet","animated","installedDate","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","StickerSetMultiCovered","covers","cover","coverSticker","ReadCancelledError","super","TypeNotFoundError","invalidConstructorId","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","SecurityError","BadMessageError","errorMessage","ErrorMessages","16","17","18","19","20","32","33","34","35","48","64","CdnFileTamperedError","buildApiWallpaper","wallpaper","WallPaperNoFile","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyKey","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","PrivacyValueAllowAll","PrivacyValueAllowContacts","PrivacyValueDisallowContacts","PrivacyValueDisallowAll","PrivacyValueAllowUsers","PrivacyValueDisallowUsers","PrivacyValueAllowChatParticipants","PrivacyValueDisallowChatParticipants","coreObjects","tlobjects","stream","_last","readByte","readFloat","getBuffer","padding","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","sentMessageIds","originRequest","disconnected","broken","UpdateNewMessage","UpdateNewScheduledMessage","UpdateNewChannelMessage","UpdateShortChatMessage","UpdateShortMessage","UpdateServiceNotification","has","localDbChatId","newProfilePhoto","UpdateEditMessage","UpdateEditChannelMessage","UpdateDeleteMessages","UpdateDeleteScheduledMessages","UpdateDeleteChannelMessages","existingIds","missingIds","profilePhotoIds","UpdateMessageID","UpdateShortSentMessage","newContent","isAlreadySent","UpdateReadMessagesContents","UpdateChannelReadMessagesContents","UpdateMessagePoll","pollId","apiPoll","pollUpdate","UpdateMessagePollVote","UpdateChannelMessageViews","UpdateReadHistoryInbox","stillUnreadCount","UpdateReadHistoryOutbox","UpdateReadChannelInbox","UpdateReadChannelOutbox","UpdateDialogPinned","DialogPeer","UpdatePinnedDialogs","order","dp","UpdateFolderPeers","folderPeer","UpdateDialogFilterOrder","UpdateChatParticipants","replacedMembers","UpdateChatParticipantAdd","addedMember","UpdateChatParticipantDelete","deletedMemberId","UpdatePinnedMessages","UpdatePinnedChannelMessages","NotifyPeer","showPreviews","sound","shouldShowPreviews","UpdateChatUserTyping","typingStatus","UpdateChannelUserTyping","UpdateChannel","UpdateDialogUnreadMark","UpdateChatDefaultBannedRights","UpdateUserStatus","UpdateUserName","updatedUser","UpdateUserPhoto","UpdateUserPhone","UpdatePeerSettings","peerType","UpdatePeerBlocked","isBlocked","blocked","UpdatePrivacy","UpdateContactsReset","UpdateFavedStickers","Session","_serverAddress","_dcId","_port","_takeoutId","_updateStates","_authKey","setDC","serverAddress","BinaryReader","AuthKey","_key","_hash","auxHash","keyId","getKey","shaData","other","RPCError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","capture","throttle","shouldRunFirst","interval","isPending","_args","setInterval","clearInterval","throttleWithTickEnd","throttleWith","onTickEnd","schedulerFn","waiting","cb","then","pause","checkPrimeAndGood","primeBytes","g","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","computeHash","algo","salt1","salt2","salt","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","GZIPPacked","contentRelated","gzipped","toBytes","input","gzip","ungzip","fitCount","peak","newData","springFactor","leftFiller","rightFiller","idx","File","fileBits","FileReader","onload","onerror","readAsDataURL","lastModified","blobToFile","fetchBlob","AES","default","i2ab","ab2i","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","plainText","encrypt","encrypted","Hash","algorithm","subtle","createCipheriv","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","ServerError","TimedOutError","TLMessage","seqNo","MessageContainer","containerLength","before","tlMessage","PromisedWebSockets","AsyncQueue","Connection","ip","loggers","_ip","_log","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","debug","PacketCodecClass","connect","_initConn","_connect","_sendLoop","_recvLoop","pop","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","MemorySession","sessionInfo","_authKeys","_sessionString","_storageKey","_loadFromSessionString","_fetchFromCache","mainDcId","hashes","skipUpdateStorage","_updateStorage","getAuthKey","setAuthKey","authKey","getSessionData","asHex","mainDcIdStr","mainDcKey","setKey","_saveToCache","_delete","1","TYPED_OK","Uint16Array","Int32Array","_has","sources","source","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","chunk","fnUntyped","setTyped","on","Buf8","Buf16","Buf32","2","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","buf2binstring","string2buf","c2","m_pos","str_len","buf_len","binstring2buf","buf2string","c_len","utf16buf","utf8border","3","adler","s1","s2","4","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","5","table","makeTable","6","time","xflags","os","extra","extra_len","comment","hcrc","done","7","strm","_in","last","_out","beg","dmax","wsize","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","dist","from_source","output","next_in","avail_in","next_out","avail_out","lencode","distcode","lenbits","distbits","dolen","msg","dodist","sane","8","adler32","inflate_fast","inflate_table","zswap32","InflateState","wrap","havedict","total","head","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","inflateReset","inflateReset2","windowBits","inflateInit2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","flush","here_bits","here_op","here_val","last_bits","last_op","last_val","opts","hbuf","inf_leave","data_type","inflateEnd","inflateGetHeader","inflateSetDictionary","dictionary","dictLength","inflateInfo","9","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","mask","root","curr","drop","used","huff","base_index","MAXBITS","offs","extra_index","10","0","11","zlib_inflate","strings","ZStream","GZheader","Inflate","chunkSize","opt","raw","ended","inflator","_mode","next_out_utf8","tail","utf8str","allowBufError","onEnd","onData","inflateRaw","Logger","BinaryWriter","MessagePacker","Function","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","layer","methods","ignoreIds","objAll","objByName","objByType","commentIndex","followingTypes","dt","getTime","Si","T1","Uint32Array","T2","T3","T4","T5","T6","T7","T8","right","x2","x4","tEnc","tDec","xInv","computeTables","encKey","decKey","rcon","_message","a2","b2","rounds","decrypt","AES_IGE","blockSize","cipher","cipherText","prevX","prevY","yXOR","AES_IGE$1","incrementCounter","_level","level","isBrowser","browser","__nwjs","colors","messageFormat","canSend","levels","format","toISOString","color","UserMigrateError","newDc","PhoneMigrateError","SlowModeWaitError","FloodTestPhoneWaitError","FileMigrateError","NetworkMigrateError","EmailUnconfirmedError","codeLength","LAYER","MtProtoPlainSender","MTProtoState","Helpers","doAuthentication","RPCResult","RequestState","MsgsAck","upload","MsgsStateInfo","Pong","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","MTProtoSender","DEFAULT_OPTIONS","_connection","logger","_retries","retries","_delay","delay","_autoReconnect","autoReconnect","_connectTimeout","connectTimeout","_authKeyCallback","authKeyCallback","_updateCallback","updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","isMainSender","_onConnectionBreak","onConnectionBreak","_user_connected","_reconnecting","_disconnected","_send_loop_handle","_recv_loop_handle","_state","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","attempt","_disconnect","send","append","promise","plain","time_offset","timeOffset","rejectAll","ack","msgIds","batch","encryptMessageData","body","recv","reconnect","decryptMessageData","_processMessage","handler","_handleUpdate","_popStates","toPop","containerId","reqMsgId","innerMessage","pong","badSalt","badMsgId","newServerSalt","states","extend","badMsg","errorCode","updateTimeOffset","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","_getNewMsgId","IGE","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","afterId","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","encryptIge","decryptIge","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","correctMsgId","bad","old","AESIGE","ige","RpcError","innerCode","Factorizator","RSA","sender","nonce","resPQ","ReqPqMulti","ResPQ","pq","factorize","pqInnerData","PQInnerData","targetFingerprint","fingerprint","serverPublicKeyFingerprints","serverDhParams","ReqDHParams","publicKeyFingerprint","encryptedData","ServerDHParamsOk","ServerDHParamsFail","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","ServerDHInnerData","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","ClientDHInnerData","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","SetClientDHParams","nonceTypes","DhGenOk","DhGenRetry","DhGenFail","nonceNumber","calcNewNonceHash","_queue","_pendingStates","_ready","setReady","catch","finally","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","after","writeDataAsMessage","getValue","requestState","_stream","MTProtoPlainSender","ConnectionTCPFull","ConnectionTCPAbridged","ConnectionTCPObfuscated","Mutex","mutex","WebSocketClient","w3cwebsocket","closeError","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","addEventListener","onmessage","release","acquire","canGet","resolveGet","canPush","resolvePush","returned","AbridgedPacketCodec","props","obfuscateTag","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","keywords","ok","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","answerCallbackButton","GetBotCallbackAnswer","b64","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","webpackPolyfill","deprecate","paths","children","i2abLow","int","i2abBig","ab2iLow","ab","ab2iBig","isBigEndian","s2i","authFlow","checkAuthorization","downloadFile","sizeTypes","apiId","apiHash","_useIPV6","useIPV6","baseLogger","floodSleepLimit","_eventBuilders","_phoneCodeHash","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_floodWaitedRequests","_initWith","InvokeWithLayer","InitConnection","systemVersion","langCode","langPack","systemLangCode","_config","phoneCodeHashes","_borrowedSenderPromises","_additionalDcsDisabled","_initSession","_sender","GetConfig","_updateLoop","load","attempts","Ping","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","race","_lastRequest","GetState","DC","_cleanupBorrowedSender","_borrowExportedSender","senderPromise","_createExportedSender","dc","ExportAuthorization","req","ImportAuthorization","inputLocation","messageOrMedia","_downloadPhoto","_downloadDocument","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoSizeEmpty","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","_switchDC","authParams","apiCredentials","fileParams","callback","event","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","sequentialUpdates","endianness","hostname","location","loadavg","uptime","freemem","MAX_VALUE","totalmem","cpus","networkInterfaces","getNetworkInterfaces","arch","tmpdir","tmpDir","EOL","homedir","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","ys","condition","PUBLIC_KEYS","_serverKeys","keyInfo","rand","toEncrypt","Mutex_1","_pending","isLocked","_this","ticket","_dispatchNext","runExclusive","NativeWebSocket","_global","WebSocket","MozWebSocket","websocket_version","W3CWebSocket","uri","protocols","prop","me","signInUser","botAuthToken","ImportBotAuthorization","signInBot","phoneCodeHash","signInUserWithQrCode","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","SignIn","AuthorizationSignUpRequired","signInWithPassword","SignUp","AcceptTermsOfService","isScanningComplete","inputPromise","ExportLoginToken","exceptIds","LoginToken","updatePromise","UpdateLoginToken","result2","LoginTokenSuccess","authorization","Authorization","LoginTokenMigrateTo","migratedResult","ImportLoginToken","sendResult","SendCode","CodeSettings","SentCodeTypeSms","SentCodeTypeApp","resendResult","ResendCode","passwordSrpResult","GetPassword","passwordSrpCheck","computePasswordSrpCheck","CheckPassword","Foreman","maxWorkers","requestWorker","activeWorkers","deferred","_resolve","createDeferred","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","GetFile","precise","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","SaveBigFilePart","filePart","fileTotalParts","SaveFilePart","InputFileBig","InputFile","md5Checksum","isCheckPassword","currentPassword","newPassword","email","emailCodeCallback","onEmailCodeError","pwd","newAlgo","PasswordKdfAlgoUnknown","hasPassword","InputCheckPasswordEmpty","UpdatePasswordSettings","newSettings","PasswordInputSettings","newPasswordHash","newSecureSettings","ConfirmPasswordEmail","NewMessage","Raw","StopPropagation","EventBuilder","types","func","blacklistChats","resolved","Memory","StringSession","CacheApiSession","LocalStorageSession","IdbSession","decode","serverAddressLen","dcBuffer","addressBuffer","addressLengthBuffer","portBuffer","encode","StorageSession","cached","removeItem","idb","del","promisifyRequest","oncomplete","onsuccess","onabort","createStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","defaultGetStoreFunc","defaultGetStore","customStore","setMany","entries","entry","getMany","eachCursor","openCursor","continue","items","cursor","_sessionData","_callback","skipOnUpdate","fetchFullUser","userWithFullInfo","fetchNearestCountry","dcInfo","GetNearestDc","country","fetchTopUsers","topPeers","GetTopPeers","correspondents","TopPeers","fetchContactList","GetContacts","ContactsNotModified","savedCount","fetchUsers","updateContact","ImportContacts","deleteUser","DeleteContacts","fetchProfilePhotos","GetUserPhotos","inputGifBot","fetchStickerSets","allStickers","GetAllStickers","AllStickersNotModified","sets","fetchRecentStickers","GetRecentStickers","RecentStickersNotModified","stickers","processStickerResult","fetchFavoriteStickers","GetFavedStickers","FavedStickersNotModified","fetchFeaturedStickers","GetFeaturedStickers","FeaturedStickersNotModified","faveSticker","unfave","FaveSticker","fetchStickers","GetStickerSet","packs","acc","documentId","fetchAnimatedEmojis","InputStickerSetAnimatedEmoji","searchStickers","SearchStickerSets","FoundStickerSetsNotModified","fetchSavedGifs","GetSavedGifs","SavedGifsNotModified","gifs","processGifResult","installStickerSet","InstallStickerSet","uninstallStickerSet","UninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","GetInlineBotResults","foundGif","BotInlineMediaResult","fetchStickersForEmoji","GetStickers","StickersNotModified","fetchEmojiKeywords","fromVersion","GetEmojiKeywordsDifference","emojiKeyword","keyword","emoticons","checkChatUsername","CheckUsername","setChatUsername","UpdateUsername","updatePrivateLink","ExportChatInvite","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","onRequestEmailCode","checkPassword","clearPassword","updatePassword","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","UpdateProfile","checkUsername","updateUsername","updateProfilePhoto","UploadProfilePhoto","uploadProfilePhoto","fetchWallpapers","GetWallPapers","WallPapersNotModified","filteredWallpapers","wallpapers","WallPaper","pattern","uploadWallpaper","UploadWallPaper","WallPaperSettings","fetchBlockedContacts","GetBlocked","blockedIds","BlockedSlice","blockContact","Block","unblockContact","Unblock","fetchAuthorizations","GetAuthorizations","authorizations","terminateAuthorization","ResetAuthorization","terminateAllAuthorizations","ResetAuthorizations","fetchNotificationExceptions","GetNotifyExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","GetContactSignUpNotification","GetNotifySettings","InputNotifyUsers","InputNotifyChats","InputNotifyBroadcasts","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","SetContactSignUpNotification","updateNotificationSettings","fetchLanguages","langpack","GetLanguages","fetchLangPack","sourceLangPacks","collections","GetLangPack","fetchPrivacySettings","GetPrivacy","registerDevice","secret","RegisterDevice","tokenType","appSandbox","otherUids","unregisterDevice","UnregisterDevice","setPrivacySettings","privacyRules","allowedUsers","InputPrivacyValueAllowUsers","allowedChats","InputPrivacyValueAllowChatParticipants","blockedUsers","InputPrivacyValueDisallowUsers","blockedChats","InputPrivacyValueDisallowChatParticipants","InputPrivacyValueAllowAll","InputPrivacyValueAllowContacts","InputPrivacyValueDisallowContacts","InputPrivacyValueDisallowAll","SetPrivacy","buildShippingOptions","shippingOptions","prices","cur","label","validateRequestedInfo","requestInfo","shouldSave","payments","ValidateRequestedInfo","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","SendPaymentForm","InputPaymentCredentials","DataJSON","getPaymentForm","GetPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","GetPaymentReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initClient","flushUpdatesOnTickEnd","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","sendToOrigin","callbackState","Map","postMessage","callbackArgs","lastArg","fnName","callApi"],"mappings":";aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,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FirE,GAAa,CACXlkG,KAAM,iBACNi5B,YACA3tB,MAAO,CAAEjH,QAASiH,EAAMjH,WAK1B40B,GACFkrE,GAAcxiG,OAAOs3B,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAMysD,EAAWye,GAAczmG,IAAI0D,EAAK63B,WACpCysD,IACgBA,EDvCPrgD,YAAa,GC0C1B","file":"3d0807b05cc1ab7d3c59.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 111);\n","const Api = require('./tl/api');\nconst TelegramClient = require('./client/TelegramClient');\nconst connection = require('./network');\nconst tl = require('./tl');\nconst version = require('./Version');\nconst events = require('./events');\nconst utils = require('./Utils');\nconst errors = require('./errors');\nconst sessions = require('./sessions');\nconst extensions = require('./extensions');\nconst helpers = require('./Helpers');\n\nmodule.exports = {\n Api,\n TelegramClient,\n sessions,\n connection,\n extensions,\n tl,\n version,\n events,\n utils,\n errors,\n helpers,\n};\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet';\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n) {\n // eslint-disable-next-line max-len\n const mediaMatch = url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.Document | GramJs.StickerSet | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (['msg', 'sticker', 'gif', 'wallpaper', 'photo'].includes(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiMediaFormat, ApiOnProgress, ApiSessionData, OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n client = new TelegramClient(\n new sessions.CallbackSession(sessionData, onSessionUpdate),\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || DEFAULT_USER_AGENT,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n }\n\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n }\n\n onAuthReady();\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates = typeof result & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in result && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && media.webpage.photo instanceof GramJs.Photo\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isInputPeerChannel, isInputPeerChat, isInputPeerUser, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n if (peerEntity instanceof GramJs.User) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason === undefined) {\n return {\n isRestricted: false,\n };\n }\n\n return {\n isRestricted: peerEntity.restricted,\n restrictionReason,\n };\n } else if (peerEntity instanceof GramJs.Chat) {\n return {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n };\n } else if (peerEntity instanceof GramJs.Channel) {\n const isRestricted = peerEntity.restricted\n && peerEntity.restrictionReason\n && peerEntity.restrictionReason.some((reason) => reason.platform === 'all');\n\n return {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n isRestricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n }\n return {};\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: peerEntity.migratedTo.accessHash.toString(),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return photo.photoId.toString();\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : member.userId;\n\n return {\n userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now(),\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n} as LocalDb;\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\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 mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\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\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\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 const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\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 case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\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 if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\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 if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\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 return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\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 if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\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\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n\n const lastMessagesByChatId = buildCollectionByKey(\n [...result.messages, ...(resultPinned ? resultPinned.messages : [])]\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...preparePeers(result),\n ...(resultPinned && preparePeers(resultPinned)),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = [\n ...(resultPinned ? resultPinned.dialogs : []),\n ...result.dialogs,\n ];\n\n const orderedPinnedIds: number[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = [...result.users, ...(resultPinned ? resultPinned.users : [])]\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = [...result.chats, ...result.users]\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity),\n lastMessage,\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? call.id.toString() : undefined,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted,\n}: {\n chat: ApiChat; isMuted: boolean;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : undefined }),\n }));\n\n void requestChatUpdate(chat);\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: number; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as number,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n if (result instanceof GramJs.ChatInvite) {\n await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n\n return undefined;\n } else {\n return buildApiChatFromPreview(result.chat);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\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\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\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 */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\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 */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\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\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\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 return (crc ^ (-1)) >>> 0;\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n\n};\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiKeyboardButtons,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped, buildApiPhotoSize } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { getCurrencySign } from '../../../components/middle/helpers/getCurrencySign';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || (currentDate / 1000),\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action && buildAction(mtpMessage.action, fromId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const { inlineButtons, keyboardButtons } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty || !draft.message) {\n return undefined;\n }\n\n return {\n formattedText: buildMessageTextContent(draft.message, draft.entities),\n replyingToId: draft.replyToMsgId,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\n ]);\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n const currencySign = getCurrencySign(currency);\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n description: `${currencySign}${(Number(totalAmount) / 100).toFixed(2)} ${test ? 'TEST INVOICE' : ''}`,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'siteName',\n 'title',\n 'description',\n ]),\n photo: photo && photo instanceof GramJs.Photo\n ? {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes: photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize),\n }\n : undefined,\n // TODO support video and embed\n ...(document && { hasDocument: true }),\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let text = '';\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserId = 'users' in action\n // Api returns array of userIds, but no action currently has multiple users in it\n ? action.users && action.users[0]\n : ('userId' in action && action.userId) || undefined;\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = `%action_origin% created the group «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n text = isChannelPost\n ? `Channel renamed to «${action.title}»`\n : `%action_origin% changed group name to «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n text = isChannelPost\n ? 'Channel photo updated'\n : '%action_origin% updated group photo';\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n text = isChannelPost\n ? 'Channel photo was deleted'\n : 'Chat photo was deleted';\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% joined the group'\n : '%action_origin% added %target_user% to the group';\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% left the group'\n : '%action_origin% removed %target_user% from the group';\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = '%action_origin% joined the chat from invitation link';\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Channel created';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n text = 'Migrated to %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n text = 'Migrated from %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = '%action_origin% pinned %message%';\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'Chat history was cleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n text = `${isOutgoing ? 'Outgoing' : 'Incoming'} ${action.video ? 'Video' : 'Phone'} Call`;\n\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text += ` (${mins} min${mins > 1 ? 's' : ''})`;\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = '%action_origin% joined Telegram';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n const currencySign = getCurrencySign(action.currency);\n const amount = (Number(action.totalAmount) / 100).toFixed(2);\n text = `You successfully transferred ${currencySign}${amount} to shop for %product%`;\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = `Voice chat ended (${mins} min${mins > 1 ? 's' : ''})`;\n } else {\n text = 'Voice chat started';\n }\n } else {\n text = '%ACTION_NOT_IMPLEMENTED%';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserId,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons\n} | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'Receipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return { [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000),\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: Math.round(Date.now() / 1000),\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_IMAGE_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n}) {\n const isScheduled = message.date * 1000 > Date.now();\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId,\n}: {\n chat: ApiChat; threadId: number; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate(chat);\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n hash: calculateResultHash(messages.map((message) => message.id)),\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nexport function fetchMessageLink({ chat, message }: { chat: ApiChat; message: ApiMessage }) {\n return invokeRequest(new GramJs.channels.ExportMessageLink({\n id: message.id,\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n ...(message.isInAlbum && { grouped: true }),\n ...(message.threadInfo && message.threadInfo.topMessageId !== message.id && { thread: true }),\n }));\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","/*!\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'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object 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 * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\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 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\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(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, 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 interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, 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(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\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(null, 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(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.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 that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().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)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var 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 (!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 var 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 var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\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 (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var 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 case undefined:\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) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var 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 coersion 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// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var 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 var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var 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 var length = this.length | 0\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.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 var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\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 var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var 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 (isNaN(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 (Buffer.TYPED_ARRAY_SUPPORT &&\n 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 var indexSize = 1\n var arrLength = arr.length\n var 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 var i\n if (dir) {\n var 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 var found = true\n for (var 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 var 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 // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(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 latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, 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 // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var 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 var 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 return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(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 var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var 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\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var 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 var res = ''\n var 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 var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; 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 var 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 var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\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 = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\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 var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\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 = function readUInt32BE (offset, noAssert) {\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.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var 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 var i = byteLength\n var mul = 1\n var 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 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 if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\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 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.readFloatLE = function readFloatLE (offset, noAssert) {\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 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 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 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 = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var 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 = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var 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 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var 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 var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var 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 (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\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 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 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 (!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('sourceStart out of bounds')\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 var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\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 (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\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 } else if (typeof val === 'number') {\n val = val & 255\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 var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).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 stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var 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 var byteArray = []\n for (var 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 var c, hi, lo\n var byteArray = []\n for (var 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 for (var 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\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiUser, ApiUserStatus, ApiUserType } from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo,\n } = mtpUserFull;\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n ...(botInfo && { botDescription: botInfo.description }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: buildApiUserType(mtpUser),\n ...(firstName && { firstName }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","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 = function(v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value << v.value)\r\n }\r\n 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 = function (v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value >> v.value)\r\n }\r\n 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 (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (typeof define === \"function\" && define.amd) {\r\n define( function () {\r\n return bigInt;\r\n });\r\n}\r\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid Phone Number',\n PHONE_CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","export function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","const { constructors } = require('./tl');\n\n// eslint-disable-next-line max-len\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex');\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex');\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`);\n}\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 ``check_hash`` **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 */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\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 if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity;\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf();\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new Error('User without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty\n || entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.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 constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty();\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user);\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId);\n }\n\n _raiseCastFail(entity, 'InputPeer');\n return undefined;\n}\n\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/* CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, 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/* CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\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 constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n\n/* CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/\n * tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\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 const header = Buffer.from(JPEG_HEADER);\n // eslint-disable-next-line prefer-destructuring\n header[164] = stripped[1];\n // eslint-disable-next-line prefer-destructuring\n header[166] = stripped[2];\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);\n}\n\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 constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.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 constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.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 constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\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 */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128;\n }\n if (fileSize <= 786432000) { // 750MB\n return 256;\n }\n if (fileSize <= 1572864000) { // 1500MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\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/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.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 if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\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 const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\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\nfunction _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 === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\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 ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\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: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\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 */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.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 constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction 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*/\nfunction getDC(dcId) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: 'pluto.web.telegram.org',\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: 'venus.web.telegram.org',\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: 'aurora.web.telegram.org',\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: 'vesta.web.telegram.org',\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: 'flora.web.telegram.org',\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n getAppropriatedPartSize,\n // getInputLocation,\n strippedPhotoToJpg,\n getDC,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n if (!stickerAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute.stickerset as GramJs.InputStickerSetID;\n const emoji = stickerAttribute.alt;\n const isAnimated = document.mimeType === 'application/x-tgsticker';\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo.id ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n hash,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs && thumbs.length),\n count,\n hash,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.');\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\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 if (typeof alert !== 'undefined') {\n // eslint-disable-next-line no-alert\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`);\n }\n this.invalidConstructorId = invalidConstructorId;\n this.remaining = remaining;\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\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/**\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 */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code;\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 this.code = code;\n this.payload = payload;\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.'];\n }\n super(...args);\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.');\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to '\n + 'synchronize it using msg_id notifications and re-send the original message '\n + 'with the “correct” msg_id or wrap it in a container with a new msg_id if the '\n + 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be '\n + 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id '\n + 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message (this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a '\n + 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower '\n + 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with '\n + 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with '\n + 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n };\n\n constructor(request, code) {\n let errorMessage = BadMessageError.ErrorMessages[code]\n || `Unknown error code (this should not happen): ${code}.`;\n errorMessage += ` Caused by ${request.className}`;\n super(errorMessage);\n this.message = errorMessage;\n this.code = code;\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n};\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { pick } from '../../../util/iteratees';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n","const { TypeNotFoundError } = require('../errors/Common');\nconst { coreObjects } = require('../tl/core');\nconst { tlobjects } = require('../tl/AllTLObjects');\nconst { readBigIntFromBuffer } = require('../Helpers');\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 }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0];\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res;\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n this.offset += 4;\n return res;\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4)\n .readFloatLE(0);\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\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 /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes()\n .toString('utf-8');\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false);\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 /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = tlobjects[constructorId];\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\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 for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n clazz = coreObjects[constructorId];\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n const pos = this.tellPosition();\n const error = new TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n return clazz.fromReader(this);\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected');\n }\n const count = this.readInt();\n const temp = [];\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = undefined;\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset;\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position;\n }\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 seek(offset) {\n this.offset += offset;\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader;\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now();\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[randomId.toString()];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now();\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: update.channelId,\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = update.notifySettings;\n\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isMuted,\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\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 setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\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 let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // 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) { // 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) { // 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) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // 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 if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const {\n sha1,\n toSignedLittleBuffer,\n readBufferFromBigInt,\n readBigIntFromBuffer,\n} = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { sleep } = require('../Helpers');\n\nclass AuthKey {\n constructor(value, hash) {\n if (!hash || !value) {\n return;\n }\n this._key = value;\n this._hash = hash;\n const reader = new 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 = undefined;\n this.auxHash = undefined;\n this.keyId = undefined;\n this._hash = undefined;\n return;\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 this._key = value;\n this._hash = await sha1(this._key);\n const reader = new 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 sleep(20);\n }\n }\n\n getKey() {\n return this._key;\n }\n\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}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const n = Buffer.alloc(1);\n n.writeUInt8(number, 0);\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])]);\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20);\n return readBigIntFromBuffer(shaData, true, true);\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey()\n .equals(this._key);\n }\n}\n\nmodule.exports = AuthKey;\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require('./RPCBaseErrors');\nconst { rpcErrorRe } = require('./RPCErrorList');\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex);\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1], 10) : undefined;\n return new Cls({\n request,\n capture,\n });\n }\n }\n\n return new RPCError(rpcError.errorMessage, request);\n}\n\nconst Common = require('./Common');\nconst RPCBaseErrors = require('./RPCBaseErrors');\nconst RPCErrorList = require('./RPCErrorList');\n\nmodule.exports = {\n RPCMessageToError,\n ...Common,\n ...RPCBaseErrors,\n ...RPCErrorList,\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\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 * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF1, 0x3F, 0x73,\n 0x98, 0x0D, 0x40, 0x23, 0x8E, 0x3E, 0x21, 0xC1, 0x49, 0x34, 0xD0, 0x37, 0x56, 0x3D, 0x93, 0x0F,\n 0x48, 0x19, 0x8A, 0x0A, 0xA7, 0xC1, 0x40, 0x58, 0x22, 0x94, 0x93, 0xD2, 0x25, 0x30, 0xF4, 0xDB,\n 0xFA, 0x33, 0x6F, 0x6E, 0x0A, 0xC9, 0x25, 0x13, 0x95, 0x43, 0xAE, 0xD4, 0x4C, 0xCE, 0x7C, 0x37,\n 0x20, 0xFD, 0x51, 0xF6, 0x94, 0x58, 0x70, 0x5A, 0xC6, 0x8C, 0xD4, 0xFE, 0x6B, 0x6B, 0x13, 0xAB,\n 0xDC, 0x97, 0x46, 0x51, 0x29,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g)) {\n return; // It's good\n }\n }\n throw new Error('Changing passwords unsupported');\n // checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number)\n .greater(BigInt(0))));\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([Buffer.alloc(SIZE_FOR_HASH - number.length), number]);\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false);\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp);\n\n const minDiffBitsCount = 2048 - 64;\n const maxModExpSize = 256;\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount\n || modexp.bitLength() < minDiffBitsCount\n || Math.floor((modexp.bitLength() + 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] ^= b[i];\n }\n\n return a;\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512');\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1]));\n const hash2 = await sha256(Buffer.concat([algo.salt2, hash1, algo.salt2]));\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000);\n return sha256(Buffer.concat([algo.salt2, hash3, algo.salt2]));\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\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 = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false));\n return bigNumForHash(value);\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo;\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`);\n }\n\n const pwHash = await computeHash(algo, password);\n const p = readBigIntFromBuffer(algo.p, false);\n const { g } = algo;\n const B = readBigIntFromBuffer(request.srp_B, false);\n try {\n checkPrimeAndGood(algo.p, g);\n } catch (e) {\n throw new Error('bad /g in password');\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check');\n }\n const x = readBigIntFromBuffer(pwHash, false);\n const pForHash = numBytesForHash(algo.p);\n const gForHash = bigNumForHash(g);\n const bForHash = numBytesForHash(request.srp_B);\n const gX = modExp(BigInt(g), x, p);\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([pForHash, gForHash])), false);\n const kgX = bigIntMod(k.multiply(gX), p);\n const generateAndCheckRandom = async () => {\n const randomSize = 256;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize);\n const a = readBigIntFromBuffer(random, false);\n const A = modExp(BigInt(g), a, p);\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A);\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([aForHash, bForHash])), false);\n if (u.greater(BigInt(0))) {\n return [a, aForHash, u];\n }\n }\n }\n };\n const [a, aForHash, u] = await generateAndCheckRandom();\n const gB = bigIntMod(B.subtract(kgX), p);\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 = modExp(gB, aUx, p);\n const [K, pSha, gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2),\n ]);\n const M1 = await sha256(Buffer.concat([\n xor(pSha, gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]));\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1,\n\n });\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n};\n","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\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 if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // 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.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","const AES = require('@cryptography/aes').default;\nconst {\n i2ab,\n ab2i,\n} = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue);\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes);\n this._counter = bytes;\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\nclass CTR {\n constructor(key, counter) {\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter);\n }\n\n this._counter = counter;\n\n this._remainingCounter = undefined;\n this._remainingCounterIndex = 16;\n\n this._aes = new AES(getWords(key));\n }\n\n update(plainText) {\n return this.encrypt(plainText);\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText);\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))));\n this._remainingCounterIndex = 0;\n this._counter.increment();\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];\n }\n\n return encrypted;\n }\n}\n\n// endregion\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\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\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count);\n crypto.getRandomValues(bytes);\n return bytes;\n}\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\n async digest() {\n if (this.algorithm === 'sha1') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data));\n } else if (this.algorithm === 'sha256') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data));\n }\n return undefined;\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n { name: 'PBKDF2' }, false, ['deriveBits']);\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt,\n iterations,\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm);\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2,\n};\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = undefined) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request)),\n );\n this.code = code;\n this.message = 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/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code);\n this.code = code || 303;\n this.message = message || 'ERROR_SEE_OTHER';\n }\n}\n\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 */\nclass BadRequestError extends RPCError {\n code = 400;\n\n message = 'BAD_REQUEST';\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401;\n\n message = 'UNAUTHORIZED';\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403;\n\n message = 'FORBIDDEN';\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404;\n\n message = 'NOT_FOUND';\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406;\n\n message = 'AUTH_KEY';\n}\n\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 */\nclass FloodError extends RPCError {\n code = 420;\n\n message = 'FLOOD';\n}\n\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 */\nclass ServerError extends RPCError {\n code = 500; // Also witnessed as -500\n\n message = 'INTERNAL';\n}\n\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 */\nclass TimedOutError extends RPCError {\n code = 503; // Only witnessed as -503\n\n message = 'Timeout';\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n};\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // 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 static MAXIMUM_SIZE = 1044456 - 8;\n\n // 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 static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\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 */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets();\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect() {\n this._connected = false;\n await this._recvArray.push(undefined);\n await this.socket.close();\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","/* pako 1.0.10 nodeca/pako */(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n},{\"./common\":1}],3:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n},{}],7:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],8:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":1,\"./adler32\":3,\"./crc32\":5,\"./inffast\":7,\"./inftrees\":9}],9:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":1}],10:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],11:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],\"/lib/inflate.js\":[function(require,module,exports){\n'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n},{\"./utils/common\":1,\"./utils/strings\":2,\"./zlib/constants\":4,\"./zlib/gzheader\":6,\"./zlib/inflate\":8,\"./zlib/messages\":10,\"./zlib/zstream\":11}]},{},[])(\"/lib/inflate.js\")\n});\n","const Logger = require('./Logger');\nconst BinaryWriter = require('./BinaryWriter');\nconst BinaryReader = require('./BinaryReader');\nconst PromisedWebSockets = require('./PromisedWebSockets');\nconst MessagePacker = require('./MessagePacker');\nconst AsyncQueue = require('./AsyncQueue');\n\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n};\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\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 return (crc ^ (-1)) >>> 0;\n}\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\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\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: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\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)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\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 return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // 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 called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // 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 currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\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 return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\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()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\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\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","var 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\nexport default AES;\nexport { AES_IGE$1 as CTR, AES_IGE as IGE };\n","let _level;\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug'];\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug';\n }\n\n this.isBrowser = typeof process === 'undefined'\n || process.type === 'renderer'\n || process.browser === true\n || process.__nwjs;\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 this.messageFormat = '[%t] [%l] - [%m]';\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level));\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n this._log('warn', message, this.colors.warn);\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info);\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug);\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n this._log('error', message, this.colors.error);\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message);\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level) {\n return;\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n // eslint-disable-next-line no-console\n console.log(color + this.format(message, level) + this.colors.end);\n } else {\n // eslint-disable-next-line no-console\n console.log(this.colors.start + this.format(message, level), color);\n }\n }\n }\n}\n\nmodule.exports = Logger;\n","const {\n RPCError,\n InvalidDCError,\n FloodError,\n BadRequestError,\n} = require('./RPCBaseErrors');\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`);\n this.message = `A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n this.message = `The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0);\n super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`;\n this.codeLength = codeLength;\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n];\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n EmailUnconfirmedError,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","const api = require('./api');\n\nconst LAYER = 128;\nconst tlobjects = {};\n\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\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\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst doAuthentication = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n\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 */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\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._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * Whether the user has explicitly connected or disconnected.\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 this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\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 this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\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 this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n await Helpers.sleep(this._delay);\n }\n }\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n await this._disconnect();\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\n .. code-block:: javascript\n\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\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\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 send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n // CONTEST\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n /*\n if (!Helpers.isArrayLike(request)) {\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n } else {\n throw new Error('not supported')\n } */\n }\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 async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.time_offset = res.timeOffset;\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\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 async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // 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 const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\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 try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\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._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof 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 continue;\n } else if (e instanceof 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 continue;\n } else if (e instanceof InvalidBufferError) {\n this._log.info('Broken authorization key; resetting');\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(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 // We don't really need to do this if we're going to sign in again\n /* await this.authKey.setKey(null)\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(null)\n } */\n // We can disconnect at sign in\n /* await this.disconnect()\n */\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\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 async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\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 _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\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 _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.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 BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\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 async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\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 async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _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 return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\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 _handlePong(message) {\n const pong = message.obj;\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\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 _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\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 _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\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(message.msgId);\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 BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\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 _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\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 _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\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 _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\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\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\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n delete this._pending_state[msgId];\n state.resolve(true);\n }\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 _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 const state = this._pending_state[message.msgId];\n\n if (state) {\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\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 _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n this._log.info('Started reconnecting');\n this._reconnect();\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this.disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n await this.connect(this._connection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\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 */\nconst BigInt = require('big-integer');\nconst MTProtoState = require('./MTProtoState');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { toSignedLittleBuffer } = require('../Helpers');\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\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(connection, loggers);\n this._connection = connection;\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n let body = request.getBytes();\n let msgId = this._state._getNewMsgId();\n const m = toSignedLittleBuffer(msgId, 8);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body]);\n\n await this._connection.send(res);\n body = await this._connection.recv();\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n const reader = new BinaryReader(body);\n const authKeyId = reader.readLong();\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId');\n }\n msgId = reader.readLong();\n if (msgId.eq(BigInt(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 const length = reader.readInt();\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 return reader.tgReadObject();\n }\n}\n\nmodule.exports = MTProtoPlainSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\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\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\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 */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\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 async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\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 async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, data).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\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 async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\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 const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\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 _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\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 _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\nmodule.exports = MTProtoState;\n","const { IGE: AESIGE } = require('@cryptography/aes');\nconst Helpers = require('../Helpers');\n\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new AESIGE(key, iv);\n }\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 decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\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 encryptIge(plainText) {\n const padding = plainText.length % 16;\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)]);\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n }\n}\n\nmodule.exports = IGENEW;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\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 if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // 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 return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","const BigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst RSA = require('../crypto/RSA');\nconst Helpers = require('../Helpers');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { SecurityError } = require('../errors/Common');\n\n/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\nasync function doAuthentication(sender, log) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16);\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true);\n\n const resPQ = await sender.send(new requests.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof constructors.ResPQ)) {\n throw new Error(`Step 1 answer was ${resPQ}`);\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true);\n log.debug('Finished authKey generation step 1');\n log.debug('Starting authKey generation step 2');\n // Step 2 sending: DH Exchange\n let {\n p,\n q,\n } = Factorizator.factorize(pq);\n\n // TODO Bring back after `Factorizator` fix.\n p = Helpers.getByteArray(p);\n q = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n\n const pqInnerData = new constructors.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p,\n q,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n });\n\n // sha_digest + data + random_bytes\n let cipherText;\n let targetFingerprint;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n cipherText = await RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes());\n if (cipherText !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (cipherText === undefined) {\n throw new SecurityError('Step 2 could not find a valid key for fingerprints');\n }\n\n const serverDhParams = await sender.send(\n new requests.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p,\n q,\n publicKeyFingerprint: targetFingerprint,\n encryptedData: cipherText,\n }),\n );\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk\n || serverDhParams instanceof constructors.ServerDHParamsFail)) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`);\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server');\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server');\n }\n\n if (serverDhParams instanceof constructors.ServerDHParamsFail) {\n const sh = await Helpers.sha1(Helpers.toSignedLittleBuffer(newNonce, 32)\n .slice(4, 20));\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true);\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server');\n }\n }\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`);\n }\n log.debug('Finished authKey generation step 2');\n log.debug('Starting authKey generation step 3');\n\n // Step 3 sending: Complete DH Exchange\n const {\n key,\n iv,\n } = await Helpers.generateKeyDataFromNonce(resPQ.serverNonce, newNonce);\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch');\n }\n const ige = new IGE(key, iv);\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer);\n const reader = new BinaryReader(plainTextAnswer);\n reader.read(20); // hash sum\n const serverDhInner = reader.tgReadObject();\n if (!(serverDhInner instanceof constructors.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`);\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer');\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 3 Invalid server nonce in encrypted answer');\n }\n const dhPrime = Helpers.readBigIntFromBuffer(serverDhInner.dhPrime, false, false);\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false);\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000);\n const b = Helpers.readBigIntFromBuffer(Helpers.generateRandomBytes(256), false, false);\n const gb = Helpers.modExp(BigInt(serverDhInner.g), b, dhPrime);\n const gab = Helpers.modExp(ga, b, dhPrime);\n\n // Prepare client DH Inner Data\n const clientDhInner = new constructors.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: 0, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([await Helpers.sha1(clientDhInner), clientDhInner]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new requests.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [constructors.DhGenOk, constructors.DhGenRetry, constructors.DhGenFail];\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 const { name } = dhGen.constructor;\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`);\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(`Step 3 invalid ${name} server nonce from server`);\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypes.indexOf(dhGen.constructor);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\n const dhHash = dhGen[`newNonceHash${nonceNumber}`];\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash');\n }\n\n if (!(dhGen instanceof constructors.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return {\n authKey,\n timeOffset,\n };\n}\n\n\nmodule.exports = doAuthentication;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('../extensions/BinaryWriter');\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 this.setReady(true);\n\n if (state) {\n this._pendingStates.push(state);\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {\n })\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state);\n });\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state);\n }\n this.setReady(true);\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 if (!this._queue[this._queue.length - 1]) {\n this._queue = [];\n return undefined;\n }\n let data;\n let buffer = new BinaryWriter(Buffer.alloc(0));\n\n const batch = [];\n let size = 0;\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift();\n size += state.data.length + TLMessage.SIZE_OVERHEAD;\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId;\n if (state.after) {\n afterId = state.after.msgId;\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n );\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className\n || state.request.constructor.name}`);\n batch.push(state);\n continue;\n }\n if (batch.length) {\n this._queue.unshift(state);\n break;\n }\n this._log.warn(`Message payload for ${state.request.className\n || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);\n state.reject('Request Payload is too big');\n size = 0;\n }\n if (!batch.length) {\n return undefined;\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8);\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0);\n b.writeInt32LE(batch.length, 4);\n data = Buffer.concat([b, buffer.getValue()]);\n buffer = new BinaryWriter(Buffer.alloc(0));\n const containerId = await this._state.writeDataAsMessage(\n 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 requestState.reject(new Error('Disconnect'));\n });\n }\n}\n\nmodule.exports = MessagePacker;\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n}\n\nmodule.exports = BinaryWriter;\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst doAuthentication = require('./Authenticator');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n doAuthentication,\n MTProtoSender,\n UpdateConnectionState,\n};\n","const { Mutex } = require('async-mutex');\n\nconst mutex = new Mutex();\n\nconst WebSocketClient = require('websocket').w3cwebsocket;\n\nconst closeError = new Error('WebSocket was closed');\n\nclass PromisedWebSockets {\n constructor() {\n /* CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = undefined;\n this.closed = true;\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0);\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const thisTime = await this.read(number);\n readData = Buffer.concat([readData, thisTime]);\n number -= thisTime.length;\n if (!number) {\n return readData;\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError;\n }\n await this.canRead;\n if (this.closed) {\n throw closeError;\n }\n const toReturn = this.stream.slice(0, number);\n this.stream = this.stream.slice(number);\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 const toReturn = this.stream;\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n\n return toReturn;\n }\n\n getWebSocketLink(ip, port) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`;\n } else {\n return `ws://${ip}:${port}/apiws`;\n }\n }\n\n connect(port, ip) {\n this.stream = 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);\n this.client = new WebSocketClient(this.website, 'binary');\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive();\n resolve(this);\n };\n this.client.onerror = (error) => {\n reject(error);\n };\n this.client.onclose = () => {\n this.resolveRead(false);\n this.closed = true;\n };\n // CONTEST\n // Seems to not be working, at least in a web worker\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('offline', async () => {\n await this.close();\n this.resolveRead(false);\n });\n });\n }\n\n write(data) {\n if (this.closed) {\n throw closeError;\n }\n this.client.send(data);\n }\n\n async close() {\n await this.client.close();\n this.closed = true;\n }\n\n receive() {\n this.client.onmessage = async (message) => {\n const release = await mutex.acquire();\n try {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer());\n this.stream = Buffer.concat([this.stream, data]);\n this.resolveRead(true);\n } finally {\n release();\n }\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\n","class AsyncQueue {\n constructor() {\n this._queue = [];\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n this.canPush = true;\n }\n\n async push(value) {\n await this.canPush;\n this._queue.push(value);\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 const returned = this._queue.pop();\n this.resolvePush(true);\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n}\n\nmodule.exports = AsyncQueue;\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\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 if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\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 */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\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\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result;\n}\n","'use strict'\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","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\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\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\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\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] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\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\n const buf = new Uint32Array(key.length / 4);\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] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","module.exports = `boolFalse#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#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = 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:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# 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 file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# 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:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#f4e096c3 flags:# multiple_allowed:flags.1?true can_forward:flags.2?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string = 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#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = 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#bba51639 call:InputGroupCall time_ms:long scale:int = InputFileLocation;\npeerUser#9db1bc6d user_id:int = Peer;\npeerChat#bad0e5bb chat_id:int = Peer;\npeerChannel#bddde532 channel_id:int = 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#200250ba id:int = User;\nuser#938458c1 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 id:int 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 = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?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#9ba2d800 id:int = Chat;\nchat#3bda1bde flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true id:int 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#7328bdb id:int title:string = Chat;\nchannel#d31a961e 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 id:int access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int version: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 = Chat;\nchannelForbidden#289da732 flags:# broadcast:flags.5?true megagroup:flags.8?true id:int access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#8a1e2983 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:int 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 = ChatFull;\nchannelFull#548c3f93 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 id:int 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?int 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?int 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 = ChatFull;\nchatParticipant#c8d7493e user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantCreator#da13538a user_id:int = ChatParticipant;\nchatParticipantAdmin#e2d6e436 user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3f460fed chat_id:int 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#bce383d2 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 id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int 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 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:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#cbf24940 phone_number:string first_name:string last_name:string vcard:string user_id:int = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# 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#84551347 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 = 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#a6638b9a title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#488a7337 users:Vector = MessageAction;\nmessageActionChatDeleteUser#b2ae9b0c user_id:int = MessageAction;\nmessageActionChatJoinedByLink#f89cf5e8 inviter_id:int = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#51bdb021 channel_id:int = MessageAction;\nmessageActionChannelMigrateFrom#b055eaee title:string chat_id:int = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = 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#abe9affe domain:string = 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#76b9f11a call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\ndialog#2c171f72 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 notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?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.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#df969c2d id:int bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 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 geo_distance:flags.6?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#8af40b25 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;\nuserFull#139a9a77 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 user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?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 = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int 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#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages: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#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#86cadb6c chat_id:int from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int date:int photo:UserProfilePhoto previous:Bool = 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#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int 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#12b9417b user_id:int 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#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#3f2038db flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int 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#e73547e1 flags:# query_id:long user_id:int 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#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int 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#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int 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#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int 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#42f88f2c poll_id:long user_id:int options:Vector = 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#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#6b171718 flags:# channel_id:int 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#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChat#1330a196 chat_id:int = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#a45eb99b chat_id:int call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#f3b3781f flags:# chat_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#7fecb1ec flags:# channel_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#7f9488a user_id:int date:int stopped:Bool qts:int = 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#faeff833 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#1157b858 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int 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 id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?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 saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max: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 = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int 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#4a70994c id:long access_hash:long size:int 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#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int 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;\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;\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;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 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;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int 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 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#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 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 = 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#6e24fc9d flags:# revoked:flags.0?true permanent:flags.5?true link:string admin_id:int date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title: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;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?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 count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = 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#568a748 flags:# same_peer:flags.0?true text:string query:string = 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;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = 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#352dca58 offset:int length:int user_id:int = 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;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = 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#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#50a1dfd6 flags:# left:flags.0?true peer:Peer kicked_by:int 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#2e0709a5 hash:int 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#d5348d85 flags:# multiple_allowed:flags.1?true can_forward:flags.3?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string 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#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM 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.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;\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;\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#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int 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;\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#58fffcd0 pos:int user_id:int 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#cd886e0 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 currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = 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;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#8d0b2415 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:int invoice:Invoice provider_id:int url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials 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#10b555d0 flags:# date:int bot_id:int provider_id:int 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#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int 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#9d4c17c0 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#a26f881b prev_value:int new_value:int = 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#5cdada77 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;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int 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 = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = 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#cac943f2 hash:long bot_id:int 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#5108d648 hash:int sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int 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#e0277a62 id:long access_hash:long size:int 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#badcc1a3 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 = 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 until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 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:int file_size_max:int 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#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int 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#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int 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;\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;\nstatsGroupTopPoster#18f3d0f7 user_id:int messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#6014f412 user_id:int deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#31962a4c user_id:int 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#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int 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#c95c6654 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 id:long access_hash:long participants_count:int params:flags.0?DataJSON title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#b96b25ee 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 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 params:flags.6?DataJSON = 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;\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#1e3e6680 user_id:int date:int = 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#dfd2330f admin_id:int 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;\n---functions---\n// Only needed functions from \\`api.tl\\` are manually copied here to reduce package size\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;\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#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\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#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.getWallPapers#aabb1763 hash:int = account.WallPapers;\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.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.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = 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.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\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#d4982db5 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:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec 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:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id: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#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = 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.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\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.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = 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.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = 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.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = 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#f025bc8b peer:InputPeer = messages.AffectedHistory;\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.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = 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#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = 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.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int 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;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 128\n`;","module.exports = `resPQ#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;\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;\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;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n`;","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst DEFAULT_IPV4_IP = 'venus.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: undefined,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: undefined,\n systemVersion: undefined,\n appVersion: undefined,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n };\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (apiId === undefined || apiHash === undefined) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md');\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts };\n this.apiId = apiId;\n this.apiHash = apiHash;\n this._useIPV6 = args.useIPV6;\n // this._entityCache = new Set()\n if (typeof args.baseLogger === 'string') {\n this._log = new Logger();\n } else {\n this._log = args.baseLogger;\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented');\n } catch (e) {\n session = new MemorySession();\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance');\n }\n\n this.floodSleepLimit = args.floodSleepLimit;\n this._eventBuilders = [];\n\n this._phoneCodeHash = {};\n this.session = session;\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId, 10);\n this.apiHash = apiHash;\n\n this._requestRetries = args.requestRetries;\n this._connectionRetries = args.connectionRetries;\n this._retryDelay = args.retryDelay || 0;\n if (args.proxy) {\n this._log.warn('proxies are not supported');\n }\n this._proxy = args.proxy;\n this._timeout = args.timeout;\n this._autoReconnect = args.autoReconnect;\n\n this._connection = args.connection;\n // TODO add proxy support\n\n this._floodWaitedRequests = {};\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: undefined, // no proxies yet.\n }),\n });\n };\n\n this._args = args;\n // These will be set later\n this._config = undefined;\n this.phoneCodeHashes = [];\n this._borrowedSenderPromises = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n }\n\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession();\n\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log,\n );\n\n await this._sender.connect(connection);\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n this._updateLoop();\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (this.isConnected()) {\n await Helpers.sleep(3 * 1000);\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.Ping({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n })), 1500);\n }, 3, 100);\n } catch (err) {\n await this.disconnect();\n this.connect();\n\n return;\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect();\n }\n\n await Promise.all(\n Object.values(this._borrowedSenderPromises)\n .map((promise) => {\n return promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._borrowedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n await this.disconnect();\n this.session.delete();\n this._eventBuilders = [];\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n const DC = utils.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port);\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n _cleanupBorrowedSender(dcId) {\n delete this._borrowedSenderPromises[dcId];\n }\n\n _borrowExportedSender(dcId) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n let senderPromise = this._borrowedSenderPromises[dcId];\n if (!senderPromise) {\n senderPromise = this._createExportedSender(dcId);\n this._borrowedSenderPromises[dcId] = senderPromise;\n\n senderPromise.then((sender) => {\n if (!sender) {\n delete this._borrowedSenderPromises[dcId];\n }\n });\n }\n return senderPromise;\n }\n\n async _createExportedSender(dcId) {\n const dc = utils.getDC(dcId);\n const sender = new MTProtoSender(this.session.getAuthKey(dcId),\n {\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._cleanupBorrowedSender.bind(this),\n });\n for (let i = 0; i < 5; i++) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ));\n if (this.session.dcId !== dcId) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`);\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId }));\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n }));\n await sender.send(req);\n }\n sender.dcId = dcId;\n return sender;\n } catch (e) {\n await sender.disconnect();\n }\n }\n return undefined;\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise}\n */\n downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args);\n }\n\n downloadMedia(messageOrMedia, args) {\n let media;\n if (messageOrMedia instanceof constructors.Message) {\n media = messageOrMedia.media;\n } else {\n media = messageOrMedia;\n }\n if (typeof media === 'string') {\n throw new Error('not implemented');\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args);\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args);\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args);\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args);\n }\n return undefined;\n }\n\n downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697];\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm';\n let photo;\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity;\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return undefined;\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n );\n }\n photo = entity.photo;\n }\n\n let dcId;\n let loc;\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId;\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: isBig,\n });\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return undefined;\n }\n return this.downloadFile(loc, {\n dcId,\n });\n }\n\n downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumbs || !stickerSet.thumbs.length) {\n return undefined;\n }\n\n const { thumbVersion } = stickerSet;\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash,\n }),\n thumbVersion,\n }),\n { dcId: stickerSet.thumbDcId },\n );\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i]);\n if (size) {\n return size;\n }\n }\n return undefined;\n }\n\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.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: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadWebDocument(media, args) {\n throw new Error('not implemented');\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n try {\n const promise = this._sender.send(request);\n const result = await promise;\n // this.session.processEntities(result)\n // this._entityCache.add(result)\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0];\n } catch (e) {\n this._log.warn('error while getting me');\n this._log.warn(e);\n }\n return undefined;\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect();\n }\n\n if (await checkAuthorization(this)) {\n return;\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash,\n };\n\n await authFlow(this, apiCredentials, authParams);\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams);\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback]);\n }\n\n _handleUpdate(update) {\n // this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = [];\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x);\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities);\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, undefined);\n } else {\n this._processUpdate(update, undefined);\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || [];\n const args = {\n update,\n others,\n };\n this._dispatchUpdate(args);\n }\n\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise}\n * @private\n */\n /* CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n 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\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\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.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\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 peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.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 utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\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 Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","exports.endianness = function () { return 'LE' };\n\nexports.hostname = function () {\n if (typeof location !== 'undefined') {\n return location.hostname\n }\n else return '';\n};\n\nexports.loadavg = function () { return [] };\n\nexports.uptime = function () { return 0 };\n\nexports.freemem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.totalmem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.cpus = function () { return [] };\n\nexports.type = function () { return 'Browser' };\n\nexports.release = function () {\n if (typeof navigator !== 'undefined') {\n return navigator.appVersion;\n }\n return '';\n};\n\nexports.networkInterfaces\n= exports.getNetworkInterfaces\n= function () { return {} };\n\nexports.arch = function () { return 'javascript' };\n\nexports.platform = function () { return 'browser' };\n\nexports.tmpdir = exports.tmpDir = function () {\n return '/tmp';\n};\n\nexports.EOL = '\\n';\n\nexports.homedir = function () {\n\treturn '/'\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","const BigInt = require('big-integer');\nconst { modExp } = require('../Helpers');\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(BigInt.zero)) {\n const temp = b;\n b = a.remainder(b);\n a = temp;\n }\n return a;\n }\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 static factorize(pq) {\n if (pq.remainder(2)\n .equals(BigInt.zero)) {\n return {\n p: BigInt(2),\n q: pq.divide(BigInt(2)),\n };\n }\n let y = BigInt.randBetween(BigInt(1), pq.minus(1));\n const c = BigInt.randBetween(BigInt(1), pq.minus(1));\n const m = BigInt.randBetween(BigInt(1), pq.minus(1));\n\n let g = BigInt.one;\n let r = BigInt.one;\n let q = BigInt.one;\n let x = BigInt.zero;\n let ys = BigInt.zero;\n let k;\n\n while (g.eq(BigInt.one)) {\n x = y;\n for (let i = 0; BigInt(i)\n .lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n }\n k = BigInt.zero;\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n ys = y;\n const condition = BigInt.min(m, r.minus(k));\n for (let i = 0; BigInt(i)\n .lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n q = q.multiply(x.minus(y)\n .abs())\n .remainder(pq);\n }\n g = Factorizator.gcd(q, pq);\n k = k.add(m);\n }\n\n r = r.multiply(2);\n }\n\n\n if (g.eq(pq)) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c)\n .remainder(pq);\n g = Factorizator.gcd(x.minus(ys)\n .abs(), pq);\n\n if (g.greater(1)) {\n break;\n }\n }\n }\n const p = g;\n q = pq.divide(g);\n return p < q ? {\n p,\n q,\n } : {\n p: q,\n q: p,\n };\n }\n}\n\nmodule.exports = Factorizator;\n","/* eslint-disable max-len */\nconst BigInt = require('big-integer');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n generateRandomBytes,\n modExp,\n} = require('../Helpers');\n\nconst PUBLIC_KEYS = [{\n fingerprint: [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],\n n: BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),\n e: 65537,\n}, {\n fingerprint: [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],\n n: BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),\n e: 65537,\n}, {\n fingerprint: [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],\n n: BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),\n e: 65537,\n}, {\n fingerprint: [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],\n n: BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),\n e: 65537,\n}];\n\nconst _serverKeys = {};\n\nPUBLIC_KEYS.forEach(({\n fingerprint,\n ...keyInfo\n}) => {\n _serverKeys[readBigIntFromBuffer(fingerprint.slice(-8), true, true)] = keyInfo;\n});\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 None if no key matching this fingerprint is found.\n */\nasync function encrypt(fingerprint, data) {\n const key = _serverKeys[fingerprint];\n if (!key) {\n return undefined;\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length);\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand]);\n\n // 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 const payload = readBigIntFromBuffer(toEncrypt, false);\n const encrypted = modExp(payload, BigInt(key.e), key.n);\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false);\n}\n\nmodule.exports = {\n encrypt,\n};\n","class 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\nmodule.exports = RequestState;\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex_1 = require(\"./Mutex\");\nexports.Mutex = Mutex_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._queue = [];\n this._pending = false;\n }\n Mutex.prototype.isLocked = function () {\n return this._pending;\n };\n Mutex.prototype.acquire = function () {\n var _this = this;\n var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); });\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this\n .acquire()\n .then(function (release) {\n var result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw (e);\n }\n return Promise\n .resolve(result)\n .then(function (x) { return (release(), x); }, function (e) {\n release();\n throw e;\n });\n });\n };\n Mutex.prototype._dispatchNext = function () {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","var _global = (function () {\n\tif (!this && typeof global !== 'undefined') {\n\t\treturn global;\n\t}\n\treturn this;\n})();\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar websocket_version = require('./version');\n\n\n/**\n * Expose a W3C WebSocket class with just one or two arguments.\n */\nfunction W3CWebSocket(uri, protocols) {\n\tvar native_instance;\n\n\tif (protocols) {\n\t\tnative_instance = new NativeWebSocket(uri, protocols);\n\t}\n\telse {\n\t\tnative_instance = new NativeWebSocket(uri);\n\t}\n\n\t/**\n\t * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket\n\t * class). Since it is an Object it will be returned as it is when creating an\n\t * instance of W3CWebSocket via 'new W3CWebSocket()'.\n\t *\n\t * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2\n\t */\n\treturn native_instance;\n}\nif (NativeWebSocket) {\n\t['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {\n\t\tObject.defineProperty(W3CWebSocket, prop, {\n\t\t\tget: function() { return NativeWebSocket[prop]; }\n\t\t});\n\t});\n}\n\n/**\n * Module exports.\n */\nmodule.exports = {\n 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,\n 'version' : websocket_version\n};\n","module.exports = require('../package.json').version;\n","const crypto = require('./crypto');\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !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.from(this.cipher.update(data));\n }\n}\n\nmodule.exports = CTR;\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n const me = 'phoneNumber' in authParams\n ? await signInUser(client, apiCredentials, authParams)\n : await signInBot(client, apiCredentials, authParams);\n\n // TODO @logger\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, 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 authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\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.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\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 Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep } from '../Helpers';\n\nexport interface progressCallback {\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst REQUEST_TIMEOUT = 15000;\n\n\nclass Foreman {\n private deferred: Deferred | undefined;\n\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\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\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let {\n partSizeKb, end,\n } = fileParams;\n const {\n fileSize, workers = 1,\n } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n let sender: any;\n if (dcId) {\n try {\n sender = await client._borrowExportedSender(dcId);\n } catch (e) {\n // This should never raise\n client._log.error(e);\n if (e.message === 'DC_ID_INVALID') {\n // Can't export a sender for the ID we are currently in\n sender = client._sender;\n } else {\n throw e;\n }\n }\n } else {\n sender = client._sender;\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - (offset % ONE_MB);\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n await foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async () => {\n try {\n const result = await Promise.race([\n await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset,\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(REQUEST_TIMEOUT).then(() => Promise.reject(new Error('REQUEST_TIMEOUT'))),\n ]);\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n return result.bytes;\n } catch (err) {\n hasEnded = true;\n throw err;\n } finally {\n foreman.releaseWorker();\n }\n })());\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n\n\nfunction createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve: resolve!,\n };\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\n\ninterface OnProgress {\n isCanceled?: boolean;\n\n // Float between 0 and 1.\n (progress: number): void;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst UPLOAD_TIMEOUT = 15 * 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // We always upload from the DC we are in.\n const sender = await client._borrowExportedSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\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 if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n // eslint-disable-next-line no-loop-func\n sendingParts.push((async () => {\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: j,\n fileTotalParts: partCount,\n bytes,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: j,\n bytes,\n }),\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 }\n try {\n await Promise.race([\n await Promise.all(sendingParts),\n sleep(UPLOAD_TIMEOUT * workers).then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n } catch (err) {\n if (err.message === 'TIMEOUT') {\n // eslint-disable-next-line no-console\n console.warn('Upload timeout. Retrying...');\n i -= workers;\n continue;\n }\n\n throw err;\n }\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new 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\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\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\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\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 */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\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 Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : 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 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 Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","module.exports = '0.0.2';\n","const NewMessage = require('./NewMessage');\nconst Raw = require('./Raw');\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = {\n NewMessage,\n StopPropagation,\n Raw,\n};\n","const { EventBuilder } = require('./common');\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: undefined,\n func: undefined,\n }) {\n super();\n if (!args.types) {\n this.types = true;\n } else {\n this.types = args.types;\n }\n }\n\n build(update) {\n return update;\n }\n}\n\nmodule.exports = Raw;\n","class EventBuilder {\n constructor(args = {\n chats: undefined,\n blacklistChats: undefined,\n func: undefined,\n }) {\n this.chats = args.chats;\n this.blacklistChats = Boolean(args.blacklistChats);\n this.resolved = false;\n this.func = args.func;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n build(update) {\n\n }\n}\n\n\nmodule.exports = {\n EventBuilder,\n};\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends 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\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\n * You can use custom `encode` and `decode` functions, if present:\n\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 = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\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;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs && stickerSet.thumbs.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: result.hash,\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport { buildApiWallpaper, buildApiSession, buildPrivacyRules } from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n hash: result.hash,\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: number) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildPeer(chatOrUserId),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions() {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }), true);\n\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updateLocalDb(result);\n }\n}\n\nexport async function fetchNotificationSettings() {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent || (typeof privateMuteUntil === 'number' && Date.now() < privateMuteUntil * 1000)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number' && Date.now() < groupMuteUntil * 1000)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number' && Date.now() < broadcastMuteUntil * 1000)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : undefined,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: { sourceLangPacks: string[]; langCode: string }) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: IInputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nfunction updateLocalDb(\n result: GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined,\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\n\nexport async function validateRequestedInfo({\n messageId,\n requestInfo,\n shouldSave,\n}: {\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n messageId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n messageId: number;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n messageId,\n}: {\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n msgId: messageId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({ msgId }));\n if (!result) {\n return undefined;\n }\n return buildReceipt(result);\n}\n","import {\n ApiOnProgress, ApiSessionData, ApiUpdate, OnApiUpdate,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, sessionData);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/6b9e1c477ee38548ce72.worker.js b/dist/6b9e1c477ee38548ce72.worker.js deleted file mode 100644 index a13528ac..00000000 --- a/dist/6b9e1c477ee38548ce72.worker.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see 6b9e1c477ee38548ce72.worker.js.LICENSE.txt */ -!function(e){var t={};function n(s){if(t[s])return t[s].exports;var i=t[s]={i:s,l:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(s,i,function(t){return e[t]}.bind(null,i));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=111)}([function(e,t,n){const s=n(6),i=n(81),a=n(59),r=n(21),o=n(99),c=n(100),u=n(20),d=n(29),l=n(104),f=n(42),p=n(8);e.exports={Api:s,TelegramClient:i,sessions:l,connection:a,extensions:f,tl:r,version:o,events:c,utils:u,errors:d,helpers:p}},function(e,t,n){"use strict";n.d(t,"f",(function(){return M})),n.d(t,"a",(function(){return k})),n.d(t,"b",(function(){return E})),n.d(t,"e",(function(){return R})),n.d(t,"g",(function(){return T})),n.d(t,"c",(function(){return D})),n.d(t,"i",(function(){return B})),n.d(t,"h",(function(){return x})),n.d(t,"d",(function(){return j}));var s={};n.r(s),n.d(s,"Type",(function(){return m})),n.d(s,"fetch",(function(){return y})),n.d(s,"save",(function(){return b})),n.d(s,"clear",(function(){return _}));var i=n(0),a=n(42),r=n(4),o=n(17),c=n(26),u=n(9),d=n(41),l=n(11),f=n(5),p=n(2),g=n(34);const h=self.caches;let m;async function y(e,t,n){if(h)try{const s=new Request(t),i=await h.open(e),a=await i.match(s);if(!a)return;switch(n){case m.Text:return await a.text();case m.Blob:{const e=await a.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=a.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case m.Json:return await a.json();default:return}}catch(e){return void console.warn(e)}}async function b(e,t,n){if(h)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),i=new Request(t),a=new Response(s),r=await h.open(e);return await r.put(i,a)}catch(e){return void console.warn(e)}}async function _(e){try{if(!h)return;return await h.delete(e)}catch(e){return void console.warn(e)}}async function w({url:e,mediaFormat:t,start:n,end:a},o,c,u){const{data:h,mimeType:m,fullSize:y}=await async function(e,t,n,s,a,o,c){const u=e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!u)return;if("file"===u[1]){const e=await fetch(u[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d,g=u[2];const h=u[3]?u[3].replace("?size=",""):void 0;let m;"avatar"===u[1]||"profile"===u[1]?(d=Object(p.s)(Number(g)),g=Math.abs(Number(g))):d=u[1];switch(d){case"channel":case"chat":m=f.a.chats[g];break;case"user":m=f.a.users[g];break;case"msg":m=f.a.messages[g];break;case"sticker":case"gif":case"wallpaper":m=f.a.documents[g];break;case"photo":m=f.a.photos[g];break;case"stickerSet":m=f.a.stickerSets[g]}if(!m)return;if(["msg","sticker","gif","wallpaper","photo"].includes(d)){c===l.ApiMediaFormat.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(m,{sizeType:h,start:a,end:o,progressCallback:s,workers:r.k});let n,u;return m instanceof i.Api.Message?(n=function(e,t){if(!e||!e.media)return;if(e.media instanceof i.Api.MessageMediaPhoto)return"image/jpeg";if(e.media instanceof i.Api.MessageMediaDocument&&e.media.document instanceof i.Api.Document)return t?e.media.document.attributes.some(e=>e instanceof i.Api.DocumentAttributeSticker)?"image/webp":"image/jpeg":e.media.document.mimeType;return}(m,h),m.media instanceof i.Api.MessageMediaDocument&&m.media.document instanceof i.Api.Document&&(u=m.media.document.size)):m instanceof i.Api.Photo?n="image/jpeg":"sticker"===d&&h?n="image/webp":(n=m.mimeType,u=m.size),{mimeType:n,data:e,fullSize:u}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(m);return{mimeType:c===l.ApiMediaFormat.Lottie?"application/json":v(e),data:e}}{const e=await t.downloadProfilePhoto(m,"profile"===u[1]);return{mimeType:v(e),data:e}}}(e,o,c,u,n,a,t)||{};if(!h)return;const _=await async function(e,t,n){switch(t){case l.ApiMediaFormat.DataUri:return Object(g.a)(new Blob([e],{type:n}));case l.ApiMediaFormat.BlobUrl:return new Blob([e],{type:n});case l.ApiMediaFormat.Lottie:{const t=Object(d.inflate)(e,{to:"string"});return JSON.parse(t)}case l.ApiMediaFormat.Progressive:return e.buffer}return}(h,t,m);if(!_)return;const w=t!==l.ApiMediaFormat.Progressive&&(t!==l.ApiMediaFormat.BlobUrl||_.size<=r.o);if(!r.n&&s&&w){b(e.startsWith("avatar")?r.q:r.p,e,_)}return{prepared:t===l.ApiMediaFormat.Progressive?"":function(e){if(e instanceof Blob)return URL.createObjectURL(e);return e}(_),arrayBuffer:t===l.ApiMediaFormat.Progressive?_:void 0,mimeType:m,fullSize:y}}function v(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce((e,t)=>e+t.toString(16),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(m||(m={}));var A=n(13);a.Logger.setLevel(r.h?"debug":"warn");const I={build:e=>e};let P,C,S=!1;async function M(e,t){P=e,r.g&&console.log(">>> START INIT API"),C=new i.TelegramClient(new i.sessions.CallbackSession(t,U),"739222","60d1e1063c72d4bc4cfdda99e8906f94",{deviceModel:navigator.userAgent||"Unknown UserAgent",appVersion:r.d+" Z",useWSS:!0,additionalDcsDisabled:r.l}),C.addEventHandler(O,I),C.addEventHandler(c.b,I);try{r.g&&console.log("[GramJs/client] CONNECTING"),await C.start({phoneNumber:o.g,phoneCode:o.e,password:o.f,firstAndLastNames:o.i,qrCode:o.h,onError:o.b}),r.g&&(console.log(">>> FINISH INIT API"),console.log("[GramJs/client] CONNECTED")),Object(o.c)(),P({"@type":"updateApiReady"}),j()}catch(e){throw r.g&&console.log("[GramJs/client] CONNECTING ERROR",e),e}}async function k(){await T(new i.Api.auth.LogOut),await C.destroy()}async function E(){await C.disconnect()}function R(){return C}function U(e){P({"@type":"updateSession",sessionData:e})}function O(e){e instanceof i.connection.UpdateConnectionState?S=e.state===i.connection.UpdateConnectionState.connected:e instanceof i.Api.UpdatesTooLong&&async function(){try{await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&P({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}()}async function T(e,t=!1,n=!1){if(S)try{r.g&&console.log("[GramJs/client] INVOKE "+e.className);const n=await C.invoke(e);if(r.g&&console.log("[GramJs/client] INVOKE RESPONSE "+e.className,n),t){let t;n instanceof i.Api.Updates||n instanceof i.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof i.Api.Updates||n.updates instanceof i.Api.UpdatesCombined)&&(t=n.updates),t?(!function(e){const t=[...e.users,...e.chats];e.updates.forEach(e=>{t&&(e._entities=t)})}(t),t.updates.forEach(t=>{Object(c.b)(t,e)})):n instanceof i.Api.UpdatesTooLong||Object(c.b)(n,e)}return n}catch(t){if(r.g&&(console.log("[GramJs/client] INVOKE ERROR "+e.className),console.error(t)),function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof i.Api.messages.SendMessage||t instanceof i.Api.messages.SendMedia||t instanceof i.Api.messages.SendMultiMedia),{message:s}=e;P({"@type":"error",error:{message:s,isSlowMode:n}})}(t,e),n)throw t;return}else r.g&&console.warn(`[GramJs/client] INVOKE ERROR ${e.className}: Client is not connected`)}function D(e,t){return w(e,C,S,t)}function B(e,t){return C.uploadFile({file:e,onProgress:t,workers:r.w})}function x(e){return C.updateTwoFaSettings(e)}async function j(){const e=await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}));if(!(e&&e.user instanceof i.Api.User))return;f.a.users[e.user.id]=e.user;const t=Object(A.b)(e);Object(u.o)(t.id),Object(o.d)(t)}},function(e,t,n){"use strict";(function(e){n.d(t,"s",(function(){return d})),n.d(t,"o",(function(){return l})),n.d(t,"i",(function(){return f})),n.d(t,"g",(function(){return g})),n.d(t,"l",(function(){return h})),n.d(t,"f",(function(){return m})),n.d(t,"h",(function(){return y})),n.d(t,"j",(function(){return b})),n.d(t,"d",(function(){return _})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return v})),n.d(t,"n",(function(){return A})),n.d(t,"q",(function(){return I})),n.d(t,"t",(function(){return P})),n.d(t,"u",(function(){return C})),n.d(t,"c",(function(){return S})),n.d(t,"e",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"a",(function(){return E})),n.d(t,"p",(function(){return R})),n.d(t,"k",(function(){return U}));var s=n(15),i=n.n(s),a=n(0),r=n(8),o=n(11),c=n(5),u=n(14);function d(e){return e>0?"user":e<=-1e9?"channel":"chat"}function l(e){return e>0?new a.Api.PeerUser({userId:e}):e<=-1e9?new a.Api.PeerChannel({channelId:-e}):new a.Api.PeerChat({chatId:-e})}function f(e,t){return e>0||e<=-1e9?e>0?new a.Api.InputPeerUser({userId:e,accessHash:i()(t)}):new a.Api.InputPeerChannel({channelId:-e,accessHash:i()(t)}):new a.Api.InputPeerChat({chatId:-e})}function p(e){if(e>0){const{accessHash:t}=c.a.users[e]||{};return t?new a.Api.InputPeerUser({userId:e,accessHash:t}):void 0}if(e<=-1e9){const{accessHash:t}=c.a.chats[-e]||{};return t?new a.Api.InputPeerChannel({channelId:-e,accessHash:t}):void 0}return new a.Api.InputPeerChat({chatId:-e})}function g(e,t){return e>0?new a.Api.InputUser({userId:e,accessHash:i()(t)}):e<=-1e9?new a.Api.InputChannel({channelId:-e,accessHash:i()(t)}):-e}function h(e,t){return new a.Api.InputStickerSetID({id:i()(e),accessHash:i()(t)})}function m(e){const t=c.a.documents[e.id];if(t)return new a.Api.InputDocument(Object(u.b)(t,["id","accessHash","fileReference"]))}function y(e){const t=m(e);if(t)return new a.Api.InputMediaDocument({id:t})}function b(t,n){const{summary:s,quiz:i}=t,r=new a.Api.Poll({id:n,publicVoters:s.isPublic,question:s.question,answers:s.answers.map(({text:t,option:n})=>new a.Api.PollAnswer({text:t,option:e.from(n)})),quiz:s.quiz,multipleChoice:s.multipleChoice});if(!i)return new a.Api.InputMediaPoll({poll:r});const o=i.correctAnswers.map(t=>e.from(t)),{solution:c}=i,u=i.solutionEntities?i.solutionEntities.map(A):[];return new a.Api.InputMediaPoll({poll:r,correctAnswers:o,...c&&{solution:c,solutionEntities:u}})}function _(e){const{emoticon:t,contacts:n,nonContacts:s,groups:i,channels:r,bots:o,excludeArchived:c,excludeMuted:u,excludeRead:d,pinnedChatIds:l,includedChatIds:f,excludedChatIds:g}=e,h=l?l.map(p).filter(Boolean):[],m=f?f.map(p).filter(Boolean):[],y=g?g.map(p).filter(Boolean):[];return new a.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:i||void 0,bots:o||void 0,excludeArchived:c||void 0,excludeMuted:u||void 0,excludeRead:d||void 0,broadcasts:r||void 0,pinnedPeers:h,includePeers:m,excludePeers:y})}function w(){return Object(r.readBigIntFromBuffer)(Object(r.generateRandomBytes)(8),!0,!0)}function v(e,t,n){return new a.Api.Message({id:e,peerId:l(t),fromId:l(t),media:n.media})}function A(e){const{type:t,offset:n,length:s,url:i,userId:r}=e,u=r?c.a.users[r]:void 0;switch(t){case o.ApiMessageEntityTypes.Bold:return new a.Api.MessageEntityBold({offset:n,length:s});case o.ApiMessageEntityTypes.Italic:return new a.Api.MessageEntityItalic({offset:n,length:s});case o.ApiMessageEntityTypes.Underline:return new a.Api.MessageEntityUnderline({offset:n,length:s});case o.ApiMessageEntityTypes.Strike:return new a.Api.MessageEntityStrike({offset:n,length:s});case o.ApiMessageEntityTypes.Code:return new a.Api.MessageEntityCode({offset:n,length:s});case o.ApiMessageEntityTypes.Pre:return new a.Api.MessageEntityPre({offset:n,length:s,language:""});case o.ApiMessageEntityTypes.Blockquote:return new a.Api.MessageEntityBlockquote({offset:n,length:s});case o.ApiMessageEntityTypes.TextUrl:return new a.Api.MessageEntityTextUrl({offset:n,length:s,url:i});case o.ApiMessageEntityTypes.Url:return new a.Api.MessageEntityUrl({offset:n,length:s});case o.ApiMessageEntityTypes.Hashtag:return new a.Api.MessageEntityHashtag({offset:n,length:s});case o.ApiMessageEntityTypes.MentionName:return new a.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new a.Api.InputUser({userId:r,accessHash:u.accessHash})});default:return new a.Api.MessageEntityUnknown({offset:n,length:s})}}function I(e){let t=0;return e.forEach(e=>{t=(20261*t&2147483647)+e&2147483647}),t}function P(e){const{media:t}=e;return!!t&&(t instanceof a.Api.MessageMediaPhoto||t instanceof a.Api.MessageMediaDocument||t instanceof a.Api.MessageMediaWebPage&&t.webpage instanceof a.Api.WebPage&&t.webpage.photo instanceof a.Api.Photo)}function C(e){return"photo"in e.action&&e.action.photo instanceof a.Api.Photo}function S(e){if(e instanceof a.Api.PhotoEmpty)return new a.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new a.Api.ChatPhoto({dcId:t,photoId:n})}function M({phone:e,firstName:t,lastName:n}){return new a.Api.InputPhoneContact({clientId:i()(1),phone:e,firstName:t,lastName:n})}function k(e,t=0){return new a.Api.ChatBannedRights({...e,untilDate:t})}function E(e){return new a.Api.ChatAdminRights(e)}function R(e){const{shippingAddress:t}=e;return new a.Api.PaymentRequestedInfo({...e,shippingAddress:t?new a.Api.PostAddress(t):void 0})}function U(e){switch(e){case"phoneNumber":return new a.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new a.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new a.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new a.Api.InputPrivacyKeyForwards;case"chatInvite":return new a.Api.InputPrivacyKeyChatInvite}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"k",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"f",(function(){return A})),n.d(t,"g",(function(){return I})),n.d(t,"h",(function(){return P})),n.d(t,"a",(function(){return C})),n.d(t,"b",(function(){return S}));var s=n(0),i=n(14);function a(e){return e.hasOwnProperty("userId")}function r(e){return e.hasOwnProperty("chatId")}var o=n(18);function c(e,t=!1){const n=Boolean("min"in e&&e.min),i="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&v(e.photo),r=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:r,...i&&{accessHash:i},...a&&{avatarHash:a},...(e instanceof s.Api.Channel||e instanceof s.Api.User)&&{username:e.username},..."verified"in e&&{isVerified:e.verified},..."callActive"in e&&{isCallActive:e.callActive},..."callNotEmpty"in e&&{isCallNotEmpty:e.callNotEmpty},...(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...d(e),..."creator"in e&&{isCreator:e.creator},...l(e),...f(e)}}function u(e,t){const{peer:n,folderId:s,unreadMark:i,unreadCount:a,unreadMentionsCount:r,notifySettings:{silent:o,muteUntil:u},readOutboxMaxId:d,readInboxMaxId:l}=e,f=o||"number"==typeof u&&Date.now()<1e3*u;return{id:h(n),...s&&{folderId:s},type:y(t),title:_(n,t),lastReadOutboxMessageId:d,lastReadInboxMessageId:l,unreadCount:a,unreadMentionsCount:r,isMuted:f,...i&&{hasUnreadMark:!0},...c(t)}}function d(e){return e instanceof s.Api.Chat||e instanceof s.Api.Channel?{adminRights:Object(o.b)(e.adminRights),currentUserBannedRights:e instanceof s.Api.Channel?Object(o.b)(e.bannedRights):void 0,defaultBannedRights:Object(o.b)(e.defaultBannedRights)}:{}}function l(e){if(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden)return{isRestricted:!0};if(e instanceof s.Api.User){const t=e.restricted?p(e.restrictionReason):void 0;return void 0===t?{isRestricted:!1}:{isRestricted:e.restricted,restrictionReason:t}}if(e instanceof s.Api.Chat)return{isNotJoined:e.left,isRestricted:e.kicked};if(e instanceof s.Api.Channel){const t=e.restricted&&e.restrictionReason&&e.restrictionReason.some(e=>"all"===e.platform);return{isNotJoined:e.left,isRestricted:t,restrictionReason:p(e.restrictionReason)}}return{}}function f(e){return e instanceof s.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof s.Api.InputChannelEmpty)?{migratedTo:{chatId:h(e.migratedTo),...e.migratedTo instanceof s.Api.InputChannel&&{accessHash:e.migratedTo.accessHash.toString()}}}:{}}function p(e){if(!e)return;const t=e.find(({platform:e})=>"all"===e);return t?Object(i.b)(t,["reason","text"]):void 0}function g(e,t=!1,n=!1){if(e instanceof s.Api.Chat||e instanceof s.Api.Channel||e instanceof s.Api.User||n&&(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden))return{id:e instanceof s.Api.User?e.id:-e.id,type:y(e),title:e instanceof s.Api.User?w(e):e.title,...c(e,t)}}function h(e){return a(e)?e.userId:r(e)?-e.chatId:-e.channelId}function m(e){return function(e){return e.hasOwnProperty("userId")}(e)?e.userId:function(e){return e.hasOwnProperty("chatId")}(e)?-e.chatId:function(e){return e.hasOwnProperty("channelId")}(e)?-e.channelId:void 0}function y(e){return e instanceof s.Api.User||e instanceof s.Api.UserEmpty?"chatTypePrivate":e instanceof s.Api.Chat||e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function b(e){return a(e)?"user"+e.userId:r(e)?"chat"+e.chatId:"chat"+e.channelId}function _(e,t){return a(e)?w(t):t.title}function w(e){return e.firstName?`${e.firstName}${e.lastName?" "+e.lastName:""}`:e.lastName||void 0}function v(e){if("photoId"in e)return e.photoId.toString()}function A(e){return{userId:e instanceof s.Api.ChannelParticipantBanned||e instanceof s.Api.ChannelParticipantLeft?h(e.peer):e.userId,inviterId:"inviterId"in e?e.inviterId:void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?e.kickedBy:void 0,promotedByUserId:"promotedBy"in e?e.promotedBy:void 0,bannedRights:"bannedRights"in e?Object(o.b)(e.bannedRights):void 0,adminRights:"adminRights"in e?Object(o.b)(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof s.Api.ChannelParticipantAdmin||e instanceof s.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof s.Api.ChannelParticipantCreator||e instanceof s.Api.ChatParticipantCreator)&&{isOwner:!0}}}function I(e){return e instanceof s.Api.ChatParticipants||e instanceof s.Api.channels.ChannelParticipants?e.participants.map(A).filter(Boolean):void 0}function P(e){let t="";if(!(e.action instanceof s.Api.SendMessageCancelAction))return e.action instanceof s.Api.SendMessageTypingAction?t="lng_user_typing":e.action instanceof s.Api.SendMessageRecordVideoAction?t="lng_send_action_record_video":e.action instanceof s.Api.SendMessageUploadVideoAction?t="lng_send_action_upload_video":e.action instanceof s.Api.SendMessageRecordAudioAction?t="lng_send_action_record_audio":e.action instanceof s.Api.SendMessageUploadAudioAction?t="lng_send_action_upload_audio":e.action instanceof s.Api.SendMessageUploadPhotoAction?t="lng_send_action_upload_photo":e.action instanceof s.Api.SendMessageUploadDocumentAction?t="lng_send_action_upload_file":e.action instanceof s.Api.SendMessageGeoLocationAction?t="selecting a location to share":e.action instanceof s.Api.SendMessageChooseContactAction?t="selecting a contact to share":e.action instanceof s.Api.SendMessageGamePlayAction?t="lng_playing_game":e.action instanceof s.Api.SendMessageRecordRoundAction?t="lng_send_action_record_round":e.action instanceof s.Api.SendMessageUploadRoundAction&&(t="lng_send_action_upload_round"),{action:t,...!(e instanceof s.Api.UpdateUserTyping)&&{userId:h(e.fromId)},timestamp:Date.now()}}function C(e){return{...Object(i.c)(e,["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"]),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(m).filter(Boolean),includedChatIds:e.includePeers.map(m).filter(Boolean),excludedChatIds:e.excludePeers.map(m).filter(Boolean)}}function S({filter:e,description:t}){return{...C(e),description:t}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return s})),n.d(t,"g",(function(){return i})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return r})),n.d(t,"n",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"q",(function(){return u})),n.d(t,"o",(function(){return d})),n.d(t,"c",(function(){return l})),n.d(t,"b",(function(){return f})),n.d(t,"k",(function(){return p})),n.d(t,"w",(function(){return g})),n.d(t,"r",(function(){return h})),n.d(t,"t",(function(){return m})),n.d(t,"f",(function(){return y})),n.d(t,"u",(function(){return b})),n.d(t,"m",(function(){return _})),n.d(t,"s",(function(){return w})),n.d(t,"v",(function(){return v})),n.d(t,"a",(function(){return A})),n.d(t,"e",(function(){return I})),n.d(t,"j",(function(){return P})),n.d(t,"i",(function(){return C}));const s="e319dcb",i=!1,a=!1,r=!1,o=!1,c="tt-media",u="tt-media-avatars",d=524288,l=300,f=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),p=16,g=16,h=("undefined"!=typeof window&&window.innerHeight,200),m=50,y=100,b=40,_=1e9,w="MEMOJI_STICKER",v=777e3,A=0,I=1,P=777,C="android"},function(e,t,n){"use strict";t.a={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{}}},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{parseTl:i,serializeBytes:a,serializeDate:r}=n(44),{toSignedLittleBuffer:o}=n(8),c=n(79),u=n(80),d="undefined"!=typeof self&&void 0!==self.localStorage;function l(e){const t=i(e,109),n=[],s=[];for(const e of t)e.isFunction?s.push(e):n.push(e);return[n,s]}function f(e,n){switch(n){case"int":{const n=t.alloc(4);return n.writeInt32LE(e,0),n}case"long":return o(e,8);case"int128":return o(e,16);case"int256":return o(e,32);case"double":{const n=t.alloc(8);return n.writeDoubleLE(e,0),n}case"string":return a(e);case"Bool":return e?t.from("b5757299","hex"):t.from("379779bc","hex");case"true":return t.alloc(0);case"bytes":return a(e);case"date":return r(e);default:return e.getBytes()}}function p(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let i=0;i{this[e]=t[e]})}static fromReader(e){const t={};for(const n in c)if(c.hasOwnProperty(n)){const s=c[n];if(s.isFlag){if("true"===s.type){t[n]=Boolean(t.flags&1<f(t,c[e].type))))}else if(c[e].flagIndicator)if(Object.values(c).some(e=>e.isFlag)){let e=0;for(const t in c)c[t].isFlag&&(!1===this[t]&&"true"===c[t].type||void 0===this[t]?e|=0:e|=1</);if(n){t.readInt();const e=[],s=t.readInt();if("int"===n[1])for(let n=0;n{"function"!=typeof t[e]&&n[e]?Object.assign(n[e],t[e]):n[e]=t[e]}),n}(g("constructor",e.constructors),g("request",e.requests))}()}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"p",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"k",(function(){return m})),n.d(t,"w",(function(){return y})),n.d(t,"h",(function(){return b})),n.d(t,"u",(function(){return _})),n.d(t,"v",(function(){return w})),n.d(t,"a",(function(){return v})),n.d(t,"H",(function(){return A})),n.d(t,"b",(function(){return I})),n.d(t,"q",(function(){return P})),n.d(t,"r",(function(){return C})),n.d(t,"d",(function(){return S})),n.d(t,"c",(function(){return M})),n.d(t,"g",(function(){return k})),n.d(t,"z",(function(){return E})),n.d(t,"y",(function(){return R})),n.d(t,"i",(function(){return U})),n.d(t,"n",(function(){return O})),n.d(t,"f",(function(){return T})),n.d(t,"e",(function(){return D})),n.d(t,"A",(function(){return B})),n.d(t,"o",(function(){return x})),n.d(t,"B",(function(){return j})),n.d(t,"F",(function(){return N})),n.d(t,"G",(function(){return V})),n.d(t,"E",(function(){return F})),n.d(t,"I",(function(){return L})),n.d(t,"D",(function(){return q})),n.d(t,"C",(function(){return H})),n.d(t,"m",(function(){return K})),n.d(t,"l",(function(){return z})),n.d(t,"x",(function(){return G})),n.d(t,"s",(function(){return W})),n.d(t,"t",(function(){return $}));var s=n(0),i=n(4),a=n(1),r=n(3),o=n(9),c=n(13),u=n(14),d=n(5),l=n(2),f=n(16);let p;function g(e){p=e}async function h({limit:e,offsetDate:t,archived:n,withPinned:d}){const l=await Object(a.g)(new s.Api.messages.GetDialogs({offsetPeer:new s.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?i.e:void 0,...d&&{excludePinned:!0}})),f=d?await Object(a.g)(new s.Api.messages.GetPinnedDialogs({folderId:n?i.e:void 0})):void 0;if(!l||l instanceof s.Api.messages.DialogsNotModified)return;Z(l),f&&Z(f);const p=Object(u.a)([...l.messages,...f?f.messages:[]].map(o.b).filter(Boolean),"chatId"),g={...J(l),...f&&J(f)},h=[],m={},y={},b=[...f?f.dialogs:[],...l.dialogs],_=[];b.forEach(e=>{if(!(e instanceof s.Api.Dialog)||!n&&e.folderId===i.e||n&&e.folderId!==i.e)return;const t=g[Object(r.k)(e.peer)],a=Object(r.c)(e,t);if(a.lastMessage=p[a.id],h.push(a),d&&e.pinned&&_.push(a.id),e.draft){const{formattedText:t,replyingToId:n}=Object(o.h)(e.draft)||{};t&&(m[a.id]=t),n&&(y[a.id]=n)}});const w=[...l.users,...f?f.users:[]].map(c.a).filter(Boolean),v=h.map(e=>e.id);let A;return A=l instanceof s.Api.messages.DialogsSlice?l.count:v.length,{chatIds:v,chats:h,users:w,draftsById:m,replyingToById:y,orderedPinnedIds:d?_:void 0,totalChatCount:A}}function m(e){const{id:t,accessHash:n,adminRights:i}=e;return Object(l.g)(t,n)instanceof s.Api.InputChannel?async function(e,t,n){const i=await Object(a.g)(new s.Api.channels.GetFullChannel({channel:Object(l.g)(e,t)}));if(!(i&&i.fullChat instanceof s.Api.ChannelFull))return;const{about:o,onlineCount:c,exportedInvite:u,slowmodeSeconds:d,slowmodeNextSendDate:f,migratedFromChatId:p,migratedFromMaxId:g,canViewParticipants:h,linkedChatId:m,hiddenPrehistory:y,call:b}=i.fullChat,_=u instanceof s.Api.ChatInviteExported?u.link:void 0,{members:w,users:v}=h&&await K(e,t)||{},{members:A,users:I}=h&&n&&await K(e,t,"kicked")||{},{members:P,users:C}=h&&n&&await K(e,t,"admin")||{};return{fullInfo:{about:o,onlineCount:c,inviteLink:_,slowMode:d?{seconds:d,nextSendDate:f}:void 0,migratedFrom:p?{chatId:Object(r.j)({chatId:p}),maxMessageId:g}:void 0,canViewMembers:h,isPreHistoryHidden:y,members:w,kickedMembers:A,adminMembers:P,groupCallId:b?b.id.toString():void 0,linkedChatId:m?Object(r.j)({chatId:m}):void 0},users:[...v||[],...I||[],...C||[]]}}(t,n,i):async function(e){const t=await Object(a.g)(new s.Api.messages.GetFullChat({chatId:Object(l.g)(e)}));if(!(t&&t.fullChat instanceof s.Api.ChatFull))return;Z(t);const{about:n,participants:i,exportedInvite:o}=t.fullChat,u=Object(r.g)(i),d=u?u.filter(({isAdmin:e,isOwner:t})=>e||t):void 0;return{fullInfo:{about:n,members:u,adminMembers:d,canViewMembers:!0,...o&&{inviteLink:o.link}},users:t.users.map(c.a).filter(Boolean)}}(t)}async function y({query:e}){const t=await Object(a.g)(new s.Api.contacts.Search({q:e}));if(!t)return;Z(t);const n=t.myResults.map(r.j),i=[...t.chats,...t.users].map(e=>Object(r.d)(e)).filter(Boolean),o=t.users.map(c.a).filter(e=>!!e&&!e.isSelf);return{localChats:i.filter(e=>n.includes(e.id)),localUsers:o.filter(e=>n.includes(e.id)),globalChats:i.filter(e=>!n.includes(e.id)),globalUsers:o.filter(e=>!n.includes(e.id))}}async function b({type:e,user:t}){let n;if("self"===e||"user"===e){const i=await Object(a.g)(new s.Api.users.GetUsers({id:["user"===e&&t?Object(l.g)(t.id,t.accessHash):new s.Api.InputUserSelf]}));if(!i||!i.length)return;[n]=i}else if("support"===e){const e=await Object(a.g)(new s.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const i=Object(r.d)(n,"support"===e);if(i)return p({"@type":"updateChat",id:i.id,chat:i}),{chatId:i.id}}async function _(e){const{id:t,accessHash:n}=e,i=await Object(a.g)(new s.Api.messages.GetPeerDialogs({peers:[new s.Api.InputDialogPeer({peer:Object(l.i)(t,n)})]}));if(!i)return;const c=i.dialogs[0];if(!(c&&c instanceof s.Api.Dialog))return;const u=J(i)[Object(r.k)(c.peer)];if(!u)return;Z(i);const d=Object(o.b)(i.messages[0]);p({"@type":"updateChat",id:t,chat:{...Object(r.c)(c,u),lastMessage:d}})}function w({chat:e,text:t,entities:n,replyToMsgId:i}){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:t,...n&&{entities:n.map(l.n)},replyToMsgId:i}))}function v(e){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:""}))}async function A({chat:e,isMuted:t}){await Object(a.g)(new s.Api.account.UpdateNotifySettings({peer:new s.Api.InputNotifyPeer({peer:Object(l.i)(e.id,e.accessHash)}),settings:new s.Api.InputPeerNotifySettings({muteUntil:t?2**31-1:void 0})})),_(e)}async function I({title:e,about:t,users:n}){const o=await Object(a.g)(new s.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(o instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected channel creation update",o));const c=o.chats[0];if(!(c&&c instanceof s.Api.Channel))return void(i.g&&console.error("Created channel not found",o));const u=Object(r.d)(c);return await Object(a.g)(new s.Api.channels.InviteToChannel({channel:Object(l.g)(u.id,u.accessHash),users:n.map(({id:e,accessHash:t})=>Object(l.g)(e,t))})),u}function P({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.JoinChannel({channel:Object(l.g)(e,t)}),!0)}function C({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.LeaveChannel({channel:Object(l.g)(e,t)}),!0)}function S({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.DeleteChannel({channel:Object(l.g)(e,t)}),!0)}async function M({title:e,users:t}){const n=await Object(a.g)(new s.Api.messages.CreateChat({title:e,users:t.map(({id:e,accessHash:t})=>Object(l.g)(e,t))}),!0);if(!(n instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected chat creation update",n));const o=n.chats[0];if(o&&o instanceof s.Api.Chat)return Object(r.d)(o);i.g&&console.error("Created chat not found",n)}async function k({chatId:e,accessHash:t,photo:n}){const i=await Object(a.i)(n),r=Object(l.g)(e,t);return Object(a.g)(r instanceof s.Api.InputChannel?new s.Api.channels.EditPhoto({channel:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}):new s.Api.messages.EditChatPhoto({chatId:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}),!0)}async function E({chat:e,shouldBePinned:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.ToggleDialogPin({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),pinned:t||void 0}))&&p({"@type":"updateChatPinned",id:e.id,isPinned:t})}function R({chat:e,folderId:t}){const{id:n,accessHash:i}=e;return Object(a.g)(new s.Api.folders.EditPeerFolders({folderPeers:[new s.Api.InputFolderPeer({peer:Object(l.i)(n,i),folderId:t})]}),!0)}async function U(){const e=await Object(a.g)(new s.Api.messages.GetDialogFilters);if(e)return{byId:Object(u.a)(e.map(r.a),"id"),orderedIds:e.map(({id:e})=>e)}}async function O(){const e=await Object(a.g)(new s.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(r.b)}async function T({id:e,folderUpdate:t}){const n=Object(l.d)(t);await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&p({"@type":"updateChatFolder",id:e,folder:t})}async function D(e){const t=await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await O();t&&p({"@type":"updateChatFolder",id:e,folder:void 0}),n&&p({"@type":"updateRecommendedChatFolders",folders:n})}async function B({chat:e,hasUnreadMark:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.MarkDialogUnread({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),unread:t||void 0}))&&p({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function x(e){const t=await Object(a.g)(new s.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:i}=t,o=i.length?Object(r.d)(i[0]):Object(r.d)(n[0]);return o?(Z(t),o):void 0}function j({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.TogglePreHistoryHidden({channel:r,enabled:t}),!0)}function N({chat:e,bannedRights:t}){const{id:n,accessHash:i}=e,r=Object(l.i)(n,i);return Object(a.g)(new s.Api.messages.EditChatDefaultBannedRights({peer:r,bannedRights:Object(l.b)(t)}),!0)}function V({chat:e,user:t,bannedRights:n}){const i=Object(l.g)(e.id,e.accessHash),r=Object(l.i)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditBanned({channel:i,participant:r,bannedRights:Object(l.b)(n)}),!0)}function F({chat:e,user:t,adminRights:n,customTitle:i=""}){const r=Object(l.g)(e.id,e.accessHash),o=Object(l.g)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditAdmin({channel:r,userId:o,adminRights:Object(l.a)(n),rank:i}),!0)}async function L(e,t){const n=Object(l.g)(e.id,e.accessHash);await Object(a.g)(n instanceof s.Api.InputChannel?new s.Api.channels.EditTitle({channel:n,title:t}):new s.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function q(e,t){await Object(a.g)(new s.Api.messages.EditChatAbout({peer:Object(l.i)(e.id,e.accessHash),about:t}))&&p({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function H({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.ToggleSignatures({channel:r,enabled:t}),!0)}async function K(e,t,n="recent",o){let u;switch(n){case"kicked":u=new s.Api.ChannelParticipantsKicked({q:""});break;case"admin":u=new s.Api.ChannelParticipantsAdmins;break;default:u=new s.Api.ChannelParticipantsRecent}const d=await Object(a.g)(new s.Api.channels.GetParticipants({channel:Object(l.g)(e,t),filter:u,offset:o,limit:i.r}));if(d&&!(d instanceof s.Api.channels.ChannelParticipantsNotModified))return Z(d),{members:Object(r.g)(d),users:d.users.map(c.a).filter(Boolean)}}async function z(){const e=await Object(a.g)(new s.Api.channels.GetGroupsForDiscussion);if(e)return Z(e),e.chats.map(e=>Object(r.d)(e))}function G({channel:e,chat:t}){return Object(a.g)(new s.Api.channels.SetDiscussionGroup({broadcast:Object(l.i)(e.id,e.accessHash),group:t?Object(l.i)(t.id,t.accessHash):new s.Api.InputChannelEmpty}))}async function W(e){const t=await Object(a.g)(new s.Api.messages.MigrateChat({chatId:Object(l.g)(e.id)}),!0);if(t&&t instanceof s.Api.Updates)return Z(t),Object(r.d)(t.chats[1]);i.g&&console.error("Unexpected channel creation update",t)}async function $(e){const t=await Object(a.g)(new s.Api.messages.CheckChatInvite({hash:e}));if(t)return t instanceof s.Api.ChatInvite?void await Object(a.g)(new s.Api.messages.ImportChatInvite({hash:e}),!0):Object(r.d)(t.chat)}function J(e){const t={};return e.chats.forEach(e=>{t["chat"+e.id]=e}),e.users.forEach(e=>{t["user"+e.id]=e}),t}function Z(e){"users"in e&&e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),"chats"in e&&e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),"messages"in e&&e.messages.forEach(e=>{e instanceof s.Api.Message&&Object(l.t)(e)&&Object(f.a)(e)})}},function(e,t,n){(function(t){const s=n(15),i=n(35);function a(e,n=!0,i=!1){let a=t.from(e);const r=a.length;n&&(a=a.reverse());let o=s(a.toString("hex"),16);return i&&Math.floor(o.toString("2").length/8)>=r&&(o=o.subtract(s(2).pow(s(8*r)))),o}function r(e,n=8){const i=s(e),a=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0},generateRandomBytes:c,generateKeyDataFromNonce:async function(e,n){e=r(e,16),n=r(n,32);const[s,i,a]=await Promise.all([u(t.concat([n,e])),u(t.concat([e,n])),u(t.concat([n,n]))]);return{key:t.concat([s,i.slice(0,12)]),iv:t.concat([i.slice(12,20),a,n.slice(0,4)])}},sha1:u,sha256:function(e){const t=i.createHash("sha256");return t.update(e),t.digest()},bigIntMod:function(e,t){return e.remainder(t).add(t).remainder(t)},modExp:function(e,t,n){e=e.remainder(n);let i=s.one,a=e;for(;t.greater(s.zero);){const e=t.remainder(s(2));t=t.divide(s(2)),e.eq(s.one)&&(i=i.multiply(a),i=i.remainder(n)),a=a.multiply(a),a=a.remainder(n)}return i},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise(t=>setTimeout(t,e)),getByteArray:function(e,t=!1){const n=e.toString(2).length,i=Math.floor((n+8-1)/8);return o(s(e),i,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const n=t.alloc(4*e.length);for(let t=0;t1?"s":""})`}}else if(e instanceof s.Api.MessageActionContactSignUp)o="%action_origin% joined Telegram";else if(e instanceof s.Api.MessageActionPaymentSent){const t=l(e.currency),n=(Number(e.totalAmount)/100).toFixed(2);o=`You successfully transferred ${t}${n} to shop for %product%`}else if(e instanceof s.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);o=`Voice chat ended (${t} min${t>1?"s":""})`}else o="Voice chat started";else o="%ACTION_NOT_IMPLEMENTED%";"photo"in e&&e.photo instanceof s.Api.Photo&&(Object(p.b)(e.photo),a=Object(c.a)(e.photo));return{text:o,type:u,targetUserId:d,targetChatId:f,photo:a}}(t.action,n,Boolean(t.post),a);u&&(o.action=u);const{replyToMsgId:d,replyToTopId:f}=t.replyTo||{},h=t.editDate&&!t.editHide,{inlineButtons:m,keyboardButtons:y}=function(e){const{id:t,replyMarkup:n,media:i}=e;if(!n)return i instanceof s.Api.MessageMediaWebPage&&i.webpage instanceof s.Api.WebPage&&"telegram_message"===i.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:i.webpage.url}]]}:void 0;if(!(n instanceof s.Api.ReplyKeyboardMarkup||n instanceof s.Api.ReplyInlineMarkup))return;const a=n.rows.map(({buttons:e})=>e.map(e=>{let n,a,{text:r}=e;return e instanceof s.Api.KeyboardButton?(n="command",a=r):e instanceof s.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof s.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof s.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof s.Api.KeyboardButtonBuy?(i instanceof s.Api.MessageMediaInvoice&&i.receiptMsgId&&(r="Receipt",a=i.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:r,messageId:t,value:a}}));return{[n instanceof s.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a}}(t)||{},b=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&Object(r.j)(e.savedFromPeer),s=e.fromId&&Object(r.j)(e.fromId);return{isChannelPost:Boolean(e.channelPost),isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,i),{replies:_,mediaUnread:w,postAuthor:v}=t,I=t.groupedId&&t.groupedId.toString(),C=Boolean(I)&&!(o.document||o.audio),S=t.replyMarkup instanceof s.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:a,content:o,date:t.date,senderId:n||t.out&&t.post&&g||e,views:t.views,isFromScheduled:t.fromScheduled,...d&&{replyToMessageId:d},...f&&{replyToTopMessageId:f},...b&&{forwardInfo:b},...h&&{isEdited:h},...w&&{isMediaUnread:w},...t.mentioned&&w&&{hasUnreadMention:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:m,...y&&{keyboardButtons:y},...S&&{shouldHideKeyboardButtons:S},...t.viaBotId&&{viaBotId:t.viaBotId},..._&&_.comments&&{threadInfo:B(_,t.id,e)},...v&&{adminTitle:v}}}function A(e,t){return{text:e,...t&&{entities:t.map(D)}}}function I(e){if(!(e instanceof s.Api.DraftMessageEmpty)&&e.message)return{formattedText:A(e.message,e.entities),replyingToId:e.replyToMsgId}}function P(e){const t=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;return Object(o.a)(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(!(e instanceof s.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof s.Api.Photo))return;if(e.ttlSeconds)return;return Object(c.a)(e.photo)}(e);if(n)return{photo:n};const i=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document instanceof s.Api.Document&&e.document.mimeType.startsWith("video")))return;return C(e.document)}(e);if(i)return{video:i};const r=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||t.voice)return;return{fileName:R(e.document,"audio"),...Object(a.b)(e.document,["size","mimeType"]),...Object(a.b)(t,["duration","performer","title"])}}(e);if(r)return{audio:r};const u=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||!t.voice)return;const{duration:n,waveform:i}=t;return{duration:n,waveform:i?Array.from(i):void 0}}(e);if(u)return{voice:u};const d=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document))return;if(e.ttlSeconds)return;return S(e.document)}(e);if(d)return{document:d};const f=function(e){if(!(e instanceof s.Api.MessageMediaContact))return;return Object(a.b)(e,["firstName","lastName","phoneNumber","userId"])}(e);if(f)return{contact:f};const p=function(e){if(!(e instanceof s.Api.MessageMediaPoll))return;return M(e.poll,e.results)}(e);if(p)return{poll:p};const g=E(e);if(g)return{webPage:g};const h=function(e){if(!(e instanceof s.Api.MessageMediaInvoice))return;return function(e){const{description:t,title:n,photo:s,test:i,totalAmount:a,currency:r,receiptMsgId:o}=e,c=l(r);return{text:t,title:n,photoUrl:s&&s.url,receiptMsgId:o,description:`${c}${(Number(a)/100).toFixed(2)} ${i?"TEST INVOICE":""}`}}(e)}(e);return h?{invoice:h}:void 0}function C(e){if(e instanceof s.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:i,size:a,attributes:r}=e,o=r.find(e=>e instanceof s.Api.DocumentAttributeVideo);if(!o)return;const u=r.find(e=>e instanceof s.Api.DocumentAttributeAnimated),{duration:d,w:l,h:f,supportsStreaming:p=!1,roundMessage:g=!1}=o;return{id:String(t),mimeType:n,duration:d,fileName:R(e,"video"),width:l,height:f,supportsStreaming:p,isRound:g,isGif:Boolean(u),thumbnail:Object(c.e)(i),size:a}}function S(e){if(!(e instanceof s.Api.Document))return;const{id:t,size:n,mimeType:i,date:a,thumbs:r}=e,o=r&&Object(c.e)(r);return{id:String(t),size:n,mimeType:i,timestamp:a,fileName:R(e),thumbnail:o}}function M(e,t){const{id:n,answers:s}=e,i=s.map(e=>({text:e.text,option:String.fromCharCode(...e.option)}));return{id:n.toString(),summary:{isPublic:e.publicVoters,...Object(a.b)(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:i},results:k(t)}}function k(e){const{results:t,totalVoters:n,recentVoters:s,solution:i,solutionEntities:a}=e;return{totalVoters:n,recentVoterIds:s,results:t&&t.map(({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})),solution:i,...a&&{solutionEntities:a.map(D)}}}function E(e){if(!(e instanceof s.Api.MessageMediaWebPage&&e.webpage instanceof s.Api.WebPage))return;const{id:t,photo:n,document:i}=e.webpage;return{id:Number(t),...Object(a.b)(e.webpage,["url","displayUrl","siteName","title","description"]),photo:n&&n instanceof s.Api.Photo?{id:String(n.id),thumbnail:Object(c.e)(n.sizes),sizes:n.sizes.filter(e=>e instanceof s.Api.PhotoSize).map(c.b)}:void 0,...i&&{hasDocument:!0}}}function R(e,t="file"){const{mimeType:n,attributes:i}=e,a=i.find(e=>e instanceof s.Api.DocumentAttributeFilename);if(a)return a.fileName;const r=n.split("/")[1];return`${t}${String(e.id)}.${r}`}function U(e,t,n,s,i,a,r,o,c,d){const l=h++,f=i&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:i,size:a}=e;if(e.quick){const{width:r,height:o,duration:c}=e.quick;return i.startsWith("image/")?{photo:{id:"temp",sizes:[],thumbnail:{width:r,height:o,dataUri:""},blobUrl:n}}:{video:{id:"temp",mimeType:i,duration:c||0,fileName:t,width:r,height:o,blobUrl:n,...s&&{thumbnail:{width:r,height:o,dataUri:s}},size:a}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=Object(u.a)(n,63);return{voice:{duration:t,waveform:s}}}return i.startsWith("audio/")?{audio:{mimeType:i,fileName:t,size:a,duration:200}}:{document:{mimeType:i,fileName:t,size:a,...s&&{previewBlobUrl:s}}}}(i),p="chatTypeChannel"===e.type;return{id:l,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...a&&{sticker:a},...r&&{video:r},...o&&T(o,l)},date:d||Math.round(Date.now()/1e3),isOutgoing:!p,senderId:g,...s&&{replyToMessageId:s},...c&&{groupedId:c,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}function O(e,t){const n=h++,{content:s,chatId:i,id:a,senderId:r,groupedId:o,isInAlbum:c}=t,u=s.audio,d=e.id===g&&(i!==e.id||t.forwardInfo)&&!u;return{id:n,chatId:e.id,content:s,date:Math.round(Date.now()/1e3),isOutgoing:!d&&"chatTypeChannel"!==e.type,senderId:g,sendingState:"messageSendingStatePending",...r!==g&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:i,fromMessageId:a,senderUserId:r}},groupedId:o,isInAlbum:c}}function T(e,t){return{poll:{id:t.toString(),summary:Object(a.b)(e.summary,["question","answers"]),results:{}}}}function D(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function B(e,t,n){const{channelId:s,replies:a,maxId:o,readMaxId:c,recentRepliers:u}=e;if(s===i.j)return;return{threadId:t,...n!==s?{chatId:Object(r.j)({channelId:s}),originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:o,lastReadInboxMessageId:c,...u&&{recentReplierIds:u.map(r.j)}}}},function(e,t,n){"use strict";(function(e){n.d(t,"m",(function(){return y})),n.d(t,"g",(function(){return b})),n.d(t,"e",(function(){return _})),n.d(t,"v",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"s",(function(){return P})),n.d(t,"q",(function(){return S})),n.d(t,"y",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"c",(function(){return E})),n.d(t,"a",(function(){return R})),n.d(t,"o",(function(){return U})),n.d(t,"p",(function(){return O})),n.d(t,"r",(function(){return T})),n.d(t,"u",(function(){return D})),n.d(t,"t",(function(){return B})),n.d(t,"j",(function(){return x})),n.d(t,"w",(function(){return j})),n.d(t,"n",(function(){return N})),n.d(t,"l",(function(){return V})),n.d(t,"k",(function(){return F})),n.d(t,"i",(function(){return L})),n.d(t,"x",(function(){return q})),n.d(t,"f",(function(){return H})),n.d(t,"h",(function(){return z}));var s=n(0),i=n(11),a=n(4),r=n(1),o=n(9),c=n(13),u=n(2),d=n(5),l=n(3),f=n(34),p=n(16),g=n(33),h=n(7);let m;function y(e){m=e}async function b({chat:e,threadId:t,...n}){const a=t===i.MAIN_THREAD_ID?s.Api.messages.GetHistory:s.Api.messages.GetReplies;let d;try{d=await Object(r.g)(new a({peer:Object(u.i)(e.id,e.accessHash),...t!==i.MAIN_THREAD_ID&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&m({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!d||d instanceof s.Api.messages.MessagesNotModified||!d.messages)return;K(d);const f=d.messages.map(o.b).filter(Boolean),p=d.users.map(c.a).filter(Boolean),g=d.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=f.map(({threadInfo:e})=>e).filter(Boolean);return{messages:f,users:p,chats:g,threadInfos:h}}async function _({chat:e,messageId:t}){const n="channel"===Object(u.s)(e.id),a=await Object(r.g)(n?new s.Api.channels.GetMessages({channel:Object(u.g)(e.id,e.accessHash),id:[new s.Api.InputMessageID({id:t})]}):new s.Api.messages.GetMessages({id:[new s.Api.InputMessageID({id:t})]}));if(!a||a instanceof s.Api.messages.MessagesNotModified)return;const d=a.messages[0];if(!d)return;if(d instanceof s.Api.MessageEmpty)return i.MESSAGE_DELETED;const l=d&&Object(o.b)(d);if(!l)return;d instanceof s.Api.Message&&Object(p.a)(d);return{message:l,users:a.users.map(c.a).filter(Boolean)}}let w=Promise.resolve();function v({chat:e,text:t,entities:n,replyingTo:i,attachment:c,sticker:l,gif:f,poll:p,isSilent:g,scheduledAt:h,groupedId:y,noWebPage:b},_){const v=Object(o.g)(e,t,n,i,c,l,f,p,y,h);m({"@type":v.isScheduled?"newScheduledMessage":"newMessage",id:v.id,chatId:e.id,message:v}),setTimeout(()=>{m({"@type":v.isScheduled?"updateScheduledMessage":"updateMessage",id:v.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})},1e3);const I=Object(u.r)();if(d.a.localMessages[I.toString()]=v,y)return function({chat:e,text:t,entities:n,replyingTo:i,attachment:o,groupedId:c,isSilent:d,scheduledAt:l},f,p,g){let h=-1;A[c]||(A[c]={counter:0,singleMediaByIndex:{}});h=A[c].counter++;const m=w;return w=(async()=>{let y;try{y=await C(p,o,g)}catch(e){return a.g&&console.warn(e),A[c].counter--,void await m}const b=await async function(e,t){const n=await Object(r.g)(new s.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof s.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof s.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaPhoto({id:new s.Api.InputPhoto({id:e,accessHash:t,fileReference:i})})}if(n instanceof s.Api.MessageMediaDocument&&n.document&&n.document instanceof s.Api.Document){const{document:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaDocument({id:new s.Api.InputDocument({id:e,accessHash:t,fileReference:i})})}return}(Object(u.i)(e.id,e.accessHash),y);if(await m,!b)return A[c].counter--,void(a.g&&console.warn("Failed to upload grouped media"));if(A[c].singleMediaByIndex[h]=new s.Api.InputSingleMedia({media:b,randomId:f,message:t||"",entities:n?n.map(u.n):void 0}),Object.keys(A[c].singleMediaByIndex).length{let o;if(c)try{o=await C(v,c,_)}catch(e){return a.g&&console.warn(e),void await P}else l?o=Object(u.h)(l):f?o=Object(u.h)(f):p&&(o=Object(u.j)(p,I));await P;const d=o?s.Api.messages.SendMedia:s.Api.messages.SendMessage;await Object(r.g)(new d({clearDraft:!0,message:t||"",entities:n?n.map(u.n):void 0,peer:Object(u.i)(e.id,e.accessHash),randomId:I,...g&&{silent:g},...h&&{scheduleDate:h},...i&&{replyToMsgId:i},...o&&{media:o},...b&&{noWebpage:b}}),!0)})(),w}const A={};async function I({chat:e,message:t,text:n,entities:i,noWebPage:a}){const o=1e3*t.date>Date.now(),c={content:{...t.content,...n&&{text:{text:n,entities:i}}}};m({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:c}),d.a.localMessages[t.id]={...t,...c};const l=i&&i.map(u.n);await Object(r.g)(new s.Api.messages.EditMessage({message:n||"",entities:l,peer:Object(u.i)(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function P({chat:e,message:t,scheduledAt:n}){await Object(r.g)(new s.Api.messages.EditMessage({peer:Object(u.i)(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function C(t,n,i){const{filename:a,blobUrl:o,mimeType:c,quick:u,voice:d}=n,l=await Object(f.b)(o,a),p=e=>{i.isCanceled?p.isCanceled=!0:i(e,t.id)},h=await Object(r.i)(l,p),m=[new s.Api.DocumentAttributeFilename({fileName:a})];if(u){if(c.startsWith("image/"))return new s.Api.InputMediaUploadedPhoto({file:h});{const{width:e,height:t,duration:n}=u;void 0!==n&&m.push(new s.Api.DocumentAttributeVideo({duration:n,w:e,h:t}))}}if(d){const{duration:t,waveform:n}=d,{data:i}=Object(g.a)(n,63);m.push(new s.Api.DocumentAttributeAudio({voice:!0,duration:t,waveform:e.from(i)}))}return new s.Api.InputMediaUploadedDocument({file:h,mimeType:c,attributes:m})}async function S({chat:e,messageId:t,isUnpin:n,isOneSide:i,isSilent:a}){await Object(r.g)(new s.Api.messages.UpdatePinnedMessage({peer:Object(u.i)(e.id,e.accessHash),id:t,...n&&{unpin:!0},...i&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function M({chat:e}){await Object(r.g)(new s.Api.messages.UnpinAllMessages({peer:Object(u.i)(e.id,e.accessHash)}),!0)}async function k({chat:e,messageIds:t,shouldDeleteForAll:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteMessages({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&m({"@type":"deleteMessages",ids:t,...i&&{chatId:e.id}})}async function E({chat:e,messageIds:t}){await Object(r.g)(new s.Api.messages.DeleteScheduledMessages({peer:Object(u.i)(e.id,e.accessHash),id:t}))&&m({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function R({chat:e,shouldDeleteForAll:t,maxId:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n}):new s.Api.messages.DeleteHistory({peer:Object(u.i)(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&m({"@type":"deleteHistory",chatId:e.id})}async function U({chat:e,threadId:t,maxId:n}){const a="channel"===Object(u.s)(e.id);a&&t===i.MAIN_THREAD_ID?await Object(r.g)(new s.Api.channels.ReadHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n})):a?await Object(r.g)(new s.Api.messages.ReadDiscussion({peer:Object(u.i)(e.id,e.accessHash),msgId:t,readMaxId:n})):await Object(r.g)(new s.Api.messages.ReadHistory({peer:Object(u.i)(e.id,e.accessHash),maxId:n})),t===i.MAIN_THREAD_ID?Object(h.u)(e):T({chat:e,threadId:t})}async function O({chat:e,messageIds:t}){const n="channel"===Object(u.s)(e.id);await Object(r.g)(n?new s.Api.channels.ReadMessageContents({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.ReadMessageContents({id:t})),m({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function T({chat:e,threadId:t}){const[n,i]=await Promise.all([Object(r.g)(new s.Api.messages.GetDiscussionMessage({peer:Object(u.i)(e.id,e.accessHash),msgId:t})),Object(r.g)(new s.Api.messages.GetReplies({peer:Object(u.i)(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=Object(p.c)(n.messages[0]);if(!a)return;m({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:i instanceof s.Api.messages.ChannelMessages?i.count:void 0},firstMessageId:i&&"messages"in i&&i.messages.length?i.messages[0].id:void 0});n.chats.map(e=>Object(l.d)(e)).filter(Boolean).forEach(e=>{m({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})}async function D({chatOrUser:e,type:t,query:n,topMessageId:i,minDate:a,maxDate:d,...l}){let f;switch(t){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"profilePhoto":f=new s.Api.InputMessagesFilterChatPhotos;break;case"text":default:f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:f,q:n||"",topMsgId:i,minDate:a,maxDate:d,...l}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K(p);const g=p.messages.map(o.b).filter(Boolean),h=p.users.map(c.a).filter(Boolean);let m,y=g.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(y=p.count,g.length&&(m=g[g.length-1].id)),{messages:g,users:h,totalCount:y,nextOffsetId:m}}async function B({query:e,offsetRate:t=0,limit:n,type:i="text",minDate:u,maxDate:d}){let f;switch(i){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"text":default:if(!(e||d&&u))return;f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new s.Api.InputPeerEmpty,limit:n,filter:f,folderId:a.a,minDate:u,maxDate:d}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K({chats:p.chats,users:p.users,messages:p.messages});const g=p.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=p.users.map(c.a).filter(Boolean),m=p.messages.map(o.b).filter(Boolean);let y,b=m.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(b=p.count,m.length&&(y=m[m.length-1].id)),{messages:m,users:h,chats:g,totalCount:b,nextRate:"nextRate"in p&&p.nextRate?p.nextRate:y}}async function x({message:e}){const t=await Object(r.g)(new s.Api.messages.GetWebPagePreview({message:e}));return t&&Object(o.n)(t)}async function j({chat:t,messageId:n,options:i}){const{id:a,accessHash:o}=t;await Object(r.g)(new s.Api.messages.SendVote({peer:Object(u.i)(a,o),msgId:n,options:i.map(t=>e.from(t))}),!0)}async function N({chat:t,messageId:n,option:i,offset:a,limit:o,shouldResetVoters:d}){const{id:l,accessHash:f}=t,p=await Object(r.g)(new s.Api.messages.GetPollVotes({peer:Object(u.i)(l,f),id:n,...i&&{option:e.from(i)},...a&&{offset:a},...o&&{limit:o}}));if(!p)return;K({chats:[],users:p.users,messages:[]});const g=p.users.map(c.a).filter(Boolean),h=p.votes.map(e=>({userId:e.userId,date:e.date}));return{count:p.count,votes:h,users:g,nextOffset:p.nextOffset,shouldResetVoters:d}}async function V({fromChat:e,toChat:t,messages:n}){const i=n.map(({id:e})=>e),a=n.map(u.r);n.forEach((e,n)=>{const s=Object(o.f)(t,e);d.a.localMessages[String(a[n])]=s,m({"@type":"newMessage",id:s.id,chatId:t.id,message:s})}),await Object(r.g)(new s.Api.messages.ForwardMessages({fromPeer:Object(u.i)(e.id,e.accessHash),toPeer:Object(u.i)(t.id,t.accessHash),randomId:a,id:i}),!0)}async function F({chat:e,timestamp:t}){const n=await Object(r.g)(new s.Api.messages.GetHistory({peer:Object(u.i)(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof s.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function L({chat:e,hash:t=0}){const{id:n,accessHash:i}=e,a=await Object(r.g)(new s.Api.messages.GetScheduledHistory({peer:Object(u.i)(n,i),hash:t}));if(!a||a instanceof s.Api.messages.MessagesNotModified||!a.messages)return;K(a);const c=a.messages.map(o.b).filter(Boolean);return{messages:c,hash:Object(u.q)(c.map(e=>e.id))}}async function q({chat:e,ids:t}){const{id:n,accessHash:i}=e;await Object(r.g)(new s.Api.messages.SendScheduledMessages({peer:Object(u.i)(n,i),id:t}),!0)}function H({chat:e,message:t}){return Object(r.g)(new s.Api.channels.ExportMessageLink({id:t.id,channel:Object(u.g)(e.id,e.accessHash),...t.isInAlbum&&{grouped:!0},...t.threadInfo&&t.threadInfo.topMessageId!==t.id&&{thread:!0}}))}function K(e){e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),e.messages.forEach(e=>{(e instanceof s.Api.Message&&Object(u.t)(e)||e instanceof s.Api.MessageService&&Object(u.u)(e))&&Object(p.a)(e)})}async function z({chat:e}){const t=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:new s.Api.InputMessagesFilterPinned,q:"",limit:a.t}));if(!t||t instanceof s.Api.messages.MessagesNotModified||!t.messages)return;K(t);return{messages:t.messages.map(o.b).filter(Boolean),users:t.users.map(c.a).filter(Boolean),chats:t.chats.map(e=>Object(l.d)(e)).filter(Boolean)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";var s=n(64);n.o(s,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return s.ApiMediaFormat})),n.o(s,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return s.ApiMessageEntityTypes})),n.o(s,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return s.MAIN_THREAD_ID})),n.o(s,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return s.MESSAGE_DELETED}));var i=n(65);n.o(i,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return i.ApiMediaFormat})),n.o(i,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return i.ApiMessageEntityTypes})),n.o(i,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return i.MAIN_THREAD_ID})),n.o(i,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return i.MESSAGE_DELETED}));var a=n(66);n.d(t,"ApiMessageEntityTypes",(function(){return a.a})),n.d(t,"MAIN_THREAD_ID",(function(){return a.b})),n.d(t,"MESSAGE_DELETED",(function(){return a.c}));var r=n(67);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat}));var o=n(68);n.d(t,"ApiMediaFormat",(function(){return o.a}));n(69),n(70),n(71)},function(e,t,n){"use strict";(function(e){var s=n(73),i=n(74),a=n(75);function r(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(r()=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(s)return F(e).length;t=(""+t).toLowerCase(),s=!0}}function h(e,t,n){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function m(e,t,n){var s=e[t];e[t]=e[n],e[n]=s}function y(e,t,n,s,i){if(0===e.length)return-1;if("string"==typeof n?(s=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,s)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,s,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,s,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,s,i){var a,r=1,o=e.length,c=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;r=2,o/=2,c/=2,n/=2}function u(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(i){var d=-1;for(a=n;ao&&(n=o-c),a=n;a>=0;a--){for(var l=!0,f=0;fi&&(s=i):s=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");s>a/2&&(s=a/2);for(var r=0;r>8,i=n%256,a.push(i),a.push(s);return a}(t,e.length-n),e,n,s)}function C(e,t,n){return 0===t&&n===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,n))}function S(e,t,n){n=Math.min(e.length,n);for(var s=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+l<=n)switch(l){case 1:u<128&&(d=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(d=c);break;case 3:a=e[i+1],r=e[i+2],128==(192&a)&&128==(192&r)&&(c=(15&u)<<12|(63&a)<<6|63&r)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:a=e[i+1],r=e[i+2],o=e[i+3],128==(192&a)&&128==(192&r)&&128==(192&o)&&(c=(15&u)<<18|(63&a)<<12|(63&r)<<6|63&o)>65535&&c<1114112&&(d=c)}null===d?(d=65533,l=1):d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|1023&d),s.push(d),i+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",s=0;for(;s0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,s,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||n>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=n)return 0;if(s>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(i>>>=0)-(s>>>=0),r=(n>>>=0)-(t>>>=0),o=Math.min(a,r),u=this.slice(s,i),d=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var a=!1;;)switch(s){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return v(this,e,t,n);case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(e,t,n){var s="";n=Math.min(e.length,n);for(var i=t;is)&&(n=s);for(var i="",a=t;an)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,s,i,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function T(e,t,n,s){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-n,2);i>>8*(s?i:1-i)}function D(e,t,n,s){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-n,4);i>>8*(s?i:3-i)&255}function B(e,t,n,s,i,a){if(n+s>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function x(e,t,n,s,a){return a||B(e,0,n,4),i.write(e,t,n,s,23,4),n+4}function j(e,t,n,s,a){return a||B(e,0,n,8),i.write(e,t,n,s,52,8),n+8}c.prototype.slice=function(e,t){var n,s=this.length;if((e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(t=void 0===t?s:~~t)<0?(t+=s)<0&&(t=0):t>s&&(t=s),t0&&(i*=256);)s+=this[e+--t]*i;return s},c.prototype.readUInt8=function(e,t){return t||U(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||U(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||U(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=this[e],i=1,a=0;++a=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=t,i=1,a=this[e+--s];s>0&&(i*=256);)a+=this[e+--s]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||U(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||U(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,s){(e=+e,t|=0,n|=0,s)||O(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=0,r=1,o=0;for(this[t]=255&e;++a>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=n-1,r=1,o=0;for(this[t+a]=255&e;--a>=0&&(r*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/r>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,s){if(n||(n=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(a<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(r+1===s){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function L(e){return s.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,s){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(43))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return o}));var s=n(0);function i(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:i}=e;return{...a(e.user),fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,...i&&{botDescription:i.description}}}}function a(e){if(!(e instanceof s.Api.User))return;const{id:t,firstName:n,lastName:i}=e,a=e.photo instanceof s.Api.UserProfilePhoto?String(e.photo.photoId):void 0;return{id:t,isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:r(e),...n&&{firstName:n},...i&&{lastName:i},username:e.username||"",phoneNumber:e.phone||"",status:o(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a}}}function r(e){return e.bot?"userTypeBot":e.deleted?"userTypeDeleted":"userTypeRegular"}function o(e){return!e||e instanceof s.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof s.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof s.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof s.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof s.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}},function(e,t,n){"use strict";function s(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function i(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function a(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a}))},function(e,t,n){(function(e){var s,i=function(e){"use strict";var t=1e7,n=9007199254740992,s=l(n),a="function"==typeof BigInt;function r(e,t,n,s){return void 0===e?r[0]:void 0!==t&&(10!=+t||n)?F(e,t,n,s):z(e)}function o(e,t){this.value=e,this.sign=t,this.isSmall=!1}function c(e){this.value=e,this.sign=e<0,this.isSmall=!0}function u(e){this.value=e}function d(e){return-n0?Math.floor(e):Math.ceil(e)}function m(e,n){var s,i,a=e.length,r=n.length,o=new Array(a),c=0,u=t;for(i=0;i=u?1:0,o[i]=s-c*u;for(;i0&&o.push(c),o}function y(e,t){return e.length>=t.length?m(e,t):m(t,e)}function b(e,n){var s,i,a=e.length,r=new Array(a),o=t;for(i=0;i0;)r[i++]=n%o,n=Math.floor(n/o);return r}function _(e,t){var n,s,i=e.length,a=t.length,r=new Array(i),o=0;for(n=0;n0;)r[i++]=c%o,c=Math.floor(c/o);return r}function I(e,t){for(var n=[];t-- >0;)n.push(0);return n.concat(e)}function P(e,n,s){return new o(e=0;--n)i=(a=1e7*i+e[n])-(s=h(a/t))*t,o[n]=0|s;return[o,0|i]}function M(e,n){var s,i=z(n);if(a)return[new u(e.value/i.value),new u(e.value%i.value)];var d,m=e.value,y=i.value;if(0===y)throw new Error("Cannot divide by zero");if(e.isSmall)return i.isSmall?[new c(h(m/y)),new c(m%y)]:[r[0],e];if(i.isSmall){if(1===y)return[e,r[0]];if(-1==y)return[e.negate(),r[0]];var b=Math.abs(y);if(b=0;i--){for(s=p-1,b[i+l]!==m&&(s=Math.floor((b[i+l]*p+b[i+l-1])/m)),a=0,r=0,c=_.length,o=0;oc&&(i=1e7*(i+1)),n=Math.ceil(i/a);do{if(k(r=A(t,n),d)<=0)break;n--}while(n);u.push(n),d=_(d,r)}return u.reverse(),[f(u),f(d)]}(m,y))[0];var I=e.sign!==i.sign,P=s[1],C=e.sign;return"number"==typeof d?(I&&(d=-d),d=new c(d)):d=new o(d,I),"number"==typeof P?(C&&(P=-P),P=new c(P)):P=new o(P,C),[d,P]}function k(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}function E(e){var t=e.abs();return!t.isUnit()&&(!!(t.equals(2)||t.equals(3)||t.equals(5))||!(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))&&(!!t.lesser(49)||void 0))}function R(e,t){for(var n,s,a,r=e.prev(),o=r,c=0;o.isEven();)o=o.divide(2),c++;e:for(s=0;s=0?s=_(e,t):(s=_(t,e),n=!n),"number"==typeof(s=f(s))?(n&&(s=-s),new c(s)):new o(s,n)}(n,s,this.sign)},o.prototype.minus=o.prototype.subtract,c.prototype.subtract=function(e){var t=z(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var s=t.value;return t.isSmall?new c(n-s):w(s,Math.abs(n),n>=0)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(e){return new u(this.value-z(e).value)},u.prototype.minus=u.prototype.subtract,o.prototype.negate=function(){return new o(this.value,!this.sign)},c.prototype.negate=function(){var e=this.sign,t=new c(-this.value);return t.sign=!e,t},u.prototype.negate=function(){return new u(-this.value)},o.prototype.abs=function(){return new o(this.value,!1)},c.prototype.abs=function(){return new c(Math.abs(this.value))},u.prototype.abs=function(){return new u(this.value>=0?this.value:-this.value)},o.prototype.multiply=function(e){var n,s,i,a=z(e),c=this.value,u=a.value,d=this.sign!==a.sign;if(a.isSmall){if(0===u)return r[0];if(1===u)return this;if(-1===u)return this.negate();if((n=Math.abs(u))0?function e(t,n){var s=Math.max(t.length,n.length);if(s<=30)return v(t,n);s=Math.ceil(s/2);var i=t.slice(s),a=t.slice(0,s),r=n.slice(s),o=n.slice(0,s),c=e(a,o),u=e(i,r),d=e(y(a,i),y(o,r)),l=y(y(c,I(_(_(d,c),u),s)),I(u,2*s));return p(l),l}(c,u):v(c,u),d)},o.prototype.times=o.prototype.multiply,c.prototype._multiplyBySmall=function(e){return d(e.value*this.value)?new c(e.value*this.value):P(Math.abs(e.value),l(Math.abs(this.value)),this.sign!==e.sign)},o.prototype._multiplyBySmall=function(e){return 0===e.value?r[0]:1===e.value?this:-1===e.value?this.negate():P(Math.abs(e.value),this.value,this.sign!==e.sign)},c.prototype.multiply=function(e){return z(e)._multiplyBySmall(this)},c.prototype.times=c.prototype.multiply,u.prototype.multiply=function(e){return new u(this.value*z(e).value)},u.prototype.times=u.prototype.multiply,o.prototype.square=function(){return new o(C(this.value),!1)},c.prototype.square=function(){var e=this.value*this.value;return d(e)?new c(e):new o(C(l(Math.abs(this.value))),!1)},u.prototype.square=function(e){return new u(this.value*this.value)},o.prototype.divmod=function(e){var t=M(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=c.prototype.divmod=o.prototype.divmod,o.prototype.divide=function(e){return M(this,e)[0]},u.prototype.over=u.prototype.divide=function(e){return new u(this.value/z(e).value)},c.prototype.over=c.prototype.divide=o.prototype.over=o.prototype.divide,o.prototype.mod=function(e){return M(this,e)[1]},u.prototype.mod=u.prototype.remainder=function(e){return new u(this.value%z(e).value)},c.prototype.remainder=c.prototype.mod=o.prototype.remainder=o.prototype.mod,o.prototype.pow=function(e){var t,n,s,i=z(e),a=this.value,o=i.value;if(0===o)return r[1];if(0===a)return r[0];if(1===a)return r[1];if(-1===a)return i.isEven()?r[1]:r[-1];if(i.sign)return r[0];if(!i.isSmall)throw new Error("The exponent "+i.toString()+" is too large.");if(this.isSmall&&d(t=Math.pow(a,o)))return new c(h(t));for(n=this,s=r[1];!0&o&&(s=s.times(n),--o),0!==o;)o/=2,n=n.square();return s},c.prototype.pow=o.prototype.pow,u.prototype.pow=function(e){var t=z(e),n=this.value,s=t.value,i=BigInt(0),a=BigInt(1),o=BigInt(2);if(s===i)return r[1];if(n===i)return r[0];if(n===a)return r[1];if(n===BigInt(-1))return t.isEven()?r[1]:r[-1];if(t.isNegative())return new u(i);for(var c=this,d=r[1];(s&a)===a&&(d=d.times(c),--s),s!==i;)s/=o,c=c.square();return d},o.prototype.modPow=function(e,t){if(e=z(e),(t=z(t)).isZero())throw new Error("Cannot take modPow with modulus 0");var n=r[1],s=this.mod(t);for(e.isNegative()&&(e=e.multiply(r[-1]),s=s.modInv(t));e.isPositive();){if(s.isZero())return r[0];e.isOdd()&&(n=n.multiply(s).mod(t)),e=e.divide(2),s=s.square().mod(t)}return n},u.prototype.modPow=c.prototype.modPow=o.prototype.modPow,o.prototype.compareAbs=function(e){var t=z(e),n=this.value,s=t.value;return t.isSmall?1:k(n,s)},c.prototype.compareAbs=function(e){var t=z(e),n=Math.abs(this.value),s=t.value;return t.isSmall?n===(s=Math.abs(s))?0:n>s?1:-1:-1},u.prototype.compareAbs=function(e){var t=this.value,n=z(e).value;return(t=t>=0?t:-t)===(n=n>=0?n:-n)?0:t>n?1:-1},o.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:k(n,s)*(this.sign?-1:1)},o.prototype.compareTo=o.prototype.compare,c.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return t.isSmall?n==s?0:n>s?1:-1:n<0!==t.sign?n<0?-1:1:n<0?1:-1},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,n=z(e).value;return t===n?0:t>n?1:-1},u.prototype.compareTo=u.prototype.compare,o.prototype.equals=function(e){return 0===this.compare(e)},u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals=o.prototype.eq=o.prototype.equals,o.prototype.notEquals=function(e){return 0!==this.compare(e)},u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals=o.prototype.neq=o.prototype.notEquals,o.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater=o.prototype.gt=o.prototype.greater,o.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser=o.prototype.lt=o.prototype.lesser,o.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals=o.prototype.geq=o.prototype.greaterOrEquals,o.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals=o.prototype.leq=o.prototype.lesserOrEquals,o.prototype.isEven=function(){return 0==(1&this.value[0])},c.prototype.isEven=function(){return 0==(1&this.value)},u.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},o.prototype.isOdd=function(){return 1==(1&this.value[0])},c.prototype.isOdd=function(){return 1==(1&this.value)},u.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},o.prototype.isPositive=function(){return!this.sign},c.prototype.isPositive=function(){return this.value>0},u.prototype.isPositive=c.prototype.isPositive,o.prototype.isNegative=function(){return this.sign},c.prototype.isNegative=function(){return this.value<0},u.prototype.isNegative=c.prototype.isNegative,o.prototype.isUnit=function(){return!1},c.prototype.isUnit=function(){return 1===Math.abs(this.value)},u.prototype.isUnit=function(){return this.abs().value===BigInt(1)},o.prototype.isZero=function(){return!1},c.prototype.isZero=function(){return 0===this.value},u.prototype.isZero=function(){return this.value===BigInt(0)},o.prototype.isDivisibleBy=function(e){var t=z(e);return!t.isZero()&&(!!t.isUnit()||(0===t.compareAbs(2)?this.isEven():this.mod(t).isZero()))},u.prototype.isDivisibleBy=c.prototype.isDivisibleBy=o.prototype.isDivisibleBy,o.prototype.isPrime=function(e){var t=E(this);if(void 0!==t)return t;var n=this.abs(),s=n.bitLength();if(s<=64)return R(n,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var a=Math.log(2)*s.toJSNumber(),r=Math.ceil(!0===e?2*Math.pow(a,2):a),o=[],c=0;c-n?new c(e-1):new o(s,!0)},u.prototype.prev=function(){return new u(this.value-BigInt(1))};for(var U=[1];2*U[U.length-1]<=t;)U.push(2*U[U.length-1]);var O=U.length,T=U[O-1];function D(e){return Math.abs(e)<=t}function B(e,t,n){t=z(t);for(var s=e.isNegative(),a=t.isNegative(),r=s?e.not():e,o=a?t.not():t,c=0,u=0,d=null,l=null,f=[];!r.isZero()||!o.isZero();)c=(d=M(r,T))[1].toJSNumber(),s&&(c=T-1-c),u=(l=M(o,T))[1].toJSNumber(),a&&(u=T-1-u),r=d[0],o=l[0],f.push(n(c,u));for(var p=0!==n(s?1:0,a?1:0)?i(-1):i(0),g=f.length-1;g>=0;g-=1)p=p.multiply(T).add(i(f[g]));return p}o.prototype.shiftLeft=function(e){var t=z(e).toJSNumber();if(!D(t))throw new Error(String(t)+" is too large for shifting.");if(t<0)return this.shiftRight(-t);var n=this;if(n.isZero())return n;for(;t>=O;)n=n.multiply(T),t-=O-1;return n.multiply(U[t])},u.prototype.shiftLeft=function(e){return e=z(e),new u(this.value<=O;){if(s.isZero()||s.isNegative()&&s.isUnit())return s;s=(t=M(s,T))[1].isNegative()?t[0].prev():t[0],n-=O-1}return(t=M(s,U[n]))[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=function(e){return e=z(e),new u(this.value>>e.value)},c.prototype.shiftRight=o.prototype.shiftRight,o.prototype.not=function(){return this.negate().prev()},u.prototype.not=c.prototype.not=o.prototype.not,o.prototype.and=function(e){return B(this,e,(function(e,t){return e&t}))},u.prototype.and=c.prototype.and=o.prototype.and,o.prototype.or=function(e){return B(this,e,(function(e,t){return e|t}))},u.prototype.or=c.prototype.or=o.prototype.or,o.prototype.xor=function(e){return B(this,e,(function(e,t){return e^t}))},u.prototype.xor=c.prototype.xor=o.prototype.xor;function x(e){var n=e.value,s="number"==typeof n?n|1<<30:"bigint"==typeof n?n|BigInt(1<<30):n[0]+n[1]*t|1073758208;return s&-s}function j(e,t){return e=z(e),t=z(t),e.greater(t)?e:t}function N(e,t){return e=z(e),t=z(t),e.lesser(t)?e:t}function V(e,t){if(e=z(e).abs(),t=z(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var n,s,i=r[1];e.isEven()&&t.isEven();)n=N(x(e),x(t)),e=e.divide(n),t=t.divide(n),i=i.multiply(n);for(;e.isEven();)e=e.divide(x(e));do{for(;t.isEven();)t=t.divide(x(t));e.greater(t)&&(s=t,t=e,e=s),t=t.subtract(e)}while(!t.isZero());return i.isUnit()?e:e.multiply(i)}o.prototype.bitLength=function(){var e=this;return e.compareTo(i(0))<0&&(e=e.negate().subtract(i(1))),0===e.compareTo(i(0))?i(0):i(function e(t,n){if(n.compareTo(t)<=0){var s=e(t,n.square(n)),a=s.p,r=s.e,o=a.multiply(n);return o.compareTo(t)<=0?{p:o,e:2*r+1}:{p:a,e:2*r}}return{p:i(1),e:0}}(e,i(2)).e).add(i(1))},u.prototype.bitLength=c.prototype.bitLength=o.prototype.bitLength;var F=function(e,t,n,s){n=n||"0123456789abcdefghijklmnopqrstuvwxyz",e=String(e),s||(e=e.toLowerCase(),n=n.toLowerCase());var i,a=e.length,r=Math.abs(t),o={};for(i=0;i=r)){if("1"===d&&1===r)continue;throw new Error(d+" is not a valid digit in base "+t+".")}}t=z(t);var c=[],u="-"===e[0];for(i=u?1:0;i"!==e[i]&&i=0;s--)i=i.add(e[s].times(a)),a=a.times(t);return n?i.negate():i}function q(e,t){if((t=i(t)).isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var n=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return n.unshift([1]),{value:[].concat.apply([],n),isNegative:!1}}var s=!1;if(e.isNegative()&&t.isPositive()&&(s=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:s};for(var a,r=[],o=e;o.isNegative()||o.compareAbs(t)>=0;){a=o.divmod(t),o=a.quotient;var c=a.remainder;c.isNegative()&&(c=t.minus(c).abs(),o=o.next()),r.push(c.toJSNumber())}return r.push(o.toJSNumber()),{value:r.reverse(),isNegative:s}}function H(e,t,n){var s=q(e,t);return(s.isNegative?"-":"")+s.value.map((function(e){return function(e,t){return e<(t=t||"0123456789abcdefghijklmnopqrstuvwxyz").length?t[e]:"<"+e+">"}(e,n)})).join("")}function K(e){if(d(+e)){var t=+e;if(t===h(t))return a?new u(BigInt(t)):new c(t);throw new Error("Invalid integer: "+e)}var n="-"===e[0];n&&(e=e.slice(1));var s=e.split(/e/i);if(s.length>2)throw new Error("Invalid integer: "+s.join("e"));if(2===s.length){var i=s[1];if("+"===i[0]&&(i=i.slice(1)),(i=+i)!==h(i)||!d(i))throw new Error("Invalid integer: "+i+" is not a valid exponent.");var r=s[0],l=r.indexOf(".");if(l>=0&&(i-=r.length-l-1,r=r.slice(0,l)+r.slice(l+1)),i<0)throw new Error("Cannot include negative exponent part for integers");e=r+=new Array(i+1).join("0")}if(!/^([0-9][0-9]*)$/.test(e))throw new Error("Invalid integer: "+e);if(a)return new u(BigInt(n?"-"+e:e));for(var f=[],g=e.length,m=g-7;g>0;)f.push(+e.slice(m,g)),(m-=7)<0&&(m=0),g-=7;return p(f),new o(f,n)}function z(e){return"number"==typeof e?function(e){if(a)return new u(BigInt(e));if(d(e)){if(e!==h(e))throw new Error(e+" is not an integer.");return new c(e)}return K(e.toString())}(e):"string"==typeof e?K(e):"bigint"==typeof e?new u(e):e}o.prototype.toArray=function(e){return q(this,e)},c.prototype.toArray=function(e){return q(this,e)},u.prototype.toArray=function(e){return q(this,e)},o.prototype.toString=function(e,t){if(void 0===e&&(e=10),10!==e)return H(this,e,t);for(var n,s=this.value,i=s.length,a=String(s[--i]);--i>=0;)n=String(s[i]),a+="0000000".slice(n.length)+n;return(this.sign?"-":"")+a},c.prototype.toString=function(e,t){return void 0===e&&(e=10),10!=e?H(this,e,t):String(this.value)},u.prototype.toString=c.prototype.toString,u.prototype.toJSON=o.prototype.toJSON=c.prototype.toJSON=function(){return this.toString()},o.prototype.valueOf=function(){return parseInt(this.toString(),10)},o.prototype.toJSNumber=o.prototype.valueOf,c.prototype.valueOf=function(){return this.value},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=u.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var G=0;G<1e3;G++)r[G]=z(G),G>0&&(r[-G]=z(-G));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=j,r.min=N,r.gcd=V,r.lcm=function(e,t){return e=z(e).abs(),t=z(t).abs(),e.divide(V(e,t)).multiply(t)},r.isInstance=function(e){return e instanceof o||e instanceof c||e instanceof u},r.randBetween=function(e,n,s){e=z(e),n=z(n);var i=s||Math.random,a=N(e,n),o=j(e,n).subtract(a).add(1);if(o.isSmall)return a.add(Math.floor(i()*o));for(var c=q(o,t).value,u=[],d=!0,l=0;l{r.resolve=e,r.reject=t})}function d(e=!1){return o({...y("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise((e,t)=>{r.resolve=e,r.reject=t})}function l(e){return o({...y("authorizationStateWaitPassword"),hint:e}),new Promise(e=>{r.resolve=e})}function f(){return o(y("authorizationStateWaitRegistration")),new Promise(e=>{r.resolve=e})}function p(e){return o({...y("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise((e,t)=>{r.reject=t})}function g(e){let t;if(e instanceof s.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?n+" hours":"an hour")}else t=a[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),o({"@type":"updateAuthorizationError",message:t})}function h(){o(y("authorizationStateReady"))}function m(e){o({"@type":"updateCurrentUser",currentUser:e})}function y(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function b(e){r.resolve&&r.resolve(e)}function _(e){r.resolve&&r.resolve(e)}function w(e){r.resolve&&r.resolve(e)}function v(e){const{firstName:t,lastName:n}=e;r.resolve&&r.resolve([t,n])}function A(){r.reject&&r.reject(new Error("RESTART_AUTH"))}function I(){r.reject&&r.reject(new Error("RESTART_AUTH_WITH_QR"))}},function(e,t,n){"use strict";function s(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function i(e){if(!e)return;const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:i,classType:a,...r}=e;return r}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i}))},function(e,t,n){"use strict";n.d(t,"e",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return f}));var s=n(0),i=n(20),a=n(18);function r(e,t,n){return''.replace("{{path}}",function(e){let t="M";const n=e.length;for(let s=0;s=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[n-128-64]:(n>=128?t+=",":n>=64&&(t+="-"),t+=String(63&n))}return t+="z",t}(e)).replace("{{width}}",String(t)).replace("{{height}}",String(n))}const o={w:100,h:100};function c(e,t){if(!e||!e.length)return;const n=e.find(e=>e instanceof s.Api.PhotoStrippedSize);if(!n)return;const r=e.filter(e=>e instanceof s.Api.PhotoSize),{w:c,h:u}=r&&r.length?r[r.length-1]:o,{bytes:d}=n;return{dataUri:Object(a.a)(t&&"image/jpeg"!==t?d:Object(i.strippedPhotoToJpg)(d),void 0,t),width:c,height:u}}function u(e){const{w:t,h:n,bytes:s}=e;return{dataUri:Object(a.a)(s,void 0,"image/webp"),width:t,height:n}}function d(e,t){const{w:n,h:s}=t;return{dataUri:"data:image/svg+xml;utf8,"+r(e.bytes,n,s),width:n,height:s}}function l(e){const t=e.sizes.filter(e=>e instanceof s.Api.PhotoSize||e instanceof s.Api.PhotoSizeProgressive).map(f);return{id:String(e.id),thumbnail:c(e.sizes),sizes:t}}function f(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}},function(e,t,n){(function(t){const{constructors:s}=n(21),i=t.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),a=t.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error("Invalid message type: "+e.constructor.name)}},getInputPeer:function e(t,n=!0,i=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof s.User){if(t.isSelf&&n)return new s.InputPeerSelf;if(void 0===t.accessHash&&i)throw new Error("User without accessHash or min info cannot be input");return new s.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof s.Chat||t instanceof s.ChatEmpty||t instanceof s.ChatForbidden)return new s.InputPeerChat({chatId:t.id});if(t instanceof s.Channel){if(void 0===t.accessHash&&i)throw new TypeError("Channel without accessHash or min info cannot be input");return new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof s.ChannelForbidden?new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof s.InputUser?new s.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof s.InputChannel?new s.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof s.UserEmpty?new s.InputPeerEmpty:t instanceof s.UserFull?e(t.user):t instanceof s.ChatFull?new s.InputPeerChat({chatId:t.id}):t instanceof s.PeerChat?new s.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof s.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof s.Chat||e instanceof s.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=1572864e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const n=t.from(i);return n[164]=e[1],n[166]=e[2],t.concat([n,e.slice(3),a])},getDC:function(e){switch(e){case 1:return{id:1,ipAddress:"pluto.web.telegram.org",port:443};case 2:return{id:2,ipAddress:"venus.web.telegram.org",port:443};case 3:return{id:3,ipAddress:"aurora.web.telegram.org",port:443};case 4:return{id:4,ipAddress:"vesta.web.telegram.org",port:443};case 5:return{id:5,ipAddress:"flora.web.telegram.org",port:443};default:throw new Error("Cannot find the DC with the ID of "+e)}}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(6),{serializeBytes:i,serializeDate:a}=n(44);e.exports={constructors:s,requests:s,serializeBytes:i,serializeDate:a}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return u}));var s=n(0),i=n(4),a=n(19),r=n(5);function o(e){if(e instanceof s.Api.DocumentEmpty)return;const t=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeSticker);if(!t)return;const n=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeImageSize),r=t.stickerset,o=t.alt,c="application/x-tgsticker"===e.mimeType,u=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoCachedSize),d=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoPathSize),l=u?Object(a.c)(u):d&&n?Object(a.d)(d,n):void 0,{w:f,h:p}=u||n||{};return{id:String(e.id),stickerSetId:r.id?String(r.id):i.s,stickerSetAccessHash:String(r.accessHash),emoji:o,isAnimated:c,width:f,height:p,thumbnail:l}}function c(e){const{archived:t,animated:n,installedDate:s,id:i,accessHash:a,title:r,thumbs:o,count:c,hash:u}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(i),accessHash:String(a),title:r,hasThumbnail:Boolean(o&&o.length),count:c,hash:u}}function u(e){const t=c(e.set),n=e instanceof s.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach(e=>{if(e instanceof s.Api.Document){const n=o(e);n&&(t.covers.push(n),r.a.documents[String(e.id)]=e)}}),t}},function(e,t){class n extends Error{constructor(){super("The read operation was cancelled.")}}class s extends Error{constructor(e,t){super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${e}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${t.length}`),"undefined"!=typeof alert&&alert("Missing MTProto Entity: Please, make sure to add TL definition for ID "+e),this.invalidConstructorId=e,this.remaining=t}}class i extends Error{constructor(e,t){super(`Invalid checksum (${e} when ${t} was expected). This packet should be skipped.`),this.checksum=e,this.validChecksum=t}}class a extends Error{constructor(e){let t;4===e.length?(t=-e.readInt32LE(0),super(`Invalid response buffer (HTTP code ${t})`)):super(`Invalid response buffer (too short ${e})`),this.code=t,this.payload=e}}class r extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=" Caused by "+e.className,super(n),this.message=n,this.code=t}}var c,u,d;d={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).",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).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",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).",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).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",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).",64:"Invalid container."},(u="ErrorMessages")in(c=o)?Object.defineProperty(c,u,{value:d,enumerable:!0,configurable:!0,writable:!0}):c[u]=d,e.exports={ReadCancelledError:n,TypeNotFoundError:s,InvalidChecksumError:i,InvalidBufferError:a,SecurityError:r,CdnFileTamperedError:class extends r{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return u}));var s=n(0),i=n(9),a=n(14);function r(e){if(e instanceof s.Api.WallPaperNoFile)return;const{slug:t}=e,n=Object(i.a)(e.document);return n?{slug:t,document:n}:void 0}function o(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...Object(a.b)(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function c(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}function u(e){let t,n,i,a,r;return e.forEach(e=>{e instanceof s.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof s.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof s.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof s.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof s.Api.PrivacyValueAllowUsers?n=e.users:e instanceof s.Api.PrivacyValueDisallowUsers?a=e.users:e instanceof s.Api.PrivacyValueAllowChatParticipants?i=e.chats.map(e=>-e):e instanceof s.Api.PrivacyValueDisallowChatParticipants&&(r=e.chats.map(e=>-e))}),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:i||[],blockUserIds:a||[],blockChatIds:r||[]}}},function(e,t,n){const{TypeNotFoundError:s}=n(23),{coreObjects:i}=n(54),{tlobjects:a}=n(49),{readBigIntFromBuffer:r}=n(8);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return r(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error("Invalid boolean code "+e.toString("16"))}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=a[e];if(void 0===t){if(2574415285===e)return!0;if(3162085175===e)return!1;if(481674261===e){const e=[],t=this.readInt();for(let n=0;ne instanceof s.Api.User).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}),n.filter(e=>e instanceof s.Api.Chat||e instanceof s.Api.Channel).map(e=>Object(r.d)(e)).forEach(e=>{e&&h({"@type":"updateChat",id:e.id,chat:e})})),e instanceof s.Api.UpdateNewScheduledMessage?h({"@type":y.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):h({"@type":y.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t}),e.message instanceof s.Api.MessageService){const{action:n}=e.message;if(n instanceof s.Api.MessageActionChatEditTitle)h({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof s.Api.MessageActionChatEditPhoto){const i=Object(c.c)(n.photo),a=Object(r.e)(i),o=Math.abs(Object(f.c)(e.message));u.a.chats[o]&&(u.a.chats[o].photo=i),Object(f.b)(n.photo),a&&h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof s.Api.Photo&&{newProfilePhoto:Object(g.a)(n.photo)}})}else if(n instanceof s.Api.MessageActionChatDeletePhoto){const n=Math.abs(Object(f.c)(e.message));u.a.chats[n]&&(u.a.chats[n].photo=new s.Api.ChatPhotoEmpty),h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof s.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&e.id===n.userId)&&h({"@type":"updateChatLeave",id:t.chatId}):n instanceof s.Api.MessageActionChatAddUser&&e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&n.users.includes(e.id))&&h({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof s.Api.UpdateEditMessage||e instanceof s.Api.UpdateEditChannelMessage){if(e.message instanceof s.Api.MessageEmpty)return void(l.g&&console.error("Unexpected update:",e.className,e));e.message instanceof s.Api.Message&&Object(c.t)(e.message)&&Object(f.a)(e.message);const t=Object(a.b)(e.message);h({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof s.Api.UpdateDeleteMessages)h({"@type":"deleteMessages",ids:e.messages});else if(e instanceof s.Api.UpdateDeleteScheduledMessages)h({"@type":"deleteScheduledMessages",ids:e.messages,chatId:Object(r.i)(e.peer)});else if(e instanceof s.Api.UpdateDeleteChannelMessages){const t=Object(r.j)({channelId:e.channelId}),n=e.messages,i=n.filter(e=>u.a.messages[`${t}-${e}`]),a=n.filter(e=>!u.a.messages[`${t}-${e}`]),o=n.map(e=>{const n=u.a.messages[`${t}-${e}`];return n&&n instanceof s.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0}).filter(Boolean);i.length&&h({"@type":"deleteMessages",ids:i,chatId:t}),o.length&&h({"@type":"deleteProfilePhotos",ids:o,chatId:t}),a.length&&setTimeout(()=>{h({"@type":"deleteMessages",ids:a,chatId:t})},1e3)}else if((t instanceof s.Api.messages.SendMessage||t instanceof s.Api.messages.SendMedia||t instanceof s.Api.messages.SendMultiMedia||t instanceof s.Api.messages.ForwardMessages)&&(e instanceof s.Api.UpdateMessageID||e instanceof s.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const i=n&&u.a.localMessages[n.toString()];if(!i)throw new Error("Local message not found");let r;if(e instanceof s.Api.UpdateShortSentMessage){i.content.text&&e.entities&&(r={text:Object(a.j)(i.content.text.text,e.entities)}),e.media&&(r={...r,...Object(a.i)(e.media)});const t=Object(c.m)(e.id,i.chatId,e);Object(c.t)(t)&&Object(f.a)(t)}y.add(e.id);const o="date"in e&&1e3*e.dateString.fromCharCode(...e))});else if(e instanceof s.Api.UpdateChannelMessageViews)h({"@type":"updateMessage",chatId:Object(r.j)({channelId:e.channelId}),id:e.id,message:{views:e.views}});else if(e instanceof s.Api.UpdateReadHistoryInbox)h({"@type":"updateChatInbox",id:Object(r.j)(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadHistoryOutbox)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateReadChannelInbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadChannelOutbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateDialogPinned&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChatPinned",id:Object(r.j)(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof s.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter(e=>e instanceof s.Api.DialogPeer).map(e=>Object(r.j)(e.peer)):[];h({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof s.Api.UpdateFolderPeers)e.folderPeers.forEach(e=>{const{folderId:t,peer:n}=e;h({"@type":"updateChatListType",id:Object(r.j)(n),folderId:t})});else if(e instanceof s.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Object(r.a)(n):void 0;h({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof s.Api.UpdateDialogFilterOrder)h({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof s.Api.UpdateChatParticipants){const t=Object(r.g)(e.participants);h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.participants.chatId}),replacedMembers:t})}else if(e instanceof s.Api.UpdateChatParticipantAdd){const t=Object(r.f)(Object(i.b)(e,["userId","inviterId","date"]));h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),addedMember:t})}else if(e instanceof s.Api.UpdateChatParticipantDelete){const{userId:t}=e;h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),deletedMemberId:t})}else if(e instanceof s.Api.UpdatePinnedMessages||e instanceof s.Api.UpdatePinnedChannelMessages){const t=e instanceof s.Api.UpdatePinnedMessages?e.peer:{channelId:e.channelId},n=Object(r.j)(t);h({"@type":"updatePinnedIds",chatId:n,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof s.Api.UpdateNotifySettings&&e.peer instanceof s.Api.NotifyPeer){const{silent:t,muteUntil:n,showPreviews:s,sound:i}=e.notifySettings,a=t||"number"==typeof n&&Date.now()<1e3*n;h({"@type":"updateNotifyExceptions",id:Object(r.j)(e.peer.peer),isMuted:a,...""===i&&{isSilent:!0},...void 0!==s&&{shouldShowPreviews:Boolean(s)}})}else if(e instanceof s.Api.UpdateUserTyping||e instanceof s.Api.UpdateChatUserTyping){const t=e instanceof s.Api.UpdateUserTyping?e.userId:Object(r.j)({chatId:e.chatId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannelUserTyping){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find(e=>e instanceof s.Api.Channel||e instanceof s.Api.ChannelForbidden);if(n instanceof s.Api.Channel){const t=Object(r.d)(n);t&&(h({"@type":"updateChat",id:t.id,chat:t}),h({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:Object(r.j)({channelId:e.channelId})}))}else if(n instanceof s.Api.ChannelForbidden){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),h({"@type":"updateChatLeave",id:t})}else 0===t.length&&h({"@type":"resetMessages",id:Object(r.j)({chatId:e.channelId})})}else if(e instanceof s.Api.UpdateDialogUnreadMark&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChat",id:Object(r.j)(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof s.Api.UpdateChatDefaultBannedRights)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{defaultBannedRights:Object(d.b)(e.defaultBannedRights)}});else if(e instanceof s.Api.UpdateUserStatus){const{userId:t,status:n}=e;h({"@type":"updateUserStatus",userId:t,status:Object(o.c)(n)})}else if(e instanceof s.Api.UpdateUserName){const t=u.a.users[e.userId],n=t&&t.mutualContact&&!t.self?Object(i.b)(e,["username"]):Object(i.b)(e,["firstName","lastName","username"]);h({"@type":"updateUser",id:e.userId,user:n})}else if(e instanceof s.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=Object(r.e)(n);u.a.users[t]&&(u.a.users[t].photo=n),h({"@type":"updateUser",id:t,user:{avatarHash:s}})}else if(e instanceof s.Api.UpdateUserPhone){const{userId:t,phone:n}=e;h({"@type":"updateUser",id:t,user:{phoneNumber:n}})}else if(e instanceof s.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;t&&t.length&&(t.filter(e=>e instanceof s.Api.User&&!e.contact).forEach(e=>{h({"@type":"deleteUser",id:e.id})}),t.filter(e=>e instanceof s.Api.User&&e.contact).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}))}else if(e instanceof s.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:i}}=e,a="NotifyUsers"===i?"contact":"NotifyChats"===i?"group":"NotifyBroadcasts"===i?"broadcast":void 0;if(!a)return;h({"@type":"updateNotifySettings",peerType:a,isSilent:Boolean(n||"number"==typeof s&&Date.now()<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof s.Api.UpdatePeerBlocked)h({"@type":"updatePeerBlocked",id:Object(r.j)(e.peerId),isBlocked:e.blocked});else if(e instanceof s.Api.UpdatePrivacy){const t=Object(p.c)(e.key);t&&h({"@type":"updatePrivacy",key:t,rules:Object(p.d)(e.rules)})}else if(e instanceof s.Api.UpdateContactsReset)h({"@type":"updateResetContactList"});else if(e instanceof s.Api.UpdateFavedStickers)h({"@type":"updateFavoriteStickers"});else if(l.g){const t="object"==typeof e&&"className"in e?e.className:e;console.warn("[GramJs/updater] Unexpected update:",t)}}},function(e,t,n){const s=n(48);e.exports=class extends s{constructor(){super(),this._serverAddress=void 0,this._dcId=0,this._port=void 0,this._takeoutId=void 0,this._entities=new Set,this._updateStates={}}get dcId(){return this._dcId}get serverAddress(){return this._serverAddress}get port(){return this._port}get authKey(){return this._authKey}set authKey(e){this._authKey=e}setDC(e,t,n){this._dcId=0|e,this._serverAddress=t,this._port=n}}},function(e,t,n){(function(t){const{sha1:s,toSignedLittleBuffer:i,readBufferFromBigInt:a,readBigIntFromBuffer:r}=n(8),o=n(25),{sleep:c}=n(8);class u{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new o(t);this.auxHash=n.readLong(!1),n.read(4),this.keyId=n.readLong(!1)}async setKey(e){if(!e)return this._key=void 0,this.auxHash=void 0,this.keyId=void 0,void(this._hash=void 0);if(e instanceof u)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await s(this._key);const t=new o(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await c(20)}getKey(){return this._key}async calcNewNonceHash(e,n){e=i(e,32);const o=t.alloc(1);o.writeUInt8(n,0);const c=t.concat([e,t.concat([o,a(this.auxHash,8,!0)])]),u=(await s(c)).slice(4,20);return r(u,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=u}).call(this,n(12).Buffer)},function(e,t,n){const{RPCError:s}=n(36),{rpcErrorRe:i}=n(47);const a=n(23),r=n(36),o=n(47);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of i){const i=e.errorMessage.match(n);if(i){return new s({request:t,capture:2===i.length?parseInt(i[1],10):void 0})}}return new s(e.errorMessage,t)},...a,...r,...o}},function(e,t,n){"use strict";function s(e,t,n=!0){let s,i,a;return(...r)=>{i=!0,a=r,s||(n&&(i=!1,e(...a)),s=self.setInterval(()=>{if(!i)return self.clearInterval(s),void(s=void 0);i=!1,e(...a)},t))}}function i(e){return a(r,e)}function a(e,t){let n,s=!1;return(...i)=>{n=i,s||(s=!0,e(()=>{s=!1,t(...n)}))}}function r(e){Promise.resolve().then(e)}n.d(t,"b",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const o=e=>new Promise(t=>{setTimeout(()=>t(),e)})},function(e,t,n){(function(t){const s=n(15),{constructors:i}=n(21),{readBigIntFromBuffer:a,readBufferFromBigInt:r,sha256:o,bigIntMod:c,modExp:u,generateRandomBytes:d}=n(8),l=n(35);function f(e,n){if(!t.from([199,28,174,185,198,177,201,4,142,108,82,47,112,241,63,115,152,13,64,35,142,62,33,193,73,52,208,55,86,61,147,15,72,25,138,10,167,193,64,88,34,148,147,210,37,48,244,219,250,51,111,110,10,201,37,19,149,67,174,212,76,206,124,55,32,253,81,246,148,88,112,90,198,140,212,254,107,107,19,171,220,151,70,81,41,105,50,132,84,241,143,175,140,89,95,100,36,119,254,150,187,42,148,29,91,205,29,74,200,204,73,136,7,8,250,155,55,142,60,79,58,144,96,190,230,124,249,164,164,166,149,129,16,81,144,126,22,39,83,181,107,15,107,65,13,186,116,216,168,75,42,20,179,20,78,14,241,40,71,84,253,23,237,149,13,89,101,180,185,221,70,88,45,177,23,141,22,156,107,196,101,176,214,255,156,163,146,143,239,91,154,228,228,24,252,21,232,62,190,160,248,127,169,255,94,237,112,5,13,237,40,73,244,123,249,89,217,86,133,12,233,41,133,31,13,129,21,246,53,177,5,238,46,78,21,208,75,36,84,191,111,79,173,240,52,177,4,3,17,156,216,227,185,47,204,91]).equals(e)||![3,4,5,7].includes(n))throw new Error("Changing passwords unsupported")}function p(e){return t.concat([t.alloc(256-e.length),e])}function g(e){return r(e,256,!1)}function h(e,t){const n=t.subtract(e);return!(n.lesser(s(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function m(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=d(256),n=a(e,!1),i=u(s(_),n,b);if(h(i,b)){const e=g(i),r=a(await o(t.concat([e,P])),!1);if(r.greater(s(0)))return[n,e,r]}}})(),U=c(w.subtract(M),b);if(!h(U,b))throw new Error("bad gB");const O=R.multiply(v),T=k.add(O),D=u(U,T,b),[B,x,j,N,V]=await Promise.all([o(g(D)),o(A),o(I),o(r.salt1),o(r.salt2)]),F=await o(t.concat([m(x,j),N,V,E,P,B]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:t.from(E),M1:F})},computeDigest:async function(e,t){try{f(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return g(u(s(e.g),a(await y(e,t),!1),a(e.p,!1)))}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{inflate:i}=n(41),{serializeBytes:a}=n(21);class r{constructor(e){this.data=e,this.CONSTRUCTOR_ID=812830625,this.classType="constructor"}static async gzipIfSmaller(e,t){if(e&&t.length>512){const e=await new r(t).toBytes();if(e.length{const s=new FileReader;s.onload=e=>{const{result:s}=e.target||{};"string"==typeof s&&t(s),n(new Error("Failed to read blob"))},s.onerror=n,s.readAsDataURL(e)})}async function a(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}},function(e,t,n){(function(t){const s=n(45).default,{i2ab:i,ab2i:a}=n(77),{getWords:r}=n(78);class o{constructor(e){this.setBytes(e)}setBytes(e){e=t.from(e),this._counter=e}increment(){for(let e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}}}class c{constructor(e,t){t instanceof o||(t=new o(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new s(r(e))}update(e){return this.encrypt(e)}encrypt(e){const n=t.from(e);for(let e=0;e{s[e]&&r[e]&&(this._authKeys[e]=new i(t.from(s[e].data),t.from(r[e].data)))})}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey="GramJs-session-"+Date.now()),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(n=>{const s=this._authKeys[n];t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash}),t}async _loadFromSessionString(){const[,e,n]=this._sessionString.split(":"),s=Number(e),{ipAddress:r,port:o}=a.getDC(s);this.setDC(s,r,o);const c=new i;await c.setKey(t.from(n,"hex"),!0),this.setAuthKey(c,s)}async _updateStorage(){if(this._storageKey)try{await this._saveToCache(JSON.stringify(this.getSessionData()))}catch(e){console.warn("Failed to update session in storage"),console.warn(e)}}async delete(){try{return await this._delete()}catch(e){console.warn("Failed to delete session from storage"),console.warn(e)}}_delete(){throw new Error("Not Implemented")}_fetchFromCache(){throw new Error("Not Implemented")}_saveToCache(e){throw new Error("Not Implemented")}}}).call(this,n(12).Buffer)},function(e,t,n){e.exports=function e(t,n,s){function i(r,o){if(!n[r]){if(!t[r]){if(a)return a(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[r]={exports:{}};t[r][0].call(u.exports,(function(e){return i(t[r][1][e]||e)}),u,u.exports,e,t,n,s)}return n[r].exports}for(var a=!1,r=0;r=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&a||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r>>6,t[r++]=128|63&n):n<65536?(t[r++]=224|n>>>12,t[r++]=128|n>>>6&63,t[r++]=128|63&n):(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63,t[r++]=128|n>>>6&63,t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n4)u[s++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?u[s++]=65533:i<65536?u[s++]=i:(i-=65536,u[s++]=55296|i>>10&1023,u[s++]=56320|1023&i)}return c(u,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,s){for(var i=65535&e|0,a=e>>>16&65535|0,r=0;0!==n;){n-=r=n>2e3?2e3:n;do{a=a+(i=i+t[s++]|0)|0}while(--r);i%=65521,a%=65521}return i|a<<16|0}},{}],4:[function(e,t,n){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){"use strict";var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=s,r=i+n;e^=-1;for(var o=i;o>>8^a[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,n){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){"use strict";t.exports=function(e,t){var n,s,i,a,r,o,c,u,d,l,f,p,g,h,m,y,b,_,w,v,A,I,P,C,S;n=e.state,s=e.next_in,C=e.input,i=s+(e.avail_in-5),a=e.next_out,S=e.output,r=a-(t-e.avail_out),o=a+(e.avail_out-257),c=n.dmax,u=n.wsize,d=n.whave,l=n.wnext,f=n.window,p=n.hold,g=n.bits,h=n.lencode,m=n.distcode,y=(1<>>=w=_>>>24,g-=w,0==(w=_>>>16&255))S[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=h[(65535&_)+(p&(1<>>=w,g-=w),g<15&&(p+=C[s++]<>>=w=_>>>24,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<c){e.msg="invalid distance too far back",n.mode=30;break e}if(p>>>=w,g-=w,A>(w=a-r)){if((w=A-w)>d&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(I=0,P=f,0===l){if(I+=u-w,w2;)S[a++]=P[I++],S[a++]=P[I++],S[a++]=P[I++],v-=3;v&&(S[a++]=P[I++],v>1&&(S[a++]=P[I++]))}else{I=a-A;do{S[a++]=S[I++],S[a++]=S[I++],S[a++]=S[I++],v-=3}while(v>2);v&&(S[a++]=S[I++],v>1&&(S[a++]=S[I++]))}break}}break}}while(s>3,p&=(1<<(g-=v<<3))-1,e.next_in=s,e.next_out=a,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(852),t.distcode=t.distdyn=new s.Buf32(592),t.sane=1,t.back=-1,0):-2}function l(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,d(e)):-2}function f(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?-2:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,l(e))):-2}function p(e,t){var n,s;return e?(s=new u,e.state=s,s.window=null,0!==(n=f(e,t))&&(e.state=null),n):-2}var g,h,m=!0;function y(e){if(m){var t;for(g=new s.Buf32(512),h=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(1,e.lens,0,288,g,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(2,e.lens,0,32,h,0,e.work,{bits:5}),m=!1}e.lencode=g,e.lenbits=9,e.distcode=h,e.distbits=5}function b(e,t,n,i){var a,r=e.state;return null===r.window&&(r.wsize=1<=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):((a=r.wsize-r.wnext)>i&&(a=i),s.arraySet(r.window,t,n-i,a,r.wnext),(i-=a)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,n.check=a(n.check,B,2,0),h=0,m=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&h)){e.msg="unknown compression method",n.mode=30;break}if(m-=4,R=8+(15&(h>>>=4)),0===n.wbits)n.wbits=R;else if(R>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=3;case 3:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>8&255,B[2]=h>>>16&255,B[3]=h>>>24&255,n.check=a(n.check,B,4,0)),h=0,m=0,n.mode=4;case 4:for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>8),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=5;case 5:if(1024&n.flags){for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((v=n.length)>p&&(v=p),v&&(n.head&&(R=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,u,l,v,R)),512&n.flags&&(n.check=a(n.check,u,v,l)),p-=v,l+=v,n.length-=v),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===p)break e;v=0;do{R=u[l+v++],n.head&&R&&n.length<65536&&(n.head.name+=String.fromCharCode(R))}while(R&&v>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>=7&m,m-=7&m,n.mode=27;break}for(;m<3;){if(0===p)break e;p--,h+=u[l++]<>>=1)){case 0:n.mode=14;break;case 1:if(y(n),n.mode=20,6===t){h>>>=2,m-=2;break e}break;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}h>>>=2,m-=2;break;case 14:for(h>>>=7&m,m-=7&m;m<32;){if(0===p)break e;p--,h+=u[l++]<>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&h,h=0,m=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(v=n.length){if(v>p&&(v=p),v>g&&(v=g),0===v)break e;s.arraySet(d,u,l,v,f),p-=v,l+=v,g-=v,f+=v,n.length-=v;break}n.mode=12;break;case 17:for(;m<14;){if(0===p)break e;p--,h+=u[l++]<>>=5,m-=5,n.ndist=1+(31&h),h>>>=5,m-=5,n.ncode=4+(15&h),h>>>=4,m-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,m-=3}for(;n.have<19;)n.lens[x[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,O={bits:n.lenbits},U=o(0,n.lens,0,19,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=P,m-=P,n.lens[n.have++]=S;else{if(16===S){for(T=P+2;m>>=P,m-=P,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}R=n.lens[n.have-1],v=3+(3&h),h>>>=2,m-=2}else if(17===S){for(T=P+3;m>>=P)),h>>>=3,m-=3}else{for(T=P+7;m>>=P)),h>>>=7,m-=7}if(n.have+v>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;v--;)n.lens[n.have++]=R}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,O={bits:n.lenbits},U=o(1,n.lens,0,n.nlen,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,O={bits:n.distbits},U=o(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,O),n.distbits=O.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(p>=6&&g>=258){e.next_out=f,e.avail_out=g,e.next_in=l,e.avail_in=p,n.hold=h,n.bits=m,r(e,w),f=e.next_out,d=e.output,g=e.avail_out,l=e.next_in,u=e.input,p=e.avail_in,h=n.hold,m=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;C=(D=n.lencode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,n.length=S,0===C){n.mode=26;break}if(32&C){n.back=-1,n.mode=12;break}if(64&C){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&C,n.mode=22;case 22:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;C=(D=n.distcode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,64&C){e.msg="invalid distance code",n.mode=30;break}n.offset=S,n.extra=15&C,n.mode=24;case 24:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===g)break e;if(v=w-g,n.offset>v){if((v=n.offset-v)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}v>n.wnext?(v-=n.wnext,A=n.wsize-v):A=n.wnext-v,v>n.length&&(v=n.length),I=n.window}else I=d,A=f-n.offset,v=n.length;v>g&&(v=g),g-=v,n.length-=v;do{d[f++]=I[A++]}while(--v);0===n.length&&(n.mode=21);break;case 26:if(0===g)break e;d[f++]=n.length,g--,n.mode=21;break;case 27:if(n.wrap){for(;m<32;){if(0===p)break e;p--,h|=u[l++]<=1&&0===B[S];S--);if(M>S&&(M=S),0===S)return u[d++]=20971520,u[d++]=20971520,f.bits=1,0;for(C=1;C0&&(0===e||1!==S))return-1;for(x[1]=0,I=1;I<15;I++)x[I+1]=x[I]+B[I];for(P=0;P852||2===e&&U>592)return 1;for(;;){_=I-E,l[P]b?(w=j[N+l[P]],v=T[D+l[P]]):(w=96,v=0),p=1<>E)+(g-=p)]=_<<24|w<<16|v|0}while(0!==g);for(p=1<>=1;if(0!==p?(O&=p-1,O+=p):O=0,P++,0==--B[I]){if(I===S)break;I=t[n+l[P]]}if(I>M&&(O&m)!==h){for(0===E&&(E=M),y+=C,R=1<<(k=I-E);k+E852||2===e&&U>592)return 1;u[h=O&m]=M<<24|k<<16|y-d|0}}return 0!==O&&(u[y+O]=I-E<<24|64<<16|0),f.bits=M,0}},{"../utils/common":1}],10:[function(e,t,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){"use strict";var s=e("./zlib/inflate"),i=e("./utils/common"),a=e("./utils/strings"),r=e("./zlib/constants"),o=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),d=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(o[n]);if(this.header=new u,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=a.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(o[n])}function f(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}l.prototype.push=function(e,t){var n,o,c,u,l,f=this.strm,p=this.options.chunkSize,g=this.options.dictionary,h=!1;if(this.ended)return!1;o=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?f.input=a.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?f.input=new Uint8Array(e):f.input=e,f.next_in=0,f.avail_in=f.input.length;do{if(0===f.avail_out&&(f.output=new i.Buf8(p),f.next_out=0,f.avail_out=p),(n=s.inflate(f,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===h&&(n=r.Z_OK,h=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),this.ended=!0,!1;f.next_out&&(0!==f.avail_out&&n!==r.Z_STREAM_END&&(0!==f.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=a.utf8border(f.output,f.next_out),u=f.next_out-c,l=a.buf2string(f.output,c),f.next_out=u,f.avail_out=p-u,u&&i.arraySet(f.output,f.output,c,u,0),this.onData(l)):this.onData(i.shrinkBuf(f.output,f.next_out)))),0===f.avail_in&&0===f.avail_out&&(h=!0)}while((f.avail_in>0||0===f.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),f.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=l,n.inflate=f,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},n.ungzip=f},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")},function(e,t,n){const s=n(46),i=n(58),a=n(25),r=n(60),o=n(57),c=n(61);e.exports={BinaryWriter:i,BinaryReader:a,MessagePacker:o,AsyncQueue:c,Logger:s,PromisedWebSockets:r}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){(function(t){const n=e=>e.replace(/(?:^|_)([a-z])/g,(e,t)=>t.toUpperCase()).replace(/_/g,""),s=e=>e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_","")),i=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),a=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let r;function o(e){r||(r=function(){let e;const t=[];for(let n=0;n<256;n++){e=n;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0}const c=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),c(e,t,n)),n},u=(e,i)=>{const a=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!a)throw new Error("Cannot parse TLObject "+e);const r=c(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),u={name:a[1],constructorId:parseInt(a[2],16),argsConfig:{},subclassOfId:o(a[3]),result:a[3],isFunction:i,namespace:void 0};if(!u.constructorId){const e="";let n;n=Object.values(u.argsConfig).length?" "+Object.keys(u.argsConfig).map(e=>e.toString()).join(" "):"";const s=`${u.name}${e}${n} = ${u.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===u.name&&u.name,u.constructorId=o(t.from(s,"utf8"))}for(const[e,t,n]of r)void 0===e&&(u.argsConfig[s(t)]=d(t,n));return u.name.includes(".")&&([u.namespace,u.name]=u.name.split(/\.(.+)/)),u.name=n(u.name),u};function d(e,t){e="self"===e?"is_self":e;const n={isVector:!1,isFlag:!1,skipConstructorId:!1,flagIndex:-1,flagIndicator:!0,type:void 0,useVectorId:void 0};if("#"!==t){n.flagIndicator=!1,n.type=t.replace(/^!+/,"");const e=n.type.match(/flags.(\d+)\?([\w<>.]+)/);e&&(n.isFlag=!0,n.flagIndex=Number(e[1]),[,,n.type]=e);const s=n.type.match(/[Vv]ector<([\w\d.]+)>/);s&&(n.isVector=!0,n.useVectorId="V"===n.type.charAt(0),[,n.type]=s),/^[a-z]$/.test(n.type.split(".").pop().charAt(0))&&(n.skipConstructorId=!0)}return n}e.exports={findAll:c,parseTl:function*(e,t,n=[],s=i){(n||[]).reduce((e,t)=>({...e,[t.name]:t}),{});const r=[],o={},c={},d=e;let l=!1;for(let e of d.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;l="functions"===e}else try{const t=u(e,l);if(s.has(t.constructorId))continue;r.push(t),t.isFunction||(c[t.result]||(c[t.result]=[]),o[t.name]=t,c[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of r)if(a.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of r)yield e},buildArgConfig:d,fromLine:u,CORE_TYPES:i,serializeDate:function(e){if(!e)return t.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const n=t.alloc(4);return n.writeInt32LE(e,0),n}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof t)){if("string"!=typeof e)throw Error("Bytes or str expected, not "+e.constructor.name);e=t.from(e)}const n=[];let s;return e.length<254?(s=(e.length+1)%4,0!==s&&(s=4-s),n.push(t.from([e.length])),n.push(e)):(s=e.length%4,0!==s&&(s=4-s),n.push(t.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),n.push(e)),n.push(t.alloc(s).fill(0)),t.concat(n)},snakeToCamelCase:n,variableSnakeToCamelCase:s}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"CTR",(function(){return y})),n.d(t,"IGE",(function(){return m}));var s=new Uint8Array(256),i=new Uint8Array(256),a=new Uint32Array(256),r=new Uint32Array(256),o=new Uint32Array(256),c=new Uint32Array(256),u=new Uint32Array(256),d=new Uint32Array(256),l=new Uint32Array(256),f=new Uint32Array(256);function p(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(var t=e.length%4;t<=4;t++)e+="\0x00";var n=new Uint32Array(e.length/4);for(t=0;t>7),m[h[_]^_]=_;for(;!s[y];y^=e||1)n=(n=b^b<<1^b<<2^b<<3^b<<4)>>8^255&n^99,s[y]=n,i[n]=y,g=16843009*h[t=h[e=h[y]]]^65537*t^257*e^16843008*y,p=257*h[n]^16843008*n,a[y]=p=p<<24^p>>>8,r[y]=p=p<<24^p>>>8,o[y]=p=p<<24^p>>>8,c[y]=p=p<<24^p>>>8,u[n]=g=g<<24^g>>>8,d[n]=g=g<<24^g>>>8,l[n]=g=g<<24^g>>>8,f[n]=g=g<<24^g>>>8,b=m[b]||1}();var h=function(){function e(e){var t=p(e);if(4!==t.length&&6!==t.length&&8!==t.length)throw new Error("Invalid key size");this.encKey=new Uint32Array(4*t.length+28),this.decKey=new Uint32Array(4*t.length+28),this.encKey.set(t);for(var n,i=1,a=t.length;a<4*t.length+28;a++)n=this.encKey[a-1],(a%t.length==0||8===t.length&&a%t.length==4)&&(n=s[n>>>24]<<24^s[n>>16&255]<<16^s[n>>8&255]<<8^s[255&n],a%t.length==0&&(n=n<<8^n>>>24^i<<24,i=i<<1^283*(i>>7))),this.encKey[a]=this.encKey[a-t.length]^n;for(var r=0;a;r++,a--)n=this.encKey[3&r?a:a-4],this.decKey[r]=a<=4||r<4?n:u[s[n>>>24]]^d[s[n>>16&255]]^l[s[n>>8&255]]^f[s[255&n]]}return e.prototype.encrypt=function(e){for(var t,n,i,u=p(e),d=new Uint32Array(4),l=u[0]^this.encKey[0],f=u[1]^this.encKey[1],g=u[2]^this.encKey[2],h=u[3]^this.encKey[3],m=this.encKey.length/4-2,y=4,b=0;b>>24]^r[f>>16&255]^o[g>>8&255]^c[255&h]^this.encKey[y],n=a[f>>>24]^r[g>>16&255]^o[h>>8&255]^c[255&l]^this.encKey[y+1],i=a[g>>>24]^r[h>>16&255]^o[l>>8&255]^c[255&f]^this.encKey[y+2],h=a[h>>>24]^r[l>>16&255]^o[f>>8&255]^c[255&g]^this.encKey[y+3],l=t,f=n,g=i,y+=4;for(b=0;b<4;b++)d[b]=s[l>>>24]<<24^s[f>>16&255]<<16^s[g>>8&255]<<8^s[255&h]^this.encKey[y++],t=l,l=f,f=g,g=h,h=t;return d},e.prototype.decrypt=function(e){for(var t,n,s,a=p(e),r=new Uint32Array(4),o=a[0]^this.decKey[0],c=a[3]^this.decKey[1],g=a[2]^this.decKey[2],h=a[1]^this.decKey[3],m=this.decKey.length/4-2,y=4,b=0;b>>24]^d[c>>16&255]^l[g>>8&255]^f[255&h]^this.decKey[y],n=u[c>>>24]^d[g>>16&255]^l[h>>8&255]^f[255&o]^this.decKey[y+1],s=u[g>>>24]^d[h>>16&255]^l[o>>8&255]^f[255&c]^this.decKey[y+2],h=u[h>>>24]^d[o>>16&255]^l[c>>8&255]^f[255&g]^this.decKey[y+3],o=t,c=n,g=s,y+=4;for(b=0;b<4;b++)r[3&-b]=i[o>>>24]<<24^i[c>>16&255]<<16^i[g>>8&255]<<8^i[255&h]^this.decKey[y++],t=o,o=c,c=g,g=h,h=t;return r},e}(),m=function(){function e(e,t,n){void 0===n&&(n=16),this.key=p(e),this.iv=p(t),this.cipher=new h(e),this.blockSize=n/4}return e.prototype.encrypt=function(e,t){for(var n=p(e),s=t||new Uint32Array(n.length),i=this.iv.subarray(this.blockSize,this.iv.length),a=this.iv.subarray(0,this.blockSize),r=new Uint32Array(this.blockSize),o=0;o=this.blockSize&&this.incrementCounter(),i&&(a-=i,i=0)}return this.offset=(this.offset+n.length%4)%4,s},e.prototype.decrypt=function(e,t){return this.encrypt(e,t)},e.prototype.incrementCounter=function(){for(var e=this.counter.length-1;e>=0&&!(++this.counter[e]<4294967295);e--);},e}();t.default=h},function(e,t,n){(function(t){let n;class s{constructor(e){n||(n=e||"debug"),this.isBrowser=void 0===t||"renderer"===t.type||!0===t.browser||t.__nwjs,this.isBrowser?this.colors={start:"%c",warn:"color : #ff00ff",info:"color : #ffff00",debug:"color : #00ffff",error:"color : #ff0000",end:""}:this.colors={start:"",warn:"",info:"",debug:"",error:"",end:""},this.messageFormat="[%t] [%l] - [%m]"}static setLevel(e){n=e}canSend(e){return s.levels.indexOf(n)>=s.levels.indexOf(e)}warn(e){this._log("warn",e,this.colors.warn)}info(e){this._log("info",e,this.colors.info)}debug(e){this._log("debug",e,this.colors.debug)}error(e){this._log("error",e,this.colors.error)}format(e,t){return this.messageFormat.replace("%t",(new Date).toISOString()).replace("%l",t.toUpperCase()).replace("%m",e)}_log(e,t,s){n&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(t,e),s):console.log(s+this.format(t,e)+this.colors.end))}}var i,a,r;r=["error","warn","info","debug"],(a="levels")in(i=s)?Object.defineProperty(i,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[a]=r,e.exports=s}).call(this,n(83))},function(e,t,n){const{RPCError:s,InvalidDCError:i,FloodError:a,BadRequestError:r}=n(36);class o extends i{constructor(e){const t=Number(e.capture||0);super(`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class c extends i{constructor(e){const t=Number(e.capture||0);super(`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class u extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`,this.seconds=t}}class d extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`,this.seconds=t}}class l extends a{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`,this.seconds=t}}class f extends i{constructor(e){const t=Number(e.capture||0);super(`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`),this.message=`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class p extends i{constructor(e){const t=Number(e.capture||0);super(`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class g extends r{constructor(e){const t=Number(e.capture||0);super(`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`),this.message=`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`,this.codeLength=t}}const h=[[/FILE_MIGRATE_(\d+)/,f],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,l],[/FLOOD_WAIT_(\d+)/,d],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,u],[/USER_MIGRATE_(\d+)/,o],[/NETWORK_MIGRATE_(\d+)/,p],[/EMAIL_UNCONFIRMED_(\d+)/,g]];e.exports={rpcErrorRe:h,FileMigrateError:f,FloodTestPhoneWaitError:l,FloodWaitError:d,PhoneMigrateError:c,SlowModeWaitError:u,UserMigrateError:o,NetworkMigrateError:p,EmailUnconfirmedError:g}},function(e,t){e.exports=class{get dcId(){throw new Error("Not Implemented")}get serverAddress(){throw new Error("Not Implemented")}get port(){throw new Error("Not Implemented")}get authKey(){throw new Error("Not Implemented")}set authKey(e){throw new Error("Not Implemented")}setDC(e,t,n){throw new Error("Not implemented")}save(){throw new Error("Not Implemented")}delete(){throw new Error("Not Implemented")}}},function(e,t,n){const s=n(6),i={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)i[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))i[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:128,tlobjects:i}},function(e,t,n){const s=n(51),i=n(52),a=n(8),r=n(28),o=n(56),c=n(55),u=n(38),d=n(32),l=n(86),{MsgsAck:f,upload:p,MsgsStateInfo:g,Pong:h}=n(21).constructors,m=n(57),y=n(25),{UpdateConnectionState:b}=n(59),{BadMessageError:_}=n(23),{BadServerSalt:w,BadMsgNotification:v,MsgDetailedInfo:A,MsgNewDetailedInfo:I,NewSessionCreated:P,FutureSalts:C,MsgsStateReq:S,MsgResendReq:M,MsgsAllInfo:k}=n(21).constructors,{SecurityError:E}=n(23),{InvalidBufferError:R}=n(23),{LogOut:U}=n(21).requests.auth,{RPCMessageToError:O}=n(29),{TypeNotFoundError:T}=n(23);class D{constructor(e,t){const n={...D.DEFAULT_OPTIONS,...t};this._connection=void 0,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new r,this._state=new i(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[u.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[d.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[w.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[I.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[f.CONSTRUCTOR_ID]:this._handleAck.bind(this),[C.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[S.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this._connection=e;for(let e=0;e1024)throw new u("Server replied with the wrong message padding");const y=f.tgReadObject();return new c(p,g,y)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=s(Math.floor(e)).shiftLeft(s(32)).or(s(t).shiftLeft(s(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(s(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,i=Math.floor((new Date).getTime()/1e3),a=e.shiftRight(s(32));return this.timeOffset=a-i,this.timeOffset!==n&&(this._lastMsgId=s(0),this._log.debug(`Updated time offset (old offset ${n}, bad ${t}, good ${e}, new ${this.timeOffset})`)),this.timeOffset}_getSeqNo(e){if(e){const e=2*this._sequence+1;return this._sequence+=1,e}return 2*this._sequence}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const{IGE:s}=n(45),i=n(8);e.exports=class{constructor(e,t){this.ige=new s(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const n=e.length%16;return n&&(e=t.concat([e,i.generateRandomBytes(16-n)])),i.convertToLittle(this.ige.encrypt(e))}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(37),i=n(55),a=n(38),r=n(32),o={[i.CONSTRUCTOR_ID]:i,[r.CONSTRUCTOR_ID]:r,[a.CONSTRUCTOR_ID]:a};e.exports={TLMessage:s,RPCResult:i,MessageContainer:a,GZIPPacked:r,coreObjects:o}},function(e,t,n){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{RpcError:i}=n(21).constructors,a=n(32);class r{constructor(e,t,n){this.CONSTRUCTOR_ID=4082920705,this.reqMsgId=e,this.body=t,this.error=n,this.classType="constructor"}static async fromReader(e){const t=e.readLong(),n=e.readInt(!1);return n===i.CONSTRUCTOR_ID?new r(t,void 0,i.fromReader(e)):n===a.CONSTRUCTOR_ID?new r(t,(await a.fromReader(e)).data):(e.seek(-4),new r(t,e.read(),void 0))}}s(r,"CONSTRUCTOR_ID",4082920705),s(r,"classType","constructor"),e.exports=r},function(e,t,n){(function(t){const s=n(15),i=n(53),a=n(28),r=n(84),o=n(85),c=n(8),{constructors:u,requests:d}=n(21),l=n(25),{SecurityError:f}=n(23);e.exports=async function(e,n){let p=c.generateRandomBytes(16);const g=c.readBigIntFromBuffer(p,!1,!0),h=await e.send(new d.ReqPqMulti({nonce:g}));if(n.debug("Starting authKey generation step 1"),!(h instanceof u.ResPQ))throw new Error("Step 1 answer was "+h);if(h.nonce.neq(g))throw new f("Step 1 invalid nonce from server");const m=c.readBigIntFromBuffer(h.pq,!1,!0);n.debug("Finished authKey generation step 1"),n.debug("Starting authKey generation step 2");let{p:y,q:b}=r.factorize(m);y=c.getByteArray(y),b=c.getByteArray(b),p=c.generateRandomBytes(32);const _=c.readBigIntFromBuffer(p,!0,!0),w=new u.PQInnerData({pq:c.getByteArray(m),p:y,q:b,nonce:h.nonce,serverNonce:h.serverNonce,newNonce:_});let v,A;for(const e of h.serverPublicKeyFingerprints)if(v=await o.encrypt(e.toString(),w.getBytes()),void 0!==v){A=e;break}if(void 0===v)throw new f("Step 2 could not find a valid key for fingerprints");const I=await e.send(new d.ReqDHParams({nonce:h.nonce,serverNonce:h.serverNonce,p:y,q:b,publicKeyFingerprint:A,encryptedData:v}));if(!(I instanceof u.ServerDHParamsOk||I instanceof u.ServerDHParamsFail))throw new Error("Step 2.1 answer was "+I);if(I.nonce.neq(h.nonce))throw new f("Step 2 invalid nonce from server");if(I.serverNonce.neq(h.serverNonce))throw new f("Step 2 invalid server nonce from server");if(I instanceof u.ServerDHParamsFail){const e=await c.sha1(c.toSignedLittleBuffer(_,32).slice(4,20)),t=c.readBigIntFromBuffer(e,!0,!0);if(I.newNonceHash.neq(t))throw new f("Step 2 invalid DH fail nonce from server")}if(!(I instanceof u.ServerDHParamsOk))throw new Error("Step 2.2 answer was "+I);n.debug("Finished authKey generation step 2"),n.debug("Starting authKey generation step 3");const{key:P,iv:C}=await c.generateKeyDataFromNonce(h.serverNonce,_);if(I.encryptedAnswer.length%16!=0)throw new f("Step 3 AES block size mismatch");const S=new i(P,C),M=S.decryptIge(I.encryptedAnswer),k=new l(M);k.read(20);const E=k.tgReadObject();if(!(E instanceof u.ServerDHInnerData))throw new Error("Step 3 answer was "+E);if(E.nonce.neq(h.nonce))throw new f("Step 3 Invalid nonce in encrypted answer");if(E.serverNonce.neq(h.serverNonce))throw new f("Step 3 Invalid server nonce in encrypted answer");const R=c.readBigIntFromBuffer(E.dhPrime,!1,!1),U=c.readBigIntFromBuffer(E.gA,!1,!1),O=E.serverTime-Math.floor((new Date).getTime()/1e3),T=c.readBigIntFromBuffer(c.generateRandomBytes(256),!1,!1),D=c.modExp(s(E.g),T,R),B=c.modExp(U,T,R),x=new u.ClientDHInnerData({nonce:h.nonce,serverNonce:h.serverNonce,retryId:0,gB:c.getByteArray(D,!1)}).getBytes(),j=t.concat([await c.sha1(x),x]),N=S.encryptIge(j),V=await e.send(new d.SetClientDHParams({nonce:h.nonce,serverNonce:h.serverNonce,encryptedData:N})),F=[u.DhGenOk,u.DhGenRetry,u.DhGenFail];if(!(V instanceof F[0]||V instanceof F[1]||V instanceof F[2]))throw new Error("Step 3.1 answer was "+V);const{name:L}=V.constructor;if(V.nonce.neq(h.nonce))throw new f(`Step 3 invalid ${L} nonce from server`);if(V.serverNonce.neq(h.serverNonce))throw new f(`Step 3 invalid ${L} server nonce from server`);const q=new a;await q.setKey(c.getByteArray(B));const H=1+F.indexOf(V.constructor),K=await q.calcNewNonceHash(_,H);if(V["newNonceHash"+H].neq(K))throw new f("Step 3 invalid new nonce hash");if(!(V instanceof u.DhGenOk))throw new Error("Step 3.2 answer was "+V);return n.debug("Finished authKey generation step 3"),{authKey:q,timeOffset:O}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const s=n(38),i=n(37),a=n(58);e.exports=class{constructor(e,t){this._state=e,this._queue=[],this._pendingStates=[],this._ready=new Promise(e=>{this.setReady=e}),this._log=t}values(){return this._queue}append(e){this._queue.push(e),this.setReady(!0),e&&(this._pendingStates.push(e),e.promise.catch(()=>{}).finally(()=>{this._pendingStates=this._pendingStates.filter(t=>t!==e)}))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise(e=>{this.setReady=e}),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,n=new a(t.alloc(0));const r=[];let o=0;for(;this._queue.length&&r.length<=s.MAXIMUM_LENGTH;){const e=this._queue.shift();if(o+=e.data.length+i.SIZE_OVERHEAD,o<=s.MAXIMUM_SIZE){let t;e.after&&(t=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(n,e.data,"request"===e.request.classType,t),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),r.push(e)}else{if(r.length){this._queue.unshift(e);break}this._log.warn(`Message payload for ${e.request.className||e.request.constructor.name} is too long ${e.data.length} and cannot be sent`),e.reject("Request Payload is too big"),o=0}}if(r.length){if(r.length>1){const i=t.alloc(8);i.writeUInt32LE(s.CONSTRUCTOR_ID,0),i.writeInt32LE(r.length,4),e=t.concat([i,n.getValue()]),n=new a(t.alloc(0));const o=await this._state.writeDataAsMessage(n,e,!1);for(const e of r)e.containerId=o}return e=n.getValue(),{batch:r,data:e}}}rejectAll(){this._pendingStates.forEach(e=>{e.reject(new Error("Disconnect"))})}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){e.exports=class{constructor(e){this._stream=e}write(e){this._stream=t.concat([this._stream,e])}getValue(){return this._stream}}}).call(this,n(12).Buffer)},function(e,t,n){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(51),a=n(56),r=n(50);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(87);e.exports={Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:i,doAuthentication:a,MTProtoSender:r,UpdateConnectionState:o}},function(e,t,n){(function(t){const{Mutex:s}=n(88),i=new s,a=n(90).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(){this.client=void 0,this.closed=!0}async readExactly(e){let n=t.alloc(0);for(;;){const s=await this.read(e);if(n=t.concat([n,s]),!(e-=s.length))return n}}async read(e){if(this.closed)throw r;if(await this.canRead,this.closed)throw r;const t=this.stream.slice(0,e);return this.stream=this.stream.slice(e),0===this.stream.length&&(this.canRead=new Promise(e=>{this.resolveRead=e})),t}async readAll(){if(this.closed||!await this.canRead)throw r;const e=this.stream;return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),e}getWebSocketLink(e,t){return 443===t?`wss://${e}:${t}/apiws`:`ws://${e}:${t}/apiws`}connect(e,n){return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),this.closed=!1,this.website=this.getWebSocketLink(n,e),this.client=new a(this.website,"binary"),new Promise((e,t)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{t(e)},this.client.onclose=()=>{this.resolveRead(!1),this.closed=!0},self.addEventListener("offline",async()=>{await this.close(),this.resolveRead(!1)})})}write(e){if(this.closed)throw r;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}receive(){this.client.onmessage=async e=>{const n=await i.acquire();try{const s=e.data instanceof ArrayBuffer?t.from(e.data):t.from(await new Response(e.data).arrayBuffer());this.stream=t.concat([this.stream,s]),this.resolveRead(!0)}finally{n()}}}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(){this._queue=[],this.canGet=new Promise(e=>{this.resolveGet=e}),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise(e=>{this.resolvePush=e})}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise(e=>{this.resolveGet=e}),e}}},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(15),{readBufferFromBigInt:a}=n(8),{Connection:r,PacketCodec:o}=n(39);class c extends o{constructor(e){super(e),this.tag=c.tag,this.obfuscateTag=c.obfuscateTag}encodePacket(e){let n=e.length>>2;if(n<127){const e=t.alloc(1);e.writeUInt8(n,0),n=e}else n=t.concat([t.from("7f","hex"),a(i(n),3)]);return t.concat([n,e])}async readPacket(e){let n=(await e.read(1))[0];return n>=127&&(n=t.concat([await e.read(3),t.alloc(1)]).readInt32LE(0)),e.read(n<<2)}}s(c,"tag",t.from("ef","hex")),s(c,"obfuscateTag",t.from("efefefef","hex"));e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),s(this,"PacketCodecClass",c)}},AbridgedPacketCodec:c}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{generateRandomBytes:i}=n(8),{ObfuscatedConnection:a}=n(39),{AbridgedPacketCodec:r}=n(62),o=n(94);class c{constructor(e){s(this,"header",void 0),this.connection=e.socket;const t=this.initHeader(e.PacketCodecClass);this.header=t.random,this._encrypt=t.encryptor,this._decrypt=t.decryptor}initHeader(e){const n=[t.from("50567247","hex"),t.from("474554","hex"),t.from("504f5354","hex"),t.from("eeeeeeee","hex")];let s;for(;;)if(s=i(64),239!==s[0]&&!s.slice(4,8).equals(t.alloc(4))){let e=!0;for(const t of n)if(t.equals(s.slice(0,4))){e=!1;break}if(e)break}s=s.toJSON().data;const a=t.from(s.slice(8,56)).reverse(),r=t.from(s.slice(8,40)),c=t.from(s.slice(40,56)),u=t.from(a.slice(0,32)),d=t.from(a.slice(32,48)),l=new o(r,c),f=new o(u,d);return s=t.concat([t.from(s.slice(0,56)),e.obfuscateTag,t.from(s.slice(60))]),s=t.concat([t.from(s.slice(0,56)),t.from(l.encrypt(s).slice(56,64)),t.from(s.slice(64))]),{random:s,encryptor:l,decryptor:f}}async read(e){const t=await this.connection.readExactly(e);return this._decrypt.encrypt(t)}write(e){this.connection.write(this._encrypt.encrypt(e))}}e.exports={ConnectionTCPObfuscated:class extends a{constructor(...e){super(...e),s(this,"ObfuscatedIO",c),s(this,"PacketCodecClass",r)}}}}).call(this,n(12).Buffer)},function(e,t){},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(s||(s={}));const i=-1,a="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(s||(s={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return r}));var s=n(1),i=n(0),a=n(2);async function r({chatId:t,accessHash:n,messageId:r,data:o}){const c=await Object(s.g)(new i.Api.messages.GetBotCallbackAnswer({peer:Object(a.i)(t,n),msgId:r,data:e.from(o)}));if(c)return c}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";t.byteLength=function(e){var t=u(e),n=t[0],s=t[1];return 3*(n+s)/4-s},t.toByteArray=function(e){var t,n,s=u(e),r=s[0],o=s[1],c=new a(function(e,t,n){return 3*(t+n)/4-n}(0,r,o)),d=0,l=o>0?r-4:r;for(n=0;n>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===o&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[d++]=255&t);1===o&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,a=[],r=0,o=n-i;ro?o:r+16383));1===i?(t=e[n-1],a.push(s[t>>2]+s[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],a.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return a.join("")};for(var s=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=r.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e,t,n){for(var i,a,r=[],o=t;o>18&63]+s[a>>12&63]+s[a>>6&63]+s[63&a]);return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,s,i){var a,r,o=8*i-s-1,c=(1<>1,d=-7,l=n?i-1:0,f=n?-1:1,p=e[t+l];for(l+=f,a=p&(1<<-d)-1,p>>=-d,d+=o;d>0;a=256*a+e[t+l],l+=f,d-=8);for(r=a&(1<<-d)-1,a>>=-d,d+=s;d>0;r=256*r+e[t+l],l+=f,d-=8);if(0===a)a=1-u;else{if(a===c)return r?NaN:1/0*(p?-1:1);r+=Math.pow(2,s),a-=u}return(p?-1:1)*r*Math.pow(2,a-s)},t.write=function(e,t,n,s,i,a){var r,o,c,u=8*a-i-1,d=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:a-1,g=s?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,r=d):(r=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-r))<1&&(r--,c*=2),(t+=r+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(r++,c/=2),r+l>=d?(o=0,r=d):r+l>=1?(o=(t*c-1)*Math.pow(2,i),r+=l):(o=t*Math.pow(2,l-1)*Math.pow(2,i),r=0));i>=8;e[n+p]=255&o,p+=g,o/=256,i-=8);for(r=r<0;e[n+p]=255&r,p+=g,r/=256,u-=8);e[n+p-g]|=128*h}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";function s(e){const t=new Uint8Array(4*e.length);let n=0;for(let s=0;s>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=255&i}return t.buffer}function i(e){return e.buffer}function a(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;enew p.InvokeWithLayer({layer:l,query:new p.InitConnection({apiId:this.apiId,deviceModel:r.deviceModel||s.type().toString()||"Unknown",systemVersion:r.systemVersion||s.release().toString()||"1.0",appVersion:r.appVersion||"1.0",langCode:r.langCode,langPack:"",systemLangCode:r.systemLangCode,query:e,proxy:void 0})}),this._args=r,this._config=void 0,this.phoneCodeHashes=[],this._borrowedSenderPromises={},this._additionalDcsDisabled=r.additionalDcsDisabled}async connect(){await this._initSession(),this._sender=new g(this.session.getAuthKey(),{logger:this._log,dcId:this.session.dcId,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),updateCallback:this._handleUpdate.bind(this),isMainSender:!0});const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log);await this._sender.connect(e),this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new p.help.GetConfig({}))),this._updateLoop()}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"venus.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;this.isConnected();){await c.sleep(3e3);try{await S(()=>{return e=this._sender.send(new p.Ping({pingId:c.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)})),t=1500,Promise.race([e,c.sleep(t).then(()=>Promise.reject(new Error("TIMEOUT")))]);var e,t},3,100)}catch(e){return await this.disconnect(),void this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new p.updates.GetState)}catch(e){}}}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._borrowedSenderPromises).map(e=>e.then(e=>{if(e)return e.disconnect()}))),this._borrowedSenderPromises={}}async destroy(){await this.disconnect(),this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info("Reconnecting to new data center "+e);const t=u.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}_cleanupBorrowedSender(e){delete this._borrowedSenderPromises[e]}_borrowExportedSender(e){if(this._additionalDcsDisabled)return;let t=this._borrowedSenderPromises[e];return t||(t=this._createExportedSender(e),this._borrowedSenderPromises[e]=t,t.then(t=>{t||delete this._borrowedSenderPromises[e]})),t}async _createExportedSender(e){const t=u.getDC(e),n=new g(this.session.getAuthKey(e),{logger:this._log,dcId:e,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),isMainSender:e===this.session.dcId,onConnectionBreak:this._cleanupBorrowedSender.bind(this)});for(let s=0;s<5;s++)try{if(await n.connect(new this._connection(t.ipAddress,t.port,e,this._log)),this.session.dcId!==e){this._log.info("Exporting authorization for data center "+t.ipAddress);const s=await this.invoke(new p.auth.ExportAuthorization({dcId:e})),i=this._initWith(new p.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await n.send(i)}return n.dcId=e,n}catch(e){await n.disconnect()}}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof f.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof f.MessageMediaWebPage&&n.webpage instanceof f.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof f.MessageMediaPhoto||n instanceof f.Photo?this._downloadPhoto(n,t):n instanceof f.MessageMediaDocument||n instanceof f.Document?this._downloadDocument(n,t):n instanceof f.MessageMediaContact?this._downloadContact(n,t):n instanceof f.WebDocument||n instanceof f.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,i,a;if([765557111,3316604308,524706233,3566872215].includes(e.SUBCLASS_OF_ID)){if(!e.photo){if(!e.chatPhoto)return;return this._downloadPhoto(e.chatPhoto,{sizeType:n})}s=e.photo}else s=e;if(s instanceof f.UserProfilePhoto||s instanceof f.ChatPhoto)return i=s.dcId,a=new f.InputPeerPhotoFileLocation({peer:u.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(a,{dcId:i})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new f.InputStickerSetThumb({stickerset:new f.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=v.indexOf(t);se.type===v[s]),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof f.PhotoStrippedSize?u.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof f.MessageMediaPhoto&&(e=e.photo),!(e instanceof f.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof f.PhotoSizeEmpty?void 0:n instanceof f.PhotoCachedSize||n instanceof f.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new f.InputPhotoFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n.type}),{dcId:e.dcId,fileSize:n.size,progressCallback:t.progressCallback})}_downloadDocument(e,t){if(e instanceof f.MessageMediaDocument&&(e=e.document),!(e instanceof f.Document))return;let n;if(t.sizeType){if(n=e.thumbs?this._pickFileSize(e.thumbs,t.sizeType):void 0,!n&&e.mimeType.startsWith("video/"))return;if(n&&(n instanceof f.PhotoCachedSize||n instanceof f.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new f.InputDocumentFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n?n.type:""}),{fileSize:n?n.size:e.size,progressCallback:t.progressCallback,start:t.start,end:t.end,dcId:e.dcId,workers:t.workers})}_downloadContact(e,t){throw new Error("not implemented")}_downloadWebDocument(e,t){throw new Error("not implemented")}async invoke(e){if("request"!==e.classType)throw new Error("You can only invoke MTProtoRequests");this._lastRequest=(new Date).getTime();let t=0;for(t=0;t1)for(var n=1;n{d[i(e.slice(-8),!0,!0)]=t}),e.exports={encrypt:async function(e,n){const u=d[e];if(!u)return;const l=o(235-n.length),f=t.concat([await r(n),n,l]),p=i(f,!1),g=c(p,s(u.e),u.n);return a(g,256,!1)}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(e,t){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}},function(e,t,n){const{Connection:s}=n(39),{ConnectionTCPFull:i}=n(93),{ConnectionTCPAbridged:a}=n(62),{ConnectionTCPObfuscated:r}=n(63);e.exports={Connection:s,ConnectionTCPFull:i,ConnectionTCPAbridged:a,ConnectionTCPObfuscated:r}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n(89);t.Mutex=s.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(){this._queue=[],this._pending=!1}return e.prototype.isLocked=function(){return this._pending},e.prototype.acquire=function(){var e=this,t=new Promise((function(t){return e._queue.push(t)}));return this._pending||this._dispatchNext(),t},e.prototype.runExclusive=function(e){return this.acquire().then((function(t){var n;try{n=e()}catch(e){throw t(),e}return Promise.resolve(n).then((function(e){return t(),e}),(function(e){throw t(),e}))}))},e.prototype._dispatchNext=function(){this._queue.length>0?(this._pending=!0,this._queue.shift()(this._dispatchNext.bind(this))):this._pending=!1},e}();t.default=s},function(e,t,n){(function(t){var s=function(){return this||void 0===t?this:t}(),i=s.WebSocket||s.MozWebSocket,a=n(91);function r(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(r,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?r:null,version:a}}).call(this,n(43))},function(e,t,n){e.exports=n(92).version},function(e){e.exports=JSON.parse('{"_args":[["websocket@1.0.30","/Users/alexander/dev/telegram-tt"]],"_from":"websocket@1.0.30","_id":"websocket@1.0.30","_inBundle":false,"_integrity":"sha512-aO6klgaTdSMkhfl5VVJzD5fm+Srhh5jLYbS15+OiI1sN6h/RU/XW6WN9J1uVIpUKNmsTvT3Hs35XAFjn9NMfOw==","_location":"/websocket","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"websocket@1.0.30","name":"websocket","escapedName":"websocket","rawSpec":"1.0.30","saveSpec":null,"fetchSpec":"1.0.30"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/websocket/-/websocket-1.0.30.tgz","_spec":"1.0.30","_where":"/Users/alexander/dev/telegram-tt","author":{"name":"Brian McKelvey","email":"theturtle32@gmail.com","url":"https://github.com/theturtle32"},"browser":"lib/browser.js","bugs":{"url":"https://github.com/theturtle32/WebSocket-Node/issues"},"config":{"verbose":false},"contributors":[{"name":"Iñaki Baz Castillo","email":"ibc@aliax.net","url":"http://dev.sipdoc.net"}],"dependencies":{"debug":"^2.2.0","nan":"^2.14.0","typedarray-to-buffer":"^3.1.5","yaeti":"^0.0.6"},"description":"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.","devDependencies":{"buffer-equal":"^1.0.0","faucet":"^0.0.1","gulp":"^4.0.2","gulp-jshint":"^2.0.4","jshint":"^2.0.0","jshint-stylish":"^2.2.1","tape":"^4.9.1"},"directories":{"lib":"./lib"},"engines":{"node":">=0.10.0"},"homepage":"https://github.com/theturtle32/WebSocket-Node","keywords":["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],"license":"Apache-2.0","main":"index","name":"websocket","repository":{"type":"git","url":"git+https://github.com/theturtle32/WebSocket-Node.git"},"scripts":{"gulp":"gulp","install":"(node-gyp rebuild 2> builderror.log) || (exit 0)","test":"faucet test/unit"},"version":"1.0.30"}')},function(e,t){},function(e,t,n){(function(t){const s=n(35);e.exports=class{constructor(e,n){if(!t.isBuffer(e)||!t.isBuffer(n)||16!==n.length)throw new Error("Key and iv need to be a buffer");this.cipher=s.createCipheriv("AES-256-CTR",e,n)}encrypt(e){return t.from(this.cipher.update(e))}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"authFlow",(function(){return u})),n.d(t,"checkAuthorization",(function(){return d}));var s=n(6),i=n.n(s),a=n(20),r=n.n(a),o=n(8),c=n(31);async function u(e,t,n){const s="phoneNumber"in n?await l(e,t,n):await async function(e,t,n){const{apiId:s,apiHash:a}=t,{botAuthToken:r}=n,{user:o}=await e.invoke(new i.a.auth.ImportBotAuthorization({apiId:s,apiHash:a,botAuthToken:r}));return o}(e,t,n);e._log.info("Signed in successfully as",r.a.getDisplayName(s))}async function d(e){try{return await e.invoke(new i.a.updates.GetState),!0}catch(e){return!1}}async function l(e,t,n){let s,a,r,o=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return f(e,t,n);throw s}else s=n.phoneNumber;const i=await p(e,t,s,n.forceSMS);if(a=i.phoneCodeHash,o=i.isCodeViaApp,"string"!=typeof a)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,u=!1;for(;;)try{try{r=await n.phoneCode(o)}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n)}if(!r)throw new Error("Code is empty");const d=await e.invoke(new i.a.auth.SignIn({phoneNumber:s,phoneCodeHash:a,phoneCode:r}));if(d instanceof i.a.auth.AuthorizationSignUpRequired){u=!0,c=d.termsOfService;break}return d.user}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);n.onError(s)}if(u)for(;;)try{const[t,r]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:o}=await e.invoke(new i.a.auth.SignUp({phoneNumber:s,phoneCodeHash:a,firstName:t,lastName:r}));return c&&await e.invoke(new i.a.help.AcceptTermsOfService({id:c.id})),o}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),l(e,t,n)}async function f(e,t,n){let s=!1;const a=(async()=>{for(;!s;){const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("739222"),apiHash:"60d1e1063c72d4bc4cfdda99e8906f94",exceptIds:[]}));if(!(t instanceof i.a.auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:a}=t;await Promise.race([n.qrCode({token:s,expires:a}),Object(o.sleep)(3e4)])}})(),r=new Promise(t=>{e.addEventHandler(e=>{e instanceof i.a.UpdateLoginToken&&t()},{build:e=>e})});try{await Promise.race([r,a])}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("739222"),apiHash:"60d1e1063c72d4bc4cfdda99e8906f94",exceptIds:[]}));if(t instanceof i.a.auth.LoginTokenSuccess&&t.authorization instanceof i.a.auth.Authorization)return t.authorization.user;if(t instanceof i.a.auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new i.a.auth.ImportLoginToken({token:t.token}));if(n instanceof i.a.auth.LoginTokenSuccess&&n.authorization instanceof i.a.auth.Authorization)return n.authorization.user}}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);throw s}throw void 0}async function p(e,t,n,s=!1){try{const{apiId:a,apiHash:r}=t,o=await e.invoke(new i.a.auth.SendCode({phoneNumber:n,apiId:a,apiHash:r,settings:new i.a.CodeSettings}));if(!s||o.type instanceof i.a.auth.SentCodeTypeSms)return{phoneCodeHash:o.phoneCodeHash,isCodeViaApp:o.type instanceof i.a.auth.SentCodeTypeApp};const c=await e.invoke(new i.a.auth.ResendCode({phoneNumber:n,phoneCodeHash:o.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof i.a.auth.SentCodeTypeApp}}catch(i){if("AUTH_RESTART"===i.message)return p(e,t,n,s);throw i}}async function g(e,t,n){for(;;)try{const t=await e.invoke(new i.a.account.GetPassword),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const a=await Object(c.computeCheck)(t,s),{user:r}=await e.invoke(new i.a.auth.CheckPassword({password:a}));return r}catch(e){n.onError(e)}}},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"downloadFile",(function(){return u}));var s=n(6),i=n.n(s),a=n(20),r=n(8);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class c{constructor(e){this.maxWorkers=e,o(this,"deferred",void 0),o(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=function(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function u(t,n,s){let{partSizeKb:o,end:u}=s;const{fileSize:d,workers:l=1}=s,{dcId:f,progressCallback:p,start:g=0}=s;u=u&&u{try{const s=await Promise.race([await y.send(new i.a.upload.GetFile({location:n,offset:w,limit:e,precise:t||void 0})),Object(r.sleep)(15e3).then(()=>Promise.reject(new Error("REQUEST_TIMEOUT")))]);if(p){if(p.isCanceled)throw new Error("USER_CANCELED");A+=1/m,p(A)}return!u&&s.bytes.lengthu)break}const I=(await Promise.all(_)).filter(Boolean),P=u?u+1-g:void 0;return e.concat(I,P)}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"uploadFile",(function(){return o}));var s=n(6),i=n.n(s),a=n(8),r=n(20);async function o(t,n){const{file:s,onProgress:o}=n;let{workers:c}=n;const{name:u,size:d}=s,l=Object(a.readBigIntFromBuffer)(Object(a.generateRandomBytes)(8),!0,!0),f=d>10485760,p=1024*Object(r.getAppropriatedPartSize)(d),g=Math.floor((d+p-1)/p),h=e.from(await function(e){return new Response(e).arrayBuffer()}(s)),m=await t._borrowExportedSender(t.session.dcId);c&&d||(c=1),c>=g&&(c=g);let y=0;o&&o(y);for(let e=0;eg&&(n=g);for(let s=e;s{if(await m.send(f?new i.a.upload.SaveBigFilePart({fileId:l,filePart:s,fileTotalParts:g,bytes:e}):new i.a.upload.SaveFilePart({fileId:l,filePart:s,bytes:e})),o){if(o.isCanceled)throw new Error("USER_CANCELED");y+=1/g,o(y)}})())}try{await Promise.race([await Promise.all(t),Object(a.sleep)(15e3*c).then(()=>Promise.reject(new Error("TIMEOUT")))])}catch(t){if("TIMEOUT"===t.message){console.warn("Upload timeout. Retrying..."),e-=c;continue}throw t}}return f?new i.a.InputFileBig({id:l,parts:g,name:u}):new i.a.InputFile({id:l,parts:g,name:u,md5Checksum:""})}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"updateTwoFaSettings",(function(){return u}));var s=n(6),i=n.n(s),a=n(8),r=n(31),o=n(29),c=n.n(o);async function u(t,{isCheckPassword:n,currentPassword:s,newPassword:o,hint:u="",email:d,emailCodeCallback:l,onEmailCodeError:f}){if(!o&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(d&&(!l||!f))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await t.invoke(new i.a.account.GetPassword);p.newAlgo instanceof i.a.PasswordKdfAlgoUnknown||(p.newAlgo.salt1=e.concat([p.newAlgo.salt1,Object(a.generateRandomBytes)(32)])),!p.hasPassword&&s&&(s=void 0);const g=s?await Object(r.computeCheck)(p,s):new i.a.InputCheckPasswordEmpty;if(n)await t.invoke(new i.a.auth.CheckPassword({password:g}));else try{await t.invoke(new i.a.account.UpdatePasswordSettings({password:g,newSettings:new i.a.account.PasswordInputSettings({newAlgo:p.newAlgo,newPasswordHash:o?await Object(r.computeDigest)(p.newAlgo,o):e.alloc(0),hint:u,email:d,newSecureSettings:void 0})}))}catch(e){if(!(e instanceof c.a.EmailUnconfirmedError))throw e;for(;;)try{const n=await l(e.codeLength);if(!n)throw new Error("Code is empty");await t.invoke(new i.a.account.ConfirmPasswordEmail({code:n}));break}catch(e){f(e)}}}}.call(this,n(12).Buffer)},function(e,t){e.exports="0.0.2"},function(e,t,n){const s=n(101),i=n(102);class a extends Error{}e.exports={NewMessage:s,StopPropagation:a,Raw:i}},function(e,t){},function(e,t,n){const{EventBuilder:s}=n(103);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},function(e,t){e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},function(e,t,n){const s=n(27),i=n(105),a=n(106),r=n(107),o=n(108),c=n(110);e.exports={Memory:s,StringSession:i,CacheApiSession:a,LocalStorageSession:r,IdbSession:o,CallbackSession:c}},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(25);class r extends s{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new a(t);this._dcId=n.read(1).readUInt8(0);const s=n.read(2).readInt16BE(0);this._serverAddress=String(n.read(s)),this._port=n.read(2).readInt16BE(0),this._key=n.read(-1)}}static encode(e){return e.toString("base64")}static decode(e){return t.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=t.from([this.dcId]),n=t.from(this.serverAddress),s=t.alloc(2);s.writeInt16BE(n.length,0);const i=t.alloc(2);return i.writeInt16BE(this.port,0),"1"+r.encode(t.concat([e,s,n,i,this.authKey.getKey()]))}getAuthKey(e){if(!e||e===this.dcId)return this.authKey}setAuthKey(e,t){t&&t!==this.dcId||(this.authKey=e)}}e.exports=r}).call(this,n(12).Buffer)},function(e,t,n){const s=n(40);e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open("GramJs")).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open("GramJs"),n=await t.match(e);return n?n.text():void 0}async _saveToCache(e){const t=new Request(this._storageKey),n=new Response(e);return(await self.caches.open("GramJs")).put(t,n)}}},function(e,t,n){const s=n(40);e.exports=class extends s{_delete(){return localStorage.removeItem(this._storageKey)}_fetchFromCache(){return localStorage.getItem(this._storageKey)}_saveToCache(e){return localStorage.setItem(this._storageKey,e)}}},function(e,t,n){const s=n(109),i=n(40);e.exports=class extends i{_delete(){return s.del("GramJs:"+this._storageKey)}_fetchFromCache(){return s.get("GramJs:"+this._storageKey)}_saveToCache(e){return s.set("GramJs:"+this._storageKey,e)}}},function(e,t,n){"use strict";function s(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function i(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const i=s(n);return(e,n)=>i.then(s=>n(s.transaction(t,e).objectStore(t)))}let a;function r(){return a||(a=i("keyval-store","keyval")),a}function o(e,t=r()){return t("readonly",t=>s(t.get(e)))}function c(e,t,n=r()){return n("readwrite",n=>(n.put(t,e),s(n.transaction)))}function u(e,t=r()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),s(t.transaction)))}function d(e,t=r()){return t("readonly",t=>Promise.all(e.map(e=>s(t.get(e)))))}function l(e,t,n=r()){return n("readwrite",n=>new Promise((i,a)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),i(s(n.transaction))}catch(e){a(e)}}}))}function f(e,t=r()){return t("readwrite",t=>(t.delete(e),s(t.transaction)))}function p(e=r()){return e("readwrite",e=>(e.clear(),s(e.transaction)))}function g(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},s(e.transaction)))}function h(e=r()){const t=[];return g(e,e=>t.push(e.key)).then(()=>t)}function m(e=r()){const t=[];return g(e,e=>t.push(e.value)).then(()=>t)}function y(e=r()){const t=[];return g(e,e=>t.push([e.key,e.value])).then(()=>t)}n.r(t),n.d(t,"clear",(function(){return p})),n.d(t,"createStore",(function(){return i})),n.d(t,"del",(function(){return f})),n.d(t,"entries",(function(){return y})),n.d(t,"get",(function(){return o})),n.d(t,"getMany",(function(){return d})),n.d(t,"keys",(function(){return h})),n.d(t,"promisifyRequest",(function(){return s})),n.d(t,"set",(function(){return c})),n.d(t,"setMany",(function(){return u})),n.d(t,"update",(function(){return l})),n.d(t,"values",(function(){return m}))},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(20);e.exports=class extends s{constructor(e,t){super(),this._sessionData=e,this._callback=t,this._authKeys={}}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(!this._sessionData)return;const{mainDcId:e,keys:n,hashes:s}=this._sessionData,{ipAddress:r,port:o}=a.getDC(e);this.setDC(e,r,o,!0),await Promise.all(Object.keys(n).map(async e=>{const a="string"==typeof n[e]?t.from(n[e],"hex"):t.from(n[e]);if(s[e]){const n="string"==typeof s[e]?t.from(s[e],"hex"):t.from(s[e]);this._authKeys[e]=new i(a,n)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)}))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(t=>{const n=this._authKeys[t];e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex")}),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t);var s={};n.r(s),n.d(s,"destroy",(function(){return p.a})),n.d(s,"disconnect",(function(){return p.b})),n.d(s,"downloadMedia",(function(){return p.c})),n.d(s,"fetchCurrentUser",(function(){return p.d})),n.d(s,"provideAuthPhoneNumber",(function(){return o.l})),n.d(s,"provideAuthCode",(function(){return o.j})),n.d(s,"provideAuthPassword",(function(){return o.k})),n.d(s,"provideAuthRegistration",(function(){return o.m})),n.d(s,"restartAuth",(function(){return o.n})),n.d(s,"restartAuthWithQr",(function(){return o.o})),n.d(s,"fetchChats",(function(){return c.j})),n.d(s,"fetchFullChat",(function(){return c.k})),n.d(s,"searchChats",(function(){return c.w})),n.d(s,"requestChatUpdate",(function(){return c.u})),n.d(s,"saveDraft",(function(){return c.v})),n.d(s,"clearDraft",(function(){return c.a})),n.d(s,"fetchChat",(function(){return c.h})),n.d(s,"updateChatMutedState",(function(){return c.H})),n.d(s,"createChannel",(function(){return c.b})),n.d(s,"joinChannel",(function(){return c.q})),n.d(s,"leaveChannel",(function(){return c.r})),n.d(s,"deleteChannel",(function(){return c.d})),n.d(s,"createGroupChat",(function(){return c.c})),n.d(s,"editChatPhoto",(function(){return c.g})),n.d(s,"toggleChatPinned",(function(){return c.z})),n.d(s,"toggleChatArchived",(function(){return c.y})),n.d(s,"toggleDialogUnread",(function(){return c.A})),n.d(s,"fetchChatFolders",(function(){return c.i})),n.d(s,"editChatFolder",(function(){return c.f})),n.d(s,"deleteChatFolder",(function(){return c.e})),n.d(s,"fetchRecommendedChatFolders",(function(){return c.n})),n.d(s,"getChatByUsername",(function(){return c.o})),n.d(s,"togglePreHistoryHidden",(function(){return c.B})),n.d(s,"updateChatDefaultBannedRights",(function(){return c.F})),n.d(s,"updateChatMemberBannedRights",(function(){return c.G})),n.d(s,"updateChatTitle",(function(){return c.I})),n.d(s,"updateChatAbout",(function(){return c.D})),n.d(s,"toggleSignatures",(function(){return c.C})),n.d(s,"updateChatAdmin",(function(){return c.E})),n.d(s,"fetchGroupsForDiscussion",(function(){return c.l})),n.d(s,"setDiscussionGroup",(function(){return c.x})),n.d(s,"migrateChat",(function(){return c.s})),n.d(s,"openChatByInvite",(function(){return c.t})),n.d(s,"fetchMembers",(function(){return c.m})),n.d(s,"fetchMessages",(function(){return u.g})),n.d(s,"fetchMessage",(function(){return u.e})),n.d(s,"sendMessage",(function(){return u.v})),n.d(s,"pinMessage",(function(){return u.q})),n.d(s,"unpinAllMessages",(function(){return u.y})),n.d(s,"deleteMessages",(function(){return u.b})),n.d(s,"deleteHistory",(function(){return u.a})),n.d(s,"markMessageListRead",(function(){return u.o})),n.d(s,"markMessagesRead",(function(){return u.p})),n.d(s,"requestThreadInfoUpdate",(function(){return u.r})),n.d(s,"searchMessagesLocal",(function(){return u.u})),n.d(s,"searchMessagesGlobal",(function(){return u.t})),n.d(s,"fetchWebPagePreview",(function(){return u.j})),n.d(s,"editMessage",(function(){return u.d})),n.d(s,"forwardMessages",(function(){return u.l})),n.d(s,"loadPollOptionResults",(function(){return u.n})),n.d(s,"sendPollVote",(function(){return u.w})),n.d(s,"findFirstMessageIdAfterDate",(function(){return u.k})),n.d(s,"fetchPinnedMessages",(function(){return u.h})),n.d(s,"fetchScheduledHistory",(function(){return u.i})),n.d(s,"sendScheduledMessages",(function(){return u.x})),n.d(s,"rescheduleMessage",(function(){return u.s})),n.d(s,"deleteScheduledMessages",(function(){return u.c})),n.d(s,"fetchMessageLink",(function(){return u.f})),n.d(s,"fetchFullUser",(function(){return v})),n.d(s,"fetchNearestCountry",(function(){return A})),n.d(s,"fetchTopUsers",(function(){return I})),n.d(s,"fetchContactList",(function(){return P})),n.d(s,"fetchUsers",(function(){return C})),n.d(s,"updateContact",(function(){return S})),n.d(s,"deleteUser",(function(){return M})),n.d(s,"fetchProfilePhotos",(function(){return k})),n.d(s,"fetchStickerSets",(function(){return D})),n.d(s,"fetchRecentStickers",(function(){return B})),n.d(s,"fetchFavoriteStickers",(function(){return x})),n.d(s,"fetchFeaturedStickers",(function(){return j})),n.d(s,"faveSticker",(function(){return N})),n.d(s,"fetchStickers",(function(){return V})),n.d(s,"fetchSavedGifs",(function(){return q})),n.d(s,"searchStickers",(function(){return L})),n.d(s,"installStickerSet",(function(){return H})),n.d(s,"uninstallStickerSet",(function(){return K})),n.d(s,"searchGifs",(function(){return z})),n.d(s,"fetchAnimatedEmojis",(function(){return F})),n.d(s,"fetchStickersForEmoji",(function(){return G})),n.d(s,"fetchEmojiKeywords",(function(){return W})),n.d(s,"checkChatUsername",(function(){return Z})),n.d(s,"setChatUsername",(function(){return Y})),n.d(s,"updatePrivateLink",(function(){return Q})),n.d(s,"updateProfile",(function(){return ge})),n.d(s,"checkUsername",(function(){return he})),n.d(s,"updateUsername",(function(){return me})),n.d(s,"fetchBlockedContacts",(function(){return ve})),n.d(s,"blockContact",(function(){return Ae})),n.d(s,"unblockContact",(function(){return Ie})),n.d(s,"updateProfilePhoto",(function(){return ye})),n.d(s,"uploadProfilePhoto",(function(){return be})),n.d(s,"fetchWallpapers",(function(){return _e})),n.d(s,"uploadWallpaper",(function(){return we})),n.d(s,"fetchAuthorizations",(function(){return Pe})),n.d(s,"terminateAuthorization",(function(){return Ce})),n.d(s,"terminateAllAuthorizations",(function(){return Se})),n.d(s,"fetchNotificationExceptions",(function(){return Me})),n.d(s,"fetchNotificationSettings",(function(){return ke})),n.d(s,"updateContactSignUpNotification",(function(){return Ee})),n.d(s,"updateNotificationSettings",(function(){return Re})),n.d(s,"fetchLanguages",(function(){return Ue})),n.d(s,"fetchLangPack",(function(){return Oe})),n.d(s,"fetchPrivacySettings",(function(){return Te})),n.d(s,"setPrivacySettings",(function(){return xe})),n.d(s,"registerDevice",(function(){return De})),n.d(s,"unregisterDevice",(function(){return Be})),n.d(s,"getPasswordInfo",(function(){return ne})),n.d(s,"checkPassword",(function(){return ie})),n.d(s,"clearPassword",(function(){return ae})),n.d(s,"updatePassword",(function(){return re})),n.d(s,"updateRecoveryEmail",(function(){return oe})),n.d(s,"provideRecoveryEmailCode",(function(){return ce})),n.d(s,"answerCallbackButton",(function(){return Ne.a})),n.d(s,"validateRequestedInfo",(function(){return Fe})),n.d(s,"sendPaymentForm",(function(){return Le})),n.d(s,"getPaymentForm",(function(){return qe})),n.d(s,"getReceipt",(function(){return He}));var i=n(4),a=n(30),r=n(26),o=n(17),c=n(7),u=n(10),d=n(15),l=n.n(d),f=n(0),p=n(1),g=n(2),h=n(13),m=n(3),y=n(19),b=n(5),_=n(16);let w;async function v({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;const s=await Object(p.g)(new f.Api.users.GetFullUser({id:n}));if(!s)return;const i=Object(h.b)(s);w({"@type":"updateUser",id:e,user:{fullInfo:i.fullInfo}})}async function A(){const e=await Object(p.g)(new f.Api.help.GetNearestDc);return e?e.country:void 0}async function I({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetTopPeers({hash:e,correspondents:!0}));if(!(t instanceof f.Api.contacts.TopPeers))return;const n=t.users.map(h.a).filter(e=>!!e&&!e.isSelf),s=n.map(({id:e})=>e);return{hash:Object(g.q)(s),ids:s,users:n}}async function P({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetContacts({hash:e}));if(t&&!(t instanceof f.Api.contacts.ContactsNotModified))return t.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),{hash:Object(g.q)([t.savedCount,...t.contacts.map(({userId:e})=>e)]),users:t.users.map(h.a).filter(Boolean),chats:t.users.map(e=>Object(m.d)(e)).filter(Boolean)}}async function C({users:e}){const t=await Object(p.g)(new f.Api.users.GetUsers({id:e.map(({id:e,accessHash:t})=>Object(g.i)(e,t))}));if(t&&t.length)return t.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),t.map(h.a).filter(Boolean)}function S({phone:e,firstName:t,lastName:n}){return Object(p.g)(new f.Api.contacts.ImportContacts({contacts:[Object(g.e)({phone:e||"",firstName:t||"",lastName:n||""})]}))}async function M({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;await Object(p.g)(new f.Api.contacts.DeleteContacts({id:[n]}))&&w({"@type":"deleteUser",id:e})}async function k(e,t){if(e){const{id:t,accessHash:n}=e,s=await Object(p.g)(new f.Api.photos.GetUserPhotos({userId:Object(g.g)(t,n),limit:i.u,offset:0,maxId:l()("0")}));if(!s)return;return function(e){e.photos.forEach(_.b)}(s),{photos:s.photos.filter(e=>e instanceof f.Api.Photo).map(y.a)}}const n=await Object(u.u)({chatOrUser:t,type:"profilePhoto",limit:i.u});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map(e=>e.content.action.photo).filter(Boolean),users:a}}var E=n(22),R=n(9);let U,O,T;async function D({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetAllStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.AllStickersNotModified))return t.sets.forEach(e=>{e.thumbs&&e.thumbs.length&&(b.a.stickerSets[String(e.id)]=e)}),{hash:t.hash,sets:t.sets.map(E.b)}}async function B({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetRecentStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.RecentStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function x({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFavedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FavedStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function j({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFeaturedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FeaturedStickersNotModified))return{hash:t.hash,sets:t.sets.map(E.c)}}async function N({sticker:e,unfave:t}){const n=new f.Api.messages.FaveSticker({id:Object(g.f)(e),unfave:t});await Object(p.g)(n)&&U({"@type":"updateFavoriteStickers"})}async function V({stickerSetId:e,accessHash:t}){const n=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:Object(g.l)(e,t)}));var s;if(n)return{set:Object(E.b)(n.set),stickers:$(n.documents),packs:(s=n.packs,s.reduce((e,{emoticon:t,documents:n})=>(e[t]=n.map(e=>Object(E.a)(b.a.documents[String(e)])).filter(Boolean),e),{}))}}async function F(){const e=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:new f.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:Object(E.b)(e.set),stickers:$(e.documents)}}async function L({query:e,hash:t}){const n=await Object(p.g)(new f.Api.messages.SearchStickerSets({q:e,hash:t}));if(n&&!(n instanceof f.Api.messages.FoundStickerSetsNotModified))return{hash:n.hash,sets:n.sets.map(E.c)}}async function q({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetSavedGifs({hash:e}));if(t&&!(t instanceof f.Api.messages.SavedGifsNotModified))return{hash:t.hash,gifs:J(t.gifs)}}async function H({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.InstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function K({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.UninstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function z({query:e,offset:t=""}){if(!O){const e=await Object(p.g)(new f.Api.help.GetConfig);if(!e)return;const t=await Object(p.g)(new f.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof f.Api.User))return;O=new f.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await Object(p.g)(new f.Api.messages.GetInlineBotResults({bot:O,peer:new f.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map(e=>{if(e instanceof f.Api.BotInlineMediaResult)return e.document}).filter(Boolean);return{nextOffset:n.nextOffset,gifs:J(s)}}async function G({emoji:e,hash:t=0}){const n=await Object(p.g)(new f.Api.messages.GetStickers({emoticon:e,hash:t}));if(n&&!(n instanceof f.Api.messages.StickersNotModified))return{stickers:$(n.stickers),hash:n.hash}}async function W({language:e,fromVersion:t}){const n=await Object(p.g)(new f.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce((e,t)=>(e[t.keyword]=t.emoticons,e),{})}}function $(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(E.a)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}function J(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(R.m)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}async function Z({username:e}){try{return await Object(p.g)(new f.Api.channels.CheckUsername({channel:new f.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Y({chat:e,username:t}){await Object(p.g)(new f.Api.channels.UpdateUsername({channel:Object(g.g)(e.id,e.accessHash),username:t}))&&T({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Q({chat:e}){const t=await Object(p.g)(new f.Api.messages.ExportChatInvite({peer:Object(g.i)(e.id,e.accessHash)}));t&&t instanceof f.Api.ChatInviteExported&&T({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const X={EMAIL_UNCONFIRMED:"Email unconfirmed",EMAIL_HASH_EXPIRED:"Email hash expired",NEW_SALT_INVALID:"The new salt is invalid",NEW_SETTINGS_INVALID:"The new password settings are invalid",CODE_INVALID:"Invalid Code",PASSWORD_HASH_INVALID:"Invalid Password"},ee={};let te;async function ne(){const e=await Object(p.g)(new f.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function se(e){return te({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise((e,t)=>{ee.resolve=e,ee.reject=t})}async function ie(e){try{return await Object(p.h)({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return ue(e),!1}}async function ae(e){try{return await Object(p.h)({currentPassword:e}),!0}catch(e){return ue(e),!1}}async function re(e,t,n,s){try{return await Object(p.h)({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}async function oe(e,t){try{return await Object(p.h)({currentPassword:e,newPassword:e,email:t,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}function ce(e){ee.resolve(e)}function ue(e){let t;if(e instanceof f.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?n+" hours":"an hour")}else t=X[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),te({"@type":"updateTwoFaError",message:t})}var de=n(24),le=n(18),fe=n(14);const pe=["ar","fa"];function ge({firstName:e,lastName:t,about:n}){return Object(p.g)(new f.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function he(e){return Object(p.g)(new f.Api.account.CheckUsername({username:e}))}function me(e){return Object(p.g)(new f.Api.account.UpdateUsername({username:e}))}async function ye(e){const t=await Object(p.i)(e);return Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function be(e){const t=await Object(p.i)(e);await Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function _e(e){const t=await Object(p.g)(new f.Api.account.GetWallPapers({hash:e}));if(!t||t instanceof f.Api.account.WallPapersNotModified)return;const n=t.wallpapers.filter(e=>e instanceof f.Api.WallPaper&&e.document instanceof f.Api.Document&&(!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return n.forEach(e=>{b.a.documents[String(e.document.id)]=e.document}),{hash:t.hash,wallpapers:n.map(de.b).filter(Boolean)}}async function we(e){const t=await Object(p.i)(e),n=await Object(p.g)(new f.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new f.Api.WallPaperSettings}));if(!(n&&n instanceof f.Api.WallPaper))return;const s=Object(de.b)(n);return s?(b.a.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function ve(){const e=await Object(p.g)(new f.Api.contacts.GetBlocked({limit:i.f}));if(e)return je(e),{users:e.users.map(h.a).filter(Boolean),chats:e.chats.map(e=>Object(m.d)(e,void 0,!0)).filter(Boolean),blockedIds:e.blocked.map(e=>Object(m.j)(e.peerId)),totalCount:e instanceof f.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function Ae(e){return Object(p.g)(new f.Api.contacts.Block({id:Object(g.o)(e)}))}function Ie(e,t){return Object(p.g)(new f.Api.contacts.Unblock({id:Object(g.i)(e,t)}))}async function Pe(){const e=await Object(p.g)(new f.Api.account.GetAuthorizations);if(e)return e.authorizations.map(de.a)}function Ce(e){return Object(p.g)(new f.Api.account.ResetAuthorization({hash:l()(e)}))}function Se(){return Object(p.g)(new f.Api.auth.ResetAuthorizations)}async function Me(){const e=await Object(p.g)(new f.Api.account.GetNotifyExceptions({compareSound:!0}),!0);(e instanceof f.Api.Updates||e instanceof f.Api.UpdatesCombined)&&je(e)}async function ke(){const[e,t,n,s]=await Promise.all([Object(p.g)(new f.Api.account.GetContactSignUpNotification),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyUsers})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyChats})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyBroadcasts}))]);if(!t||!n||!s)return!1;const{silent:i,muteUntil:a,showPreviews:r}=t,{silent:o,muteUntil:c,showPreviews:u}=n,{silent:d,muteUntil:l,showPreviews:g}=s;return{hasContactJoinedNotifications:!e,hasPrivateChatsNotifications:!(i||"number"==typeof a&&Date.now()<1e3*a),hasPrivateChatsMessagePreview:r,hasGroupNotifications:!(o||"number"==typeof c&&Date.now()<1e3*c),hasGroupMessagePreview:u,hasBroadcastNotifications:!(d||"number"==typeof l&&Date.now()<1e3*l),hasBroadcastMessagePreview:g}}function Ee(e){return Object(p.g)(new f.Api.account.SetContactSignUpNotification({silent:e}))}function Re(e,{isSilent:t,shouldShowPreviews:n}){let s;s="contact"===e?new f.Api.InputNotifyUsers:"group"===e?new f.Api.InputNotifyChats:new f.Api.InputNotifyBroadcasts;const i={showPreviews:n,silent:t,muteUntil:t?2**31-1:void 0};return Object(p.g)(new f.Api.account.UpdateNotifySettings({peer:s,settings:new f.Api.InputPeerNotifySettings(i)}))}async function Ue(){const e=await Object(p.g)(new f.Api.langpack.GetLanguages({langPack:i.i}));if(e)return e.map(le.b)}async function Oe({sourceLangPacks:e,langCode:t}){const n=(await Promise.all(e.map(e=>Object(p.g)(new f.Api.langpack.GetLangPack({langPack:e,langCode:pe.includes(t)?t+"-raw":t}))))).filter(Boolean).map(e=>Object(fe.a)(e.strings.map(le.b),"key"));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function Te(e){const t=Object(g.k)(e),n=await Object(p.g)(new f.Api.account.GetPrivacy({key:t}));if(n)return je(n),Object(de.d)(n.rules)}function De(e){const t=Object(p.e)().session.getAuthKey().getKey();return Object(p.g)(new f.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Be(e){return Object(p.g)(new f.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function xe(e,t){const n=Object(g.k)(e),s=[];switch(t.allowedUsers&&s.push(new f.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.allowedChats&&s.push(new f.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map(({id:e})=>-e)})),t.blockedUsers&&s.push(new f.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.blockedChats&&s.push(new f.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map(({id:e})=>-e)})),t.visibility){case"everybody":s.push(new f.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new f.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new f.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new f.Api.InputPrivacyValueDisallowAll)}const i=await Object(p.g)(new f.Api.account.SetPrivacy({key:n,rules:s}));if(i)return je(i),Object(de.d)(i.rules)}function je(e){e.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof f.Api.Chat||e instanceof f.Api.Channel)&&(b.a.chats[e.id]=e)})}var Ne=n(72);function Ve(e){if(e)return Object.values(e).map(e=>({id:e.id,title:e.title,amount:e.prices.reduce((e,t)=>e+Number(t.amount.value),0),prices:e.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}))}))}async function Fe({messageId:e,requestInfo:t,shouldSave:n}){const s=await Object(p.g)(new f.Api.payments.ValidateRequestedInfo({msgId:e,save:n||void 0,info:Object(g.p)(t)}));if(!s)return;const{id:i,shippingOptions:a}=s;return i?{id:i,shippingOptions:Ve(a)}:void 0}function Le({messageId:e,requestedInfoId:t,shippingOptionId:n,credentials:s}){return Object(p.g)(new f.Api.payments.SendPaymentForm({msgId:e,requestedInfoId:t,shippingOptionId:n,credentials:new f.Api.InputPaymentCredentials({save:s.save,data:new f.Api.DataJSON({data:JSON.stringify(s.data)})})}),!0)}async function qe({messageId:e}){const t=await Object(p.g)(new f.Api.payments.GetPaymentForm({msgId:e}));if(t)return function(e){const{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,nativeParams:a,savedInfo:r,invoice:o}=e,{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:y}=o,b=y.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),_=a?JSON.parse(a.data):{};return{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,savedInfo:r,invoice:{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:b},nativeParams:{needCardholderName:_.need_cardholder_name,needCountry:_.need_country,needZip:_.need_zip,publishableKey:_.publishable_key}}}(t)}async function He(e){const t=await Object(p.g)(new f.Api.payments.GetPaymentReceipt({msgId:e}));if(t)return function(e){const{invoice:t,info:n,shipping:s,currency:i,totalAmount:a,credentialsTitle:r}=e,{shippingAddress:o,phone:c,name:u}=n||{},{prices:d}=t,l=d.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}));let f,p;return s&&(f=s.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),p=s.title),{currency:i,prices:l,info:{shippingAddress:o,phone:c,name:u},totalAmount:Number(a.value),credentialsTitle:r,shippingPrices:f,shippingMethod:p}}(t)}let Ke;async function ze(e,t){Ke=e,Object(r.a)(Ze),Object(o.a)(Ze),Object(c.p)(Ze),Object(u.m)(Ze),function(e){w=e}(Ze),function(e){U=e}(Ze),function(e){T=e}(Ze),function(e){te=e}(Ze),await Object(p.f)(Ze,t)}const Ge=Object(a.c)((function(e){if(!Je||e!==$e)return;const t=Je;Je=void 0,t.forEach(Ke)}));let We,$e,Je;function Ze(e){Je?Je.push(e):Je=[e],We&&!i.b.has(e["@type"])||(We=Object(a.b)(Ge,i.c,!0),$e=Math.random()),We($e)}self.onerror=e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const Ye=new Map;function Qe(e){Xe({type:"update",update:e})}function Xe(e,t){t?postMessage(e,[t]):postMessage(e)}i.g&&console.log(">>> FINISH LOAD WORKER"),onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await ze(Qe,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:a}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Xe({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ye.set(e,t),a.push(t)}const t=await function(e,...t){return s[e](...t)}(n,...a),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Xe({type:"methodResponse",messageId:e,response:t},i)}catch(t){i.g&&console.error(t),e&&Xe({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ye.delete(e);break}case"cancelProgress":{const e=Ye.get(t.messageId);e&&(e.isCanceled=!0);break}}}}]); -//# sourceMappingURL=6b9e1c477ee38548ce72.worker.js.map \ No newline at end of file diff --git a/dist/6b9e1c477ee38548ce72.worker.js.map b/dist/6b9e1c477ee38548ce72.worker.js.map deleted file mode 100644 index e979bab8..00000000 --- a/dist/6b9e1c477ee38548ce72.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/gramjs/index.js","webpack:///./src/util/cacheApi.ts","webpack:///./src/api/gramjs/methods/media.ts","webpack:///./src/api/gramjs/methods/client.ts","webpack:///./src/api/gramjs/gramjsBuilders/index.ts","webpack:///./src/api/gramjs/apiBuilders/peers.ts","webpack:///./src/api/gramjs/apiBuilders/chats.ts","webpack:///./src/config.ts","webpack:///./src/api/gramjs/localDb.ts","webpack:///./src/lib/gramjs/tl/api.js","webpack:///./src/api/gramjs/methods/chats.ts","webpack:///./src/lib/gramjs/Helpers.js","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/api/gramjs/apiBuilders/messages.ts","webpack:///./src/api/gramjs/methods/messages.ts","webpack:///./src/api/types/index.ts","webpack:///./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack:///./src/api/gramjs/apiBuilders/users.ts","webpack:///./src/util/iteratees.ts","webpack:///./node_modules/big-integer/BigInteger.js","webpack:///./src/api/gramjs/helpers.ts","webpack:///./src/api/gramjs/methods/auth.ts","webpack:///./src/api/gramjs/apiBuilders/helpers.ts","webpack:///./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack:///./src/api/gramjs/apiBuilders/common.ts","webpack:///./src/lib/gramjs/Utils.js","webpack:///./src/lib/gramjs/tl/index.js","webpack:///./src/api/gramjs/apiBuilders/symbols.ts","webpack:///./src/lib/gramjs/errors/Common.js","webpack:///./src/api/gramjs/apiBuilders/misc.ts","webpack:///./src/lib/gramjs/extensions/BinaryReader.js","webpack:///./src/api/gramjs/updater.ts","webpack:///./src/lib/gramjs/sessions/Memory.js","webpack:///./src/lib/gramjs/crypto/AuthKey.js","webpack:///./src/lib/gramjs/errors/index.js","webpack:///./src/util/schedulers.ts","webpack:///./src/lib/gramjs/Password.js","webpack:///./src/lib/gramjs/tl/core/GZIPPacked.js","webpack:///./src/util/waveform.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/gramjs/crypto/crypto.js","webpack:///./src/lib/gramjs/errors/RPCBaseErrors.js","webpack:///./src/lib/gramjs/tl/core/TLMessage.js","webpack:///./src/lib/gramjs/tl/core/MessageContainer.js","webpack:///./src/lib/gramjs/network/connection/Connection.js","webpack:///./src/lib/gramjs/sessions/StorageSession.js","webpack:///./node_modules/pako/dist/pako_inflate.js","webpack:///./src/lib/gramjs/extensions/index.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/lib/gramjs/tl/generationHelpers.js","webpack:///./node_modules/@cryptography/aes/dist/es/aes.js","webpack:///./src/lib/gramjs/extensions/Logger.js","webpack:///./src/lib/gramjs/errors/RPCErrorList.js","webpack:///./src/lib/gramjs/sessions/Abstract.js","webpack:///./src/lib/gramjs/tl/AllTLObjects.js","webpack:///./src/lib/gramjs/network/MTProtoSender.js","webpack:///./src/lib/gramjs/network/MTProtoPlainSender.js","webpack:///./src/lib/gramjs/network/MTProtoState.js","webpack:///./src/lib/gramjs/crypto/IGE.js","webpack:///./src/lib/gramjs/tl/core/index.js","webpack:///./src/lib/gramjs/tl/core/RPCResult.js","webpack:///./src/lib/gramjs/network/Authenticator.js","webpack:///./src/lib/gramjs/extensions/MessagePacker.js","webpack:///./src/lib/gramjs/extensions/BinaryWriter.js","webpack:///./src/lib/gramjs/network/index.js","webpack:///./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack:///./src/lib/gramjs/extensions/AsyncQueue.js","webpack:///./src/lib/gramjs/network/connection/TCPAbridged.js","webpack:///./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/api/gramjs/methods/bots.ts","webpack:///./node_modules/base64-js/index.js","webpack:///./node_modules/ieee754/index.js","webpack:///./node_modules/isarray/index.js","webpack:///(webpack)/buildin/module.js","webpack:///./src/lib/gramjs/crypto/converters.ts","webpack:///./src/lib/gramjs/crypto/words.ts","webpack:///./src/lib/gramjs/tl/apiTl.js","webpack:///./src/lib/gramjs/tl/schemaTl.js","webpack:///./src/lib/gramjs/client/TelegramClient.js","webpack:///./node_modules/os-browserify/browser.js","webpack:///./node_modules/process/browser.js","webpack:///./src/lib/gramjs/crypto/Factorizator.js","webpack:///./src/lib/gramjs/crypto/RSA.js","webpack:///./src/lib/gramjs/network/RequestState.js","webpack:///./src/lib/gramjs/network/connection/index.js","webpack:///./node_modules/async-mutex/lib/index.js","webpack:///./node_modules/async-mutex/lib/Mutex.js","webpack:///./node_modules/websocket/lib/browser.js","webpack:///./node_modules/websocket/lib/version.js","webpack:///./src/lib/gramjs/crypto/CTR.js","webpack:///./src/lib/gramjs/client/auth.ts","webpack:///./src/lib/gramjs/client/downloadFile.ts","webpack:///./src/lib/gramjs/client/uploadFile.ts","webpack:///./src/lib/gramjs/client/2fa.ts","webpack:///./src/lib/gramjs/Version.js","webpack:///./src/lib/gramjs/events/index.js","webpack:///./src/lib/gramjs/events/Raw.js","webpack:///./src/lib/gramjs/events/common.js","webpack:///./src/lib/gramjs/sessions/index.js","webpack:///./src/lib/gramjs/sessions/StringSession.js","webpack:///./src/lib/gramjs/sessions/CacheApiSession.js","webpack:///./src/lib/gramjs/sessions/LocalStorageSession.js","webpack:///./src/lib/gramjs/sessions/IdbSession.js","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/lib/gramjs/sessions/CallbackSession.js","webpack:///./src/api/gramjs/methods/users.ts","webpack:///./src/api/gramjs/methods/symbols.ts","webpack:///./src/api/gramjs/methods/management.ts","webpack:///./src/api/gramjs/methods/twoFaSettings.ts","webpack:///./src/api/gramjs/methods/settings.ts","webpack:///./src/api/gramjs/apiBuilders/payments.ts","webpack:///./src/api/gramjs/methods/payments.ts","webpack:///./src/api/gramjs/provider.ts","webpack:///./src/api/gramjs/worker/worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Api","require","TelegramClient","connection","tl","version","events","utils","errors","sessions","extensions","helpers","cacheApi","self","caches","Type","async","fetch","cacheName","type","request","Request","cache","open","response","match","Text","text","Blob","blob","substr","contentType","headers","Json","json","err","console","warn","save","data","cacheData","JSON","stringify","Response","put","clear","delete","downloadMedia","url","mediaFormat","start","end","client","isConnected","onProgress","mimeType","fullSize","mediaMatch","arrayBuffer","Promise","reject","Error","entityType","entityId","sizeType","replace","undefined","entity","getEntityTypeById","Number","Math","abs","localDb","chats","users","messages","documents","photos","stickerSets","includes","ApiMediaFormat","Stream","acceptsBuffer","progressCallback","workers","DOWNLOAD_WORKERS","GramJs","Message","message","media","MessageMediaPhoto","MessageMediaDocument","document","Document","attributes","some","a","DocumentAttributeSticker","getMessageMediaMimeType","size","Photo","downloadStickerSetThumb","Lottie","getMimeType","downloadProfilePhoto","download","parsed","DataUri","blobToDataUri","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","MEDIA_CACHE_MAX_BYTES","MEDIA_CACHE_DISABLED","startsWith","MEDIA_CACHE_NAME_AVATARS","MEDIA_CACHE_NAME","prepared","mediaData","URL","createObjectURL","prepareMedia","fallbackMimeType","length","subarray","reduce","result","byte","toString","GramJsLogger","setLevel","DEBUG_GRAMJS","gramJsUpdateEventBuilder","build","update","onUpdate","init","_onUpdate","sessionData","DEBUG","log","CallbackSession","onSessionUpdate","process","deviceModel","navigator","userAgent","appVersion","APP_VERSION","useWSS","additionalDcsDisabled","IS_TEST","addEventHandler","handleGramJsUpdate","updater","phoneNumber","onRequestPhoneNumber","phoneCode","onRequestCode","password","onRequestPassword","firstAndLastNames","onRequestRegistration","qrCode","onRequestQrCode","onError","onAuthError","onAuthReady","fetchCurrentUser","destroy","invokeRequest","auth","LogOut","disconnect","getClient","UpdateConnectionState","state","connected","UpdatesTooLong","GetFullUser","id","InputUserSelf","connectionState","handleTerminatedSession","shouldHandleUpdates","shouldThrow","className","invoke","updatesContainer","Updates","UpdatesCombined","updates","entities","forEach","_entities","injectUpdateEntities","error","isSlowMode","SendMessage","SendMedia","SendMultiMedia","dispatchErrorUpdate","args","downloadMediaWithClient","uploadFile","file","UPLOAD_WORKERS","updateTwoFaSettings","params","userFull","user","User","currentUser","buildApiUserFromFull","setMessageBuilderCurrentUserId","onCurrentUserUpdate","chatOrUserId","buildPeer","PeerUser","userId","PeerChannel","channelId","PeerChat","chatId","buildInputPeer","accessHash","InputPeerUser","BigInt","InputPeerChannel","InputPeerChat","buildInputPeerFromLocalDb","buildInputEntity","InputUser","InputChannel","buildInputStickerSet","InputStickerSetID","buildInputDocument","InputDocument","pick","buildInputMediaDocument","inputDocument","InputMediaDocument","buildInputPoll","pollParams","randomId","summary","quiz","poll","Poll","publicVoters","isPublic","question","answers","map","option","PollAnswer","Buffer","from","multipleChoice","InputMediaPoll","correctAnswers","solution","solutionEntities","buildMtpMessageEntity","buildFilterFromApiFolder","folder","emoticon","contacts","nonContacts","groups","channels","bots","excludeArchived","excludeMuted","excludeRead","pinnedChatIds","includedChatIds","excludedChatIds","pinnedPeers","filter","Boolean","includePeers","excludePeers","DialogFilter","title","broadcasts","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","fromId","offset","ApiMessageEntityTypes","Bold","MessageEntityBold","Italic","MessageEntityItalic","Underline","MessageEntityUnderline","Strike","MessageEntityStrike","Code","MessageEntityCode","Pre","MessageEntityPre","language","Blockquote","MessageEntityBlockquote","TextUrl","MessageEntityTextUrl","Url","MessageEntityUrl","Hashtag","MessageEntityHashtag","MentionName","InputMessageEntityMentionName","MessageEntityUnknown","calculateResultHash","ids","hash","isMessageWithMedia","MessageMediaWebPage","webpage","WebPage","photo","isServiceMessageWithMedia","action","buildChatPhotoForLocalDb","PhotoEmpty","ChatPhotoEmpty","dcId","photoId","ChatPhoto","buildInputContact","phone","firstName","lastName","InputPhoneContact","clientId","buildChatBannedRights","bannedRights","untilDate","ChatBannedRights","buildChatAdminRights","adminRights","ChatAdminRights","buildShippingInfo","info","shippingAddress","PaymentRequestedInfo","PostAddress","buildInputPrivacyKey","privacyKey","InputPrivacyKeyPhoneNumber","InputPrivacyKeyStatusTimestamp","InputPrivacyKeyProfilePhoto","InputPrivacyKeyForwards","InputPrivacyKeyChatInvite","isPeerUser","peer","isPeerChat","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","String","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","Channel","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","Chat","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","Date","now","getApiChatIdFromMtpPeer","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","omitVirtualClassFields","currentUserBannedRights","defaultBannedRights","ChatForbidden","ChannelForbidden","isRestricted","restrictionReason","restricted","buildApiChatRestrictionReason","isNotJoined","left","kicked","reason","platform","migratedTo","InputChannelEmpty","restrictionReasons","targetReason","find","buildApiChatFromPreview","preview","withForbidden","getUserName","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","UserEmpty","ChatEmpty","megagroup","getPeerKey","buildChatMember","member","ChannelParticipantBanned","ChannelParticipantLeft","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","ChannelParticipantAdmin","ChatParticipantAdmin","isAdmin","ChannelParticipantCreator","ChatParticipantCreator","isOwner","buildChatMembers","participants","ChatParticipants","ChannelParticipants","buildChatTypingStatus","SendMessageCancelAction","SendMessageTypingAction","SendMessageRecordVideoAction","SendMessageUploadVideoAction","SendMessageRecordAudioAction","SendMessageUploadAudioAction","SendMessageUploadPhotoAction","SendMessageUploadDocumentAction","SendMessageGeoLocationAction","SendMessageChooseContactAction","SendMessageGamePlayAction","SendMessageRecordRoundAction","SendMessageUploadRoundAction","UpdateUserTyping","timestamp","buildApiChatFolder","pickTruthy","buildApiChatFolderFromSuggested","description","API_UPDATE_THROTTLE","API_THROTTLE_RESET_UPDATES","Set","MEMBERS_LOAD_SLICE","window","innerHeight","PINNED_MESSAGES_LIMIT","BLOCKED_LIST_LIMIT","PROFILE_PHOTOS_LIMIT","LOCAL_MESSAGE_ID_BASE","MEMOJI_STICKER_ID","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","DELETED_COMMENTS_CHANNEL_ID","DEFAULT_LANG_PACK","localMessages","parseTl","serializeBytes","serializeDate","toSignedLittleBuffer","tlContent","schemeContent","CACHING_SUPPORTED","localStorage","extractParams","fileContent","f","constructors","functions","isFunction","push","argToBytes","x","alloc","writeInt32LE","writeDoubleLE","getBytes","getArgFromReader","reader","arg","isVector","useVectorId","readInt","temp","len","flagIndicator","readLong","readLargeInt","readDouble","tgReadString","tgReadBool","tgReadBytes","tgReadDate","skipConstructorId","tgReadObject","createClasses","classesType","classes","classParams","constructorId","subclassOfId","argsConfig","namespace","fullName","join","VirtualClass","constructor","keys","argName","this","isFlag","flags","flagIndex","idForBytes","CONSTRUCTOR_ID","writeUInt32LE","buffers","concat","values","flagCalculate","boxed","charAt","indexOf","toUpperCase","shift","readResult","definitions","fromCache","jsonCache","getItem","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","requests","loadFromTlSchemas","setItem","obj1","obj2","assign","mergeWithNamespaces","buildApiFromTlSchema","fetchChats","limit","offsetDate","archived","withPinned","GetDialogs","offsetPeer","InputPeerEmpty","excludePinned","resultPinned","GetPinnedDialogs","DialogsNotModified","updateLocalDb","lastMessagesByChatId","buildCollectionByKey","buildApiMessage","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","Dialog","chat","lastMessage","pinned","draft","formattedText","replyingToId","buildMessageDraft","buildApiUser","chatIds","totalChatCount","DialogsSlice","count","fetchFullChat","GetFullChannel","channel","fullChat","ChannelFull","about","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","inviteLink","ChatInviteExported","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","fullInfo","slowMode","seconds","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","GetFullChat","ChatFull","getFullChatInfo","searchChats","query","Search","q","localPeerIds","myResults","allChats","allUsers","isSelf","localChats","localUsers","u","globalChats","globalUsers","fetchChat","mtpUser","GetUsers","help","GetSupport","requestChatUpdate","GetPeerDialogs","peers","InputDialogPeer","saveDraft","replyToMsgId","SaveDraft","clearDraft","updateChatMutedState","account","UpdateNotifySettings","InputNotifyPeer","settings","InputPeerNotifySettings","createChannel","CreateChannel","broadcast","newChannel","InviteToChannel","joinChannel","JoinChannel","leaveChannel","LeaveChannel","deleteChannel","DeleteChannel","createGroupChat","CreateChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","EditPhoto","InputChatUploadedPhoto","EditChatPhoto","toggleChatPinned","shouldBePinned","ToggleDialogPin","isPinned","toggleChatArchived","folders","EditPeerFolders","folderPeers","InputFolderPeer","fetchChatFolders","GetDialogFilters","byId","orderedIds","fetchRecommendedChatFolders","results","GetSuggestedDialogFilters","editChatFolder","folderUpdate","UpdateDialogFilter","deleteChatFolder","isActionSuccessful","recommendedChatFolders","toggleDialogUnread","MarkDialogUnread","unread","getChatByUsername","ResolveUsername","togglePreHistoryHidden","isEnabled","TogglePreHistoryHidden","enabled","updateChatDefaultBannedRights","EditChatDefaultBannedRights","updateChatMemberBannedRights","participant","EditBanned","updateChatAdmin","EditAdmin","updateChatTitle","EditTitle","EditChatTitle","updateChatAbout","EditChatAbout","toggleSignatures","ToggleSignatures","memberFilter","ChannelParticipantsKicked","ChannelParticipantsAdmins","ChannelParticipantsRecent","GetParticipants","ChannelParticipantsNotModified","fetchGroupsForDiscussion","GetGroupsForDiscussion","setDiscussionGroup","SetDiscussionGroup","group","migrateChat","MigrateChat","openChatByInvite","CheckChatInvite","ChatInvite","ImportChatInvite","store","addMessageToLocalDb","crypto","little","signed","randBuffer","bytesNumber","reverse","bigInt","floor","subtract","pow","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","ceil","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","generateRandomLong","mod","crc32","buf","k","makeCRCTable","isBuffer","crc","index","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","all","slice","iv","sha256","bigIntMod","remainder","add","modExp","b","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","max","random","sleep","ms","resolve","setTimeout","getByteArray","integer","bits","byteLength","convertToLittle","correct","writeUInt32BE","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","currentUserId","localMessageCounter","_currentUserId","mtpMessage","resolveMessageApiChatId","MessageService","buildApiMessageWithChatId","buildApiMessageFromShort","out","buildApiMessageFromShortChat","buildApiMessageFromNotification","notification","currentDate","localId","content","buildMessageMediaContent","sticker","contact","buildMessageTextContent","inboxDate","isOutgoing","isChatWithSelf","post","fwdFrom","senderId","isChannelPost","MessageActionEmpty","targetUserId","targetChatId","MessageActionChatCreate","MessageActionChatEditTitle","MessageActionChatEditPhoto","MessageActionChatDeletePhoto","MessageActionChatAddUser","MessageActionChatDeleteUser","MessageActionChatJoinedByLink","MessageActionChannelCreate","MessageActionChatMigrateTo","MessageActionChannelMigrateFrom","MessageActionPinMessage","MessageActionHistoryClear","MessageActionPhoneCall","video","duration","mins","round","MessageActionContactSignUp","MessageActionPaymentSent","currencySign","amount","totalAmount","toFixed","MessageActionGroupCall","addPhotoToLocalDb","buildApiPhoto","buildAction","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","messageId","replyMarkup","ReplyKeyboardMarkup","ReplyInlineMarkup","markup","rows","buttons","button","KeyboardButton","KeyboardButtonUrl","KeyboardButtonCallback","KeyboardButtonRequestPoll","KeyboardButtonBuy","MessageMediaInvoice","receiptMsgId","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","ReplyKeyboardHide","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","DraftMessageEmpty","buildStickerFromDocument","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","attr","DocumentAttributeAudio","voice","fileName","getFilenameFromDocument","buildAudio","waveform","Array","buildVoice","buildApiDocument","buildDocumentFromMedia","MessageMediaContact","buildContact","MessageMediaPoll","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","buildInvoice","buildInvoiceFromMedia","DocumentEmpty","thumbs","videoAttr","DocumentAttributeVideo","gifAttr","DocumentAttributeAnimated","w","width","h","height","supportsStreaming","roundMessage","isRound","isGif","thumbnail","buildApiThumbnailFromStripped","pollResults","rawAnswers","answer","fromCharCode","buildPollResults","rawResults","totalVoters","recentVoters","recentVoterIds","chosen","voters","isChosen","isCorrect","votersCount","sizes","PhotoSize","buildApiPhotoSize","hasDocument","defaultBase","filenameAttribute","DocumentAttributeFilename","extension","split","buildLocalMessage","replyingTo","attachment","gif","scheduledAt","filename","blobUrl","previewBlobUrl","quick","dataUri","inputWaveform","interpolateArray","buildUploadingMedia","isChannel","buildNewPoll","isScheduled","buildForwardedMessage","toChat","isAudio","asIncomingInChatWithSelf","sendingState","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","fetchMessages","pagination","RequestClass","MAIN_THREAD_ID","GetHistory","GetReplies","msgId","MessagesNotModified","threadInfos","fetchMessage","GetMessages","InputMessageID","MessageEmpty","MESSAGE_DELETED","queue","sendMessage","isSilent","noWebPage","localMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","UploadMedia","fileReference","InputMediaPhoto","InputPhoto","fetchInputMedia","InputSingleMedia","multiMedia","scheduleDate","sendGroupedMedia","noWebpage","editMessage","messageUpdate","mtpEntities","EditMessage","rescheduleMessage","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","InputMediaUploadedPhoto","InputMediaUploadedDocument","pinMessage","isUnpin","isOneSide","UpdatePinnedMessage","unpin","pmOneside","unpinAllMessages","UnpinAllMessages","deleteMessages","messageIds","shouldDeleteForAll","DeleteMessages","revoke","deleteScheduledMessages","DeleteScheduledMessages","deleteHistory","DeleteHistory","just_clear","markMessageListRead","ReadHistory","ReadDiscussion","requestThreadInfoUpdate","markMessagesRead","ReadMessageContents","topMessageResult","repliesResult","GetDiscussionMessage","offsetId","addOffset","discussionChatId","topMessageId","ChannelMessages","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","InputMessagesFilterPhotoVideo","InputMessagesFilterDocument","InputMessagesFilterUrl","InputMessagesFilterMusic","InputMessagesFilterVoice","InputMessagesFilterChatPhotos","InputMessagesFilterEmpty","topMsgId","nextOffsetId","totalCount","MessagesSlice","searchMessagesGlobal","offsetRate","SearchGlobal","nextRate","fetchWebPagePreview","GetWebPagePreview","sendPollVote","options","SendVote","loadPollOptionResults","shouldResetVoters","GetPollVotes","votes","vote","nextOffset","forwardMessages","fromChat","randomIds","ForwardMessages","fromPeer","toPeer","findFirstMessageIdAfterDate","fetchScheduledHistory","GetScheduledHistory","sendScheduledMessages","SendScheduledMessages","fetchMessageLink","ExportMessageLink","grouped","thread","fetchPinnedMessages","InputMessagesFilterPinned","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","write","fromString","obj","checked","copy","val","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parseInt","utf8Write","blitBuffer","asciiWrite","str","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","apply","decodeCodePointsArray","SlowBuffer","INSPECT_MAX_BYTES","global","foo","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","y","list","pos","swap16","swap32","swap64","arguments","equals","inspect","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","mtpUserFull","commonChatsCount","pinnedMsgId","botInfo","bio","pinnedMessageId","botDescription","UserProfilePhoto","mutualContact","isContact","buildApiUserType","status","buildApiUserStatus","bot","deleted","mtpStatus","UserStatusEmpty","UserStatusOnline","expires","UserStatusOffline","wasOnline","UserStatusRecently","UserStatusLastWeek","collection","byKey","BASE","MAX_INT","MAX_INT_ARR","smallToArray","supportsNativeBigInt","Integer","v","radix","alphabet","caseSensitive","parseBase","parseValue","BigInteger","sign","isSmall","SmallInteger","NativeBigInt","isPrecise","arrayToSmall","compareAbs","createArray","truncate","sum","l_a","l_b","carry","base","addAny","addSmall","difference","a_l","b_l","borrow","subtractSmall","multiplyLong","product","a_i","multiplySmall","shiftLeft","multiplySmallAndArray","square","divModSmall","lambda","divisor","quotient","divModAny","negate","comparison","quotientDigit","divisorMostSignificantDigit","divMod1","guess","xlen","highx","highy","check","part","unshift","divMod2","qSign","mSign","isBasicPrime","isUnit","isEven","isDivisibleBy","millerRabinTest","nPrev","prev","next","modPow","plus","subtractAny","minus","small","l1","l2","multiplyKaratsuba","ac","bd","abcd","times","_multiplyBySmall","divmod","over","_0","_1","_2","isNegative","exp","isZero","modInv","isPositive","isOdd","compareTo","notEquals","neq","gt","lt","greaterOrEquals","geq","lesserOrEquals","leq","isPrime","strict","logN","toJSNumber","isProbablePrime","iterations","rng","randBetween","lastT","lastR","newT","newR","powersOfTwo","powers2Length","highestPower2","shift_isSmall","bitwise","fn","xSign","ySign","xRem","not","yRem","xDigit","yDigit","xDivMod","yDivMod","remQuo","or","xor","roughLOB","gcd","integerLogarithm","tmp","absBase","alphabetValues","digits","parseBaseFromArray","toBase","valueOf","neg","digit","toBaseString","parseStringValue","decimalPlace","parseNumberValue","toArray","minusOne","lcm","isInstance","usedRNG","low","range","top","fromArray","messageFullId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","buildAuthStateUpdate","isCodeViaApp","hint","token","btoa","FloodWaitError","hours","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","bytesToDataUri","shouldOmitPrefix","instance","SUBCLASS_OF_ID","classType","rest","pathBytesToSvg","path","num","buildPath","DEFAULT_THUMB_SIZE","thumb","PhotoStrippedSize","realSizes","strippedPhotoToJpg","buildApiThumbnailFromCached","photoSize","buildApiThumbnailFromPath","sizeAttribute","PhotoSizeProgressive","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","InputPeerSelf","UserFull","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","ipAddress","port","api","stickerAttribute","DocumentAttributeImageSize","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","PhotoCachedSize","pathThumb","PhotoPathSize","stickerSetId","stickerSetAccessHash","buildStickerSet","animated","installedDate","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","StickerSetMultiCovered","covers","cover","coverSticker","ReadCancelledError","super","TypeNotFoundError","invalidConstructorId","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","SecurityError","BadMessageError","errorMessage","ErrorMessages","16","17","18","19","20","32","33","34","35","48","64","CdnFileTamperedError","buildApiWallpaper","wallpaper","WallPaperNoFile","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyKey","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","PrivacyValueAllowAll","PrivacyValueAllowContacts","PrivacyValueDisallowContacts","PrivacyValueDisallowAll","PrivacyValueAllowUsers","PrivacyValueDisallowUsers","PrivacyValueAllowChatParticipants","PrivacyValueDisallowChatParticipants","coreObjects","tlobjects","stream","_last","readByte","readFloat","getBuffer","padding","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","sentMessageIds","originRequest","disconnected","broken","UpdateNewMessage","UpdateNewScheduledMessage","UpdateNewChannelMessage","UpdateShortChatMessage","UpdateShortMessage","UpdateServiceNotification","has","localDbChatId","newProfilePhoto","UpdateEditMessage","UpdateEditChannelMessage","UpdateDeleteMessages","UpdateDeleteScheduledMessages","UpdateDeleteChannelMessages","existingIds","missingIds","profilePhotoIds","UpdateMessageID","UpdateShortSentMessage","newContent","isAlreadySent","UpdateReadMessagesContents","UpdateChannelReadMessagesContents","UpdateMessagePoll","pollId","apiPoll","pollUpdate","UpdateMessagePollVote","UpdateChannelMessageViews","UpdateReadHistoryInbox","stillUnreadCount","UpdateReadHistoryOutbox","UpdateReadChannelInbox","UpdateReadChannelOutbox","UpdateDialogPinned","DialogPeer","UpdatePinnedDialogs","order","dp","UpdateFolderPeers","folderPeer","UpdateDialogFilterOrder","UpdateChatParticipants","replacedMembers","UpdateChatParticipantAdd","addedMember","UpdateChatParticipantDelete","deletedMemberId","UpdatePinnedMessages","UpdatePinnedChannelMessages","NotifyPeer","showPreviews","sound","shouldShowPreviews","UpdateChatUserTyping","typingStatus","UpdateChannelUserTyping","UpdateChannel","UpdateDialogUnreadMark","UpdateChatDefaultBannedRights","UpdateUserStatus","UpdateUserName","updatedUser","UpdateUserPhoto","UpdateUserPhone","UpdatePeerSettings","peerType","UpdatePeerBlocked","isBlocked","blocked","UpdatePrivacy","UpdateContactsReset","UpdateFavedStickers","Session","_serverAddress","_dcId","_port","_takeoutId","_updateStates","_authKey","setDC","serverAddress","BinaryReader","AuthKey","_key","_hash","auxHash","keyId","getKey","shaData","other","RPCError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","capture","throttle","shouldRunFirst","interval","isPending","_args","setInterval","clearInterval","throttleWithTickEnd","throttleWith","onTickEnd","schedulerFn","waiting","cb","then","pause","checkPrimeAndGood","primeBytes","g","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","computeHash","algo","salt1","salt2","salt","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","GZIPPacked","contentRelated","gzipped","toBytes","input","gzip","ungzip","fitCount","peak","newData","springFactor","leftFiller","rightFiller","idx","File","fileBits","FileReader","onload","onerror","readAsDataURL","lastModified","blobToFile","fetchBlob","AES","default","i2ab","ab2i","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","plainText","encrypt","encrypted","Hash","algorithm","subtle","createCipheriv","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","ServerError","TimedOutError","TLMessage","seqNo","MessageContainer","containerLength","before","tlMessage","PromisedWebSockets","AsyncQueue","Connection","ip","loggers","_ip","_log","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","debug","PacketCodecClass","connect","_initConn","_connect","_sendLoop","_recvLoop","pop","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","MemorySession","sessionInfo","_authKeys","_sessionString","_storageKey","_loadFromSessionString","_fetchFromCache","mainDcId","hashes","skipUpdateStorage","_updateStorage","getAuthKey","setAuthKey","authKey","getSessionData","asHex","mainDcIdStr","mainDcKey","setKey","_saveToCache","_delete","1","TYPED_OK","Uint16Array","Int32Array","_has","sources","source","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","chunk","fnUntyped","setTyped","on","Buf8","Buf16","Buf32","2","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","buf2binstring","string2buf","c2","m_pos","str_len","buf_len","binstring2buf","buf2string","c_len","utf16buf","utf8border","3","adler","s1","s2","4","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","5","table","makeTable","6","time","xflags","os","extra","extra_len","comment","hcrc","done","7","strm","_in","last","_out","beg","dmax","wsize","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","dist","from_source","output","next_in","avail_in","next_out","avail_out","lencode","distcode","lenbits","distbits","dolen","msg","dodist","sane","8","adler32","inflate_fast","inflate_table","zswap32","InflateState","wrap","havedict","total","head","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","inflateReset","inflateReset2","windowBits","inflateInit2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","flush","here_bits","here_op","here_val","last_bits","last_op","last_val","opts","hbuf","inf_leave","data_type","inflateEnd","inflateGetHeader","inflateSetDictionary","dictionary","dictLength","inflateInfo","9","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","mask","root","curr","drop","used","huff","base_index","MAXBITS","offs","extra_index","10","0","11","zlib_inflate","strings","ZStream","GZheader","Inflate","chunkSize","opt","raw","ended","inflator","_mode","next_out_utf8","tail","utf8str","allowBufError","onEnd","onData","inflateRaw","Logger","BinaryWriter","MessagePacker","Function","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","layer","methods","ignoreIds","objAll","objByName","objByType","commentIndex","followingTypes","dt","getTime","Si","T1","Uint32Array","T2","T3","T4","T5","T6","T7","T8","right","x2","x4","tEnc","tDec","xInv","computeTables","encKey","decKey","rcon","_message","a2","b2","rounds","decrypt","AES_IGE","blockSize","cipher","cipherText","prevX","prevY","yXOR","AES_IGE$1","incrementCounter","_level","level","isBrowser","browser","__nwjs","colors","messageFormat","canSend","levels","format","toISOString","color","UserMigrateError","newDc","PhoneMigrateError","SlowModeWaitError","FloodTestPhoneWaitError","FileMigrateError","NetworkMigrateError","EmailUnconfirmedError","codeLength","LAYER","MtProtoPlainSender","MTProtoState","Helpers","doAuthentication","RPCResult","RequestState","MsgsAck","upload","MsgsStateInfo","Pong","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","MTProtoSender","DEFAULT_OPTIONS","_connection","logger","_retries","retries","_delay","delay","_autoReconnect","autoReconnect","_connectTimeout","connectTimeout","_authKeyCallback","authKeyCallback","_updateCallback","updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","isMainSender","_onConnectionBreak","onConnectionBreak","_user_connected","_reconnecting","_disconnected","_send_loop_handle","_recv_loop_handle","_state","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","attempt","_disconnect","send","append","promise","plain","time_offset","timeOffset","rejectAll","ack","msgIds","batch","encryptMessageData","body","recv","reconnect","decryptMessageData","_processMessage","handler","_handleUpdate","_popStates","toPop","containerId","reqMsgId","innerMessage","pong","badSalt","badMsgId","newServerSalt","states","extend","badMsg","errorCode","updateTimeOffset","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","_getNewMsgId","IGE","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","afterId","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","encryptIge","decryptIge","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","correctMsgId","bad","old","AESIGE","ige","RpcError","innerCode","Factorizator","RSA","sender","nonce","resPQ","ReqPqMulti","ResPQ","pq","factorize","pqInnerData","PQInnerData","targetFingerprint","fingerprint","serverPublicKeyFingerprints","serverDhParams","ReqDHParams","publicKeyFingerprint","encryptedData","ServerDHParamsOk","ServerDHParamsFail","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","ServerDHInnerData","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","ClientDHInnerData","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","SetClientDHParams","nonceTypes","DhGenOk","DhGenRetry","DhGenFail","nonceNumber","calcNewNonceHash","_queue","_pendingStates","_ready","setReady","catch","finally","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","after","writeDataAsMessage","getValue","requestState","_stream","MTProtoPlainSender","ConnectionTCPFull","ConnectionTCPAbridged","ConnectionTCPObfuscated","Mutex","mutex","WebSocketClient","w3cwebsocket","closeError","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","addEventListener","onmessage","release","acquire","canGet","resolveGet","canPush","resolvePush","returned","AbridgedPacketCodec","props","obfuscateTag","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","keywords","ok","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","answerCallbackButton","GetBotCallbackAnswer","b64","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","webpackPolyfill","deprecate","paths","children","i2abLow","int","i2abBig","ab2iLow","ab","ab2iBig","isBigEndian","s2i","authFlow","checkAuthorization","downloadFile","sizeTypes","apiId","apiHash","_useIPV6","useIPV6","baseLogger","floodSleepLimit","_eventBuilders","_phoneCodeHash","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_floodWaitedRequests","_initWith","InvokeWithLayer","InitConnection","systemVersion","langCode","langPack","systemLangCode","_config","phoneCodeHashes","_borrowedSenderPromises","_additionalDcsDisabled","_initSession","_sender","GetConfig","_updateLoop","load","attempts","Ping","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","race","_lastRequest","GetState","DC","_cleanupBorrowedSender","_borrowExportedSender","senderPromise","_createExportedSender","dc","ExportAuthorization","req","ImportAuthorization","inputLocation","messageOrMedia","_downloadPhoto","_downloadDocument","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoSizeEmpty","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","_switchDC","authParams","apiCredentials","fileParams","callback","event","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","sequentialUpdates","endianness","hostname","location","loadavg","uptime","freemem","MAX_VALUE","totalmem","cpus","networkInterfaces","getNetworkInterfaces","arch","tmpdir","tmpDir","EOL","homedir","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","ys","condition","PUBLIC_KEYS","_serverKeys","keyInfo","rand","toEncrypt","Mutex_1","_pending","isLocked","_this","ticket","_dispatchNext","runExclusive","NativeWebSocket","_global","WebSocket","MozWebSocket","websocket_version","W3CWebSocket","uri","protocols","prop","me","signInUser","botAuthToken","ImportBotAuthorization","signInBot","phoneCodeHash","signInUserWithQrCode","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","SignIn","AuthorizationSignUpRequired","signInWithPassword","SignUp","AcceptTermsOfService","isScanningComplete","inputPromise","ExportLoginToken","exceptIds","LoginToken","updatePromise","UpdateLoginToken","result2","LoginTokenSuccess","authorization","Authorization","LoginTokenMigrateTo","migratedResult","ImportLoginToken","sendResult","SendCode","CodeSettings","SentCodeTypeSms","SentCodeTypeApp","resendResult","ResendCode","passwordSrpResult","GetPassword","passwordSrpCheck","computePasswordSrpCheck","CheckPassword","Foreman","maxWorkers","requestWorker","activeWorkers","deferred","_resolve","createDeferred","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","GetFile","precise","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","SaveBigFilePart","filePart","fileTotalParts","SaveFilePart","InputFileBig","InputFile","md5Checksum","isCheckPassword","currentPassword","newPassword","email","emailCodeCallback","onEmailCodeError","pwd","newAlgo","PasswordKdfAlgoUnknown","hasPassword","InputCheckPasswordEmpty","UpdatePasswordSettings","newSettings","PasswordInputSettings","newPasswordHash","newSecureSettings","ConfirmPasswordEmail","NewMessage","Raw","StopPropagation","EventBuilder","types","func","blacklistChats","resolved","Memory","StringSession","CacheApiSession","LocalStorageSession","IdbSession","decode","serverAddressLen","dcBuffer","addressBuffer","addressLengthBuffer","portBuffer","encode","StorageSession","cached","removeItem","idb","del","promisifyRequest","oncomplete","onsuccess","onabort","createStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","defaultGetStoreFunc","defaultGetStore","customStore","setMany","entries","entry","getMany","eachCursor","openCursor","continue","items","cursor","_sessionData","_callback","skipOnUpdate","fetchFullUser","userWithFullInfo","fetchNearestCountry","dcInfo","GetNearestDc","country","fetchTopUsers","topPeers","GetTopPeers","correspondents","TopPeers","fetchContactList","GetContacts","ContactsNotModified","savedCount","fetchUsers","updateContact","ImportContacts","deleteUser","DeleteContacts","fetchProfilePhotos","GetUserPhotos","inputGifBot","fetchStickerSets","allStickers","GetAllStickers","AllStickersNotModified","sets","fetchRecentStickers","GetRecentStickers","RecentStickersNotModified","stickers","processStickerResult","fetchFavoriteStickers","GetFavedStickers","FavedStickersNotModified","fetchFeaturedStickers","GetFeaturedStickers","FeaturedStickersNotModified","faveSticker","unfave","FaveSticker","fetchStickers","GetStickerSet","packs","acc","documentId","fetchAnimatedEmojis","InputStickerSetAnimatedEmoji","searchStickers","SearchStickerSets","FoundStickerSetsNotModified","fetchSavedGifs","GetSavedGifs","SavedGifsNotModified","gifs","processGifResult","installStickerSet","InstallStickerSet","uninstallStickerSet","UninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","GetInlineBotResults","foundGif","BotInlineMediaResult","fetchStickersForEmoji","GetStickers","StickersNotModified","fetchEmojiKeywords","fromVersion","GetEmojiKeywordsDifference","emojiKeyword","keyword","emoticons","checkChatUsername","CheckUsername","setChatUsername","UpdateUsername","updatePrivateLink","ExportChatInvite","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","onRequestEmailCode","checkPassword","clearPassword","updatePassword","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","UpdateProfile","checkUsername","updateUsername","updateProfilePhoto","UploadProfilePhoto","uploadProfilePhoto","fetchWallpapers","GetWallPapers","WallPapersNotModified","filteredWallpapers","wallpapers","WallPaper","pattern","uploadWallpaper","UploadWallPaper","WallPaperSettings","fetchBlockedContacts","GetBlocked","blockedIds","BlockedSlice","blockContact","Block","unblockContact","Unblock","fetchAuthorizations","GetAuthorizations","authorizations","terminateAuthorization","ResetAuthorization","terminateAllAuthorizations","ResetAuthorizations","fetchNotificationExceptions","GetNotifyExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","GetContactSignUpNotification","GetNotifySettings","InputNotifyUsers","InputNotifyChats","InputNotifyBroadcasts","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","SetContactSignUpNotification","updateNotificationSettings","fetchLanguages","langpack","GetLanguages","fetchLangPack","sourceLangPacks","collections","GetLangPack","fetchPrivacySettings","GetPrivacy","registerDevice","secret","RegisterDevice","tokenType","appSandbox","otherUids","unregisterDevice","UnregisterDevice","setPrivacySettings","privacyRules","allowedUsers","InputPrivacyValueAllowUsers","allowedChats","InputPrivacyValueAllowChatParticipants","blockedUsers","InputPrivacyValueDisallowUsers","blockedChats","InputPrivacyValueDisallowChatParticipants","InputPrivacyValueAllowAll","InputPrivacyValueAllowContacts","InputPrivacyValueDisallowContacts","InputPrivacyValueDisallowAll","SetPrivacy","buildShippingOptions","shippingOptions","prices","cur","label","validateRequestedInfo","requestInfo","shouldSave","payments","ValidateRequestedInfo","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","SendPaymentForm","InputPaymentCredentials","DataJSON","getPaymentForm","GetPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","GetPaymentReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initClient","flushUpdatesOnTickEnd","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","sendToOrigin","callbackState","Map","postMessage","callbackArgs","lastArg","fnName","callApi"],"mappings":";aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,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,GAE7B95E,EAAK0T,KAAKomE,GAGZ,MAAMrlF,QDXP,SAA0CmkG,KAAc54F,GAE7D,OAAOq/D,EAAQu5B,MAAW54F,GCSG64F,CAAQrnG,KAASwO,IAClC,YAAErJ,GAAqC,iBAAblC,GAAyB,gBAAiBA,GAAYA,GAAa,GAE/F44B,GACFirE,GAAa,CACXlkG,KAAM,iBACNi5B,YACA54B,YACCkC,GAEL,MAAO+I,GACHzD,KAEF5G,QAAQqK,MAAMA,GAGZ2tB,GACFirE,GAAa,CACXlkG,KAAM,iBACNi5B,YACA3tB,MAAO,CAAEjH,QAASiH,EAAMjH,WAK1B40B,GACFkrE,GAAcxiG,OAAOs3B,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAMysD,EAAWye,GAAczmG,IAAI0D,EAAK63B,WACpCysD,IACgBA,EDvCPrgD,YAAa,GC0C1B","file":"6b9e1c477ee38548ce72.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 111);\n","const Api = require('./tl/api');\nconst TelegramClient = require('./client/TelegramClient');\nconst connection = require('./network');\nconst tl = require('./tl');\nconst version = require('./Version');\nconst events = require('./events');\nconst utils = require('./Utils');\nconst errors = require('./errors');\nconst sessions = require('./sessions');\nconst extensions = require('./extensions');\nconst helpers = require('./Helpers');\n\nmodule.exports = {\n Api,\n TelegramClient,\n sessions,\n connection,\n extensions,\n tl,\n version,\n events,\n utils,\n errors,\n helpers,\n};\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet';\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n) {\n // eslint-disable-next-line max-len\n const mediaMatch = url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.Document | GramJs.StickerSet | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (['msg', 'sticker', 'gif', 'wallpaper', 'photo'].includes(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiMediaFormat, ApiOnProgress, ApiSessionData, OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n client = new TelegramClient(\n new sessions.CallbackSession(sessionData, onSessionUpdate),\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || DEFAULT_USER_AGENT,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n }\n\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n }\n\n onAuthReady();\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates = typeof result & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in result && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && media.webpage.photo instanceof GramJs.Photo\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isInputPeerChannel, isInputPeerChat, isInputPeerUser, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n if (peerEntity instanceof GramJs.User) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason === undefined) {\n return {\n isRestricted: false,\n };\n }\n\n return {\n isRestricted: peerEntity.restricted,\n restrictionReason,\n };\n } else if (peerEntity instanceof GramJs.Chat) {\n return {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n };\n } else if (peerEntity instanceof GramJs.Channel) {\n const isRestricted = peerEntity.restricted\n && peerEntity.restrictionReason\n && peerEntity.restrictionReason.some((reason) => reason.platform === 'all');\n\n return {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n isRestricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n }\n return {};\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: peerEntity.migratedTo.accessHash.toString(),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return photo.photoId.toString();\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : member.userId;\n\n return {\n userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now(),\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n} as LocalDb;\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\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 mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\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\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\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 const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\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 case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\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 if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\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 if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\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 return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\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 if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\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\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n\n const lastMessagesByChatId = buildCollectionByKey(\n [...result.messages, ...(resultPinned ? resultPinned.messages : [])]\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...preparePeers(result),\n ...(resultPinned && preparePeers(resultPinned)),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = [\n ...(resultPinned ? resultPinned.dialogs : []),\n ...result.dialogs,\n ];\n\n const orderedPinnedIds: number[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = [...result.users, ...(resultPinned ? resultPinned.users : [])]\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = [...result.chats, ...result.users]\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity),\n lastMessage,\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? call.id.toString() : undefined,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted,\n}: {\n chat: ApiChat; isMuted: boolean;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : undefined }),\n }));\n\n void requestChatUpdate(chat);\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: number; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as number,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n if (result instanceof GramJs.ChatInvite) {\n await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n\n return undefined;\n } else {\n return buildApiChatFromPreview(result.chat);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\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\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\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 */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\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 */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\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\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\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 return (crc ^ (-1)) >>> 0;\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n\n};\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiKeyboardButtons,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped, buildApiPhotoSize } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { getCurrencySign } from '../../../components/middle/helpers/getCurrencySign';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || (currentDate / 1000),\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action && buildAction(mtpMessage.action, fromId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const { inlineButtons, keyboardButtons } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty || !draft.message) {\n return undefined;\n }\n\n return {\n formattedText: buildMessageTextContent(draft.message, draft.entities),\n replyingToId: draft.replyToMsgId,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\n ]);\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n const currencySign = getCurrencySign(currency);\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n description: `${currencySign}${(Number(totalAmount) / 100).toFixed(2)} ${test ? 'TEST INVOICE' : ''}`,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'siteName',\n 'title',\n 'description',\n ]),\n photo: photo && photo instanceof GramJs.Photo\n ? {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes: photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize),\n }\n : undefined,\n // TODO support video and embed\n ...(document && { hasDocument: true }),\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let text = '';\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserId = 'users' in action\n // Api returns array of userIds, but no action currently has multiple users in it\n ? action.users && action.users[0]\n : ('userId' in action && action.userId) || undefined;\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = `%action_origin% created the group «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n text = isChannelPost\n ? `Channel renamed to «${action.title}»`\n : `%action_origin% changed group name to «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n text = isChannelPost\n ? 'Channel photo updated'\n : '%action_origin% updated group photo';\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n text = isChannelPost\n ? 'Channel photo was deleted'\n : 'Chat photo was deleted';\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% joined the group'\n : '%action_origin% added %target_user% to the group';\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% left the group'\n : '%action_origin% removed %target_user% from the group';\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = '%action_origin% joined the chat from invitation link';\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Channel created';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n text = 'Migrated to %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n text = 'Migrated from %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = '%action_origin% pinned %message%';\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'Chat history was cleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n text = `${isOutgoing ? 'Outgoing' : 'Incoming'} ${action.video ? 'Video' : 'Phone'} Call`;\n\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text += ` (${mins} min${mins > 1 ? 's' : ''})`;\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = '%action_origin% joined Telegram';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n const currencySign = getCurrencySign(action.currency);\n const amount = (Number(action.totalAmount) / 100).toFixed(2);\n text = `You successfully transferred ${currencySign}${amount} to shop for %product%`;\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = `Voice chat ended (${mins} min${mins > 1 ? 's' : ''})`;\n } else {\n text = 'Voice chat started';\n }\n } else {\n text = '%ACTION_NOT_IMPLEMENTED%';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserId,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons\n} | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'Receipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return { [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000),\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: Math.round(Date.now() / 1000),\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_IMAGE_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n}) {\n const isScheduled = message.date * 1000 > Date.now();\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId,\n}: {\n chat: ApiChat; threadId: number; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate(chat);\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n hash: calculateResultHash(messages.map((message) => message.id)),\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nexport function fetchMessageLink({ chat, message }: { chat: ApiChat; message: ApiMessage }) {\n return invokeRequest(new GramJs.channels.ExportMessageLink({\n id: message.id,\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n ...(message.isInAlbum && { grouped: true }),\n ...(message.threadInfo && message.threadInfo.topMessageId !== message.id && { thread: true }),\n }));\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","/*!\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'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object 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 * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\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 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\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(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, 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 interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, 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(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\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(null, 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(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.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 that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().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)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var 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 (!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 var 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 var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\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 (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var 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 case undefined:\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) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var 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 coersion 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// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var 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 var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var 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 var length = this.length | 0\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.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 var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\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 var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var 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 (isNaN(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 (Buffer.TYPED_ARRAY_SUPPORT &&\n 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 var indexSize = 1\n var arrLength = arr.length\n var 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 var i\n if (dir) {\n var 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 var found = true\n for (var 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 var 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 // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(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 latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, 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 // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var 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 var 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 return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(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 var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var 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\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var 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 var res = ''\n var 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 var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; 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 var 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 var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\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 = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\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 var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\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 = function readUInt32BE (offset, noAssert) {\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.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var 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 var i = byteLength\n var mul = 1\n var 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 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 if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\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 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.readFloatLE = function readFloatLE (offset, noAssert) {\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 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 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 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 = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var 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 = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var 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 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var 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 var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var 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 (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\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 if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\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 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 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 (!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('sourceStart out of bounds')\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 var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\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 (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\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 } else if (typeof val === 'number') {\n val = val & 255\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 var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).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 stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var 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 var byteArray = []\n for (var 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 var c, hi, lo\n var byteArray = []\n for (var 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 for (var 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\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiUser, ApiUserStatus, ApiUserType } from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo,\n } = mtpUserFull;\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n ...(botInfo && { botDescription: botInfo.description }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: buildApiUserType(mtpUser),\n ...(firstName && { firstName }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","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 = function(v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value << v.value)\r\n }\r\n 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 = function (v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value >> v.value)\r\n }\r\n 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 (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (typeof define === \"function\" && define.amd) {\r\n define( function () {\r\n return bigInt;\r\n });\r\n}\r\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid Phone Number',\n PHONE_CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","export function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","const { constructors } = require('./tl');\n\n// eslint-disable-next-line max-len\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex');\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex');\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`);\n}\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 ``check_hash`` **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 */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\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 if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity;\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf();\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new Error('User without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty\n || entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.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 constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty();\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user);\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId);\n }\n\n _raiseCastFail(entity, 'InputPeer');\n return undefined;\n}\n\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/* CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, 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/* CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\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 constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n\n/* CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/\n * tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\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 const header = Buffer.from(JPEG_HEADER);\n // eslint-disable-next-line prefer-destructuring\n header[164] = stripped[1];\n // eslint-disable-next-line prefer-destructuring\n header[166] = stripped[2];\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);\n}\n\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 constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.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 constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.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 constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\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 */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128;\n }\n if (fileSize <= 786432000) { // 750MB\n return 256;\n }\n if (fileSize <= 1572864000) { // 1500MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\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/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.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 if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\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 const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\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\nfunction _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 === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\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 ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\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: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\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 */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.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 constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction 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*/\nfunction getDC(dcId) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: 'pluto.web.telegram.org',\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: 'venus.web.telegram.org',\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: 'aurora.web.telegram.org',\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: 'vesta.web.telegram.org',\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: 'flora.web.telegram.org',\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n getAppropriatedPartSize,\n // getInputLocation,\n strippedPhotoToJpg,\n getDC,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n if (!stickerAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute.stickerset as GramJs.InputStickerSetID;\n const emoji = stickerAttribute.alt;\n const isAnimated = document.mimeType === 'application/x-tgsticker';\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo.id ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n hash,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs && thumbs.length),\n count,\n hash,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.');\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\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 if (typeof alert !== 'undefined') {\n // eslint-disable-next-line no-alert\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`);\n }\n this.invalidConstructorId = invalidConstructorId;\n this.remaining = remaining;\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\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/**\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 */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code;\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 this.code = code;\n this.payload = payload;\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.'];\n }\n super(...args);\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.');\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to '\n + 'synchronize it using msg_id notifications and re-send the original message '\n + 'with the “correct” msg_id or wrap it in a container with a new msg_id if the '\n + 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be '\n + 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id '\n + 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message (this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a '\n + 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower '\n + 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with '\n + 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with '\n + 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n };\n\n constructor(request, code) {\n let errorMessage = BadMessageError.ErrorMessages[code]\n || `Unknown error code (this should not happen): ${code}.`;\n errorMessage += ` Caused by ${request.className}`;\n super(errorMessage);\n this.message = errorMessage;\n this.code = code;\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n};\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { pick } from '../../../util/iteratees';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n","const { TypeNotFoundError } = require('../errors/Common');\nconst { coreObjects } = require('../tl/core');\nconst { tlobjects } = require('../tl/AllTLObjects');\nconst { readBigIntFromBuffer } = require('../Helpers');\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 }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0];\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res;\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n this.offset += 4;\n return res;\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4)\n .readFloatLE(0);\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\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 /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes()\n .toString('utf-8');\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false);\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 /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = tlobjects[constructorId];\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\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 for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n clazz = coreObjects[constructorId];\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n const pos = this.tellPosition();\n const error = new TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n return clazz.fromReader(this);\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected');\n }\n const count = this.readInt();\n const temp = [];\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = undefined;\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset;\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position;\n }\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 seek(offset) {\n this.offset += offset;\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader;\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now();\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[randomId.toString()];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now();\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: update.channelId,\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = update.notifySettings;\n\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isMuted,\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\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 setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\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 let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // 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) { // 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) { // 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) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // 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 if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const {\n sha1,\n toSignedLittleBuffer,\n readBufferFromBigInt,\n readBigIntFromBuffer,\n} = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { sleep } = require('../Helpers');\n\nclass AuthKey {\n constructor(value, hash) {\n if (!hash || !value) {\n return;\n }\n this._key = value;\n this._hash = hash;\n const reader = new 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 = undefined;\n this.auxHash = undefined;\n this.keyId = undefined;\n this._hash = undefined;\n return;\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 this._key = value;\n this._hash = await sha1(this._key);\n const reader = new 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 sleep(20);\n }\n }\n\n getKey() {\n return this._key;\n }\n\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}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const n = Buffer.alloc(1);\n n.writeUInt8(number, 0);\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])]);\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20);\n return readBigIntFromBuffer(shaData, true, true);\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey()\n .equals(this._key);\n }\n}\n\nmodule.exports = AuthKey;\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require('./RPCBaseErrors');\nconst { rpcErrorRe } = require('./RPCErrorList');\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex);\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1], 10) : undefined;\n return new Cls({\n request,\n capture,\n });\n }\n }\n\n return new RPCError(rpcError.errorMessage, request);\n}\n\nconst Common = require('./Common');\nconst RPCBaseErrors = require('./RPCBaseErrors');\nconst RPCErrorList = require('./RPCErrorList');\n\nmodule.exports = {\n RPCMessageToError,\n ...Common,\n ...RPCBaseErrors,\n ...RPCErrorList,\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\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 * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF1, 0x3F, 0x73,\n 0x98, 0x0D, 0x40, 0x23, 0x8E, 0x3E, 0x21, 0xC1, 0x49, 0x34, 0xD0, 0x37, 0x56, 0x3D, 0x93, 0x0F,\n 0x48, 0x19, 0x8A, 0x0A, 0xA7, 0xC1, 0x40, 0x58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x0C, 0xE9, 0x29, 0x85, 0x1F,\n 0x0D, 0x81, 0x15, 0xF6, 0x35, 0xB1, 0x05, 0xEE, 0x2E, 0x4E, 0x15, 0xD0, 0x4B, 0x24, 0x54, 0xBF,\n 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 throw new Error('Changing passwords unsupported');\n // checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number)\n .greater(BigInt(0))));\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([Buffer.alloc(SIZE_FOR_HASH - number.length), number]);\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false);\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp);\n\n const minDiffBitsCount = 2048 - 64;\n const maxModExpSize = 256;\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount\n || modexp.bitLength() < minDiffBitsCount\n || Math.floor((modexp.bitLength() + 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] ^= b[i];\n }\n\n return a;\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512');\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1]));\n const hash2 = await sha256(Buffer.concat([algo.salt2, hash1, algo.salt2]));\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000);\n return sha256(Buffer.concat([algo.salt2, hash3, algo.salt2]));\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\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 = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false));\n return bigNumForHash(value);\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo;\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`);\n }\n\n const pwHash = await computeHash(algo, password);\n const p = readBigIntFromBuffer(algo.p, false);\n const { g } = algo;\n const B = readBigIntFromBuffer(request.srp_B, false);\n try {\n checkPrimeAndGood(algo.p, g);\n } catch (e) {\n throw new Error('bad /g in password');\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check');\n }\n const x = readBigIntFromBuffer(pwHash, false);\n const pForHash = numBytesForHash(algo.p);\n const gForHash = bigNumForHash(g);\n const bForHash = numBytesForHash(request.srp_B);\n const gX = modExp(BigInt(g), x, p);\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([pForHash, gForHash])), false);\n const kgX = bigIntMod(k.multiply(gX), p);\n const generateAndCheckRandom = async () => {\n const randomSize = 256;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize);\n const a = readBigIntFromBuffer(random, false);\n const A = modExp(BigInt(g), a, p);\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A);\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([aForHash, bForHash])), false);\n if (u.greater(BigInt(0))) {\n return [a, aForHash, u];\n }\n }\n }\n };\n const [a, aForHash, u] = await generateAndCheckRandom();\n const gB = bigIntMod(B.subtract(kgX), p);\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 = modExp(gB, aUx, p);\n const [K, pSha, gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2),\n ]);\n const M1 = await sha256(Buffer.concat([\n xor(pSha, gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]));\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1,\n\n });\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n};\n","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\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 if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // 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.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","const AES = require('@cryptography/aes').default;\nconst {\n i2ab,\n ab2i,\n} = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue);\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes);\n this._counter = bytes;\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\nclass CTR {\n constructor(key, counter) {\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter);\n }\n\n this._counter = counter;\n\n this._remainingCounter = undefined;\n this._remainingCounterIndex = 16;\n\n this._aes = new AES(getWords(key));\n }\n\n update(plainText) {\n return this.encrypt(plainText);\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText);\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))));\n this._remainingCounterIndex = 0;\n this._counter.increment();\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];\n }\n\n return encrypted;\n }\n}\n\n// endregion\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\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\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count);\n crypto.getRandomValues(bytes);\n return bytes;\n}\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\n async digest() {\n if (this.algorithm === 'sha1') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data));\n } else if (this.algorithm === 'sha256') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data));\n }\n return undefined;\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n { name: 'PBKDF2' }, false, ['deriveBits']);\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt,\n iterations,\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm);\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2,\n};\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = undefined) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request)),\n );\n this.code = code;\n this.message = 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/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code);\n this.code = code || 303;\n this.message = message || 'ERROR_SEE_OTHER';\n }\n}\n\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 */\nclass BadRequestError extends RPCError {\n code = 400;\n\n message = 'BAD_REQUEST';\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401;\n\n message = 'UNAUTHORIZED';\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403;\n\n message = 'FORBIDDEN';\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404;\n\n message = 'NOT_FOUND';\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406;\n\n message = 'AUTH_KEY';\n}\n\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 */\nclass FloodError extends RPCError {\n code = 420;\n\n message = 'FLOOD';\n}\n\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 */\nclass ServerError extends RPCError {\n code = 500; // Also witnessed as -500\n\n message = 'INTERNAL';\n}\n\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 */\nclass TimedOutError extends RPCError {\n code = 503; // Only witnessed as -503\n\n message = 'Timeout';\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n};\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // 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 static MAXIMUM_SIZE = 1044456 - 8;\n\n // 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 static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\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 */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets();\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect() {\n this._connected = false;\n await this._recvArray.push(undefined);\n await this.socket.close();\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","/* pako 1.0.10 nodeca/pako */(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n},{\"./common\":1}],3:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n},{}],7:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],8:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":1,\"./adler32\":3,\"./crc32\":5,\"./inffast\":7,\"./inftrees\":9}],9:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":1}],10:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],11:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],\"/lib/inflate.js\":[function(require,module,exports){\n'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n},{\"./utils/common\":1,\"./utils/strings\":2,\"./zlib/constants\":4,\"./zlib/gzheader\":6,\"./zlib/inflate\":8,\"./zlib/messages\":10,\"./zlib/zstream\":11}]},{},[])(\"/lib/inflate.js\")\n});\n","const Logger = require('./Logger');\nconst BinaryWriter = require('./BinaryWriter');\nconst BinaryReader = require('./BinaryReader');\nconst PromisedWebSockets = require('./PromisedWebSockets');\nconst MessagePacker = require('./MessagePacker');\nconst AsyncQueue = require('./AsyncQueue');\n\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n};\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\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 return (crc ^ (-1)) >>> 0;\n}\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\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\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: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\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)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\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 return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // 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 called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // 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 currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\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 return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\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()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\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\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","var 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\nexport default AES;\nexport { AES_IGE$1 as CTR, AES_IGE as IGE };\n","let _level;\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug'];\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug';\n }\n\n this.isBrowser = typeof process === 'undefined'\n || process.type === 'renderer'\n || process.browser === true\n || process.__nwjs;\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 this.messageFormat = '[%t] [%l] - [%m]';\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level));\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n this._log('warn', message, this.colors.warn);\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info);\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug);\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n this._log('error', message, this.colors.error);\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message);\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level) {\n return;\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n // eslint-disable-next-line no-console\n console.log(color + this.format(message, level) + this.colors.end);\n } else {\n // eslint-disable-next-line no-console\n console.log(this.colors.start + this.format(message, level), color);\n }\n }\n }\n}\n\nmodule.exports = Logger;\n","const {\n RPCError,\n InvalidDCError,\n FloodError,\n BadRequestError,\n} = require('./RPCBaseErrors');\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`);\n this.message = `A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n this.message = `The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0);\n super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`;\n this.codeLength = codeLength;\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n];\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n EmailUnconfirmedError,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","const api = require('./api');\n\nconst LAYER = 128;\nconst tlobjects = {};\n\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\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\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst doAuthentication = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n\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 */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\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._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * Whether the user has explicitly connected or disconnected.\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 this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\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 this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\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 this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n await Helpers.sleep(this._delay);\n }\n }\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n await this._disconnect();\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\n .. code-block:: javascript\n\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\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\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 send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n // CONTEST\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n /*\n if (!Helpers.isArrayLike(request)) {\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n } else {\n throw new Error('not supported')\n } */\n }\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 async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.time_offset = res.timeOffset;\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\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 async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // 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 const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\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 try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\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._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof 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 continue;\n } else if (e instanceof 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 continue;\n } else if (e instanceof InvalidBufferError) {\n this._log.info('Broken authorization key; resetting');\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(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 // We don't really need to do this if we're going to sign in again\n /* await this.authKey.setKey(null)\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(null)\n } */\n // We can disconnect at sign in\n /* await this.disconnect()\n */\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\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 async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\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 _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\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 _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.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 BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\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 async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\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 async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _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 return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\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 _handlePong(message) {\n const pong = message.obj;\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\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 _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\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 _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\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(message.msgId);\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 BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\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 _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\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 _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\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 _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\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\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\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n delete this._pending_state[msgId];\n state.resolve(true);\n }\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 _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 const state = this._pending_state[message.msgId];\n\n if (state) {\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\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 _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n this._log.info('Started reconnecting');\n this._reconnect();\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this.disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n await this.connect(this._connection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\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 */\nconst BigInt = require('big-integer');\nconst MTProtoState = require('./MTProtoState');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { toSignedLittleBuffer } = require('../Helpers');\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\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(connection, loggers);\n this._connection = connection;\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n let body = request.getBytes();\n let msgId = this._state._getNewMsgId();\n const m = toSignedLittleBuffer(msgId, 8);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body]);\n\n await this._connection.send(res);\n body = await this._connection.recv();\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n const reader = new BinaryReader(body);\n const authKeyId = reader.readLong();\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId');\n }\n msgId = reader.readLong();\n if (msgId.eq(BigInt(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 const length = reader.readInt();\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 return reader.tgReadObject();\n }\n}\n\nmodule.exports = MTProtoPlainSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\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\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\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 */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\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 async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\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 async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, data).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\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 async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\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 const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\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 _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\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 _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\nmodule.exports = MTProtoState;\n","const { IGE: AESIGE } = require('@cryptography/aes');\nconst Helpers = require('../Helpers');\n\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new AESIGE(key, iv);\n }\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 decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\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 encryptIge(plainText) {\n const padding = plainText.length % 16;\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)]);\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n }\n}\n\nmodule.exports = IGENEW;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\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 if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // 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 return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","const BigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst RSA = require('../crypto/RSA');\nconst Helpers = require('../Helpers');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { SecurityError } = require('../errors/Common');\n\n/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\nasync function doAuthentication(sender, log) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16);\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true);\n\n const resPQ = await sender.send(new requests.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof constructors.ResPQ)) {\n throw new Error(`Step 1 answer was ${resPQ}`);\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true);\n log.debug('Finished authKey generation step 1');\n log.debug('Starting authKey generation step 2');\n // Step 2 sending: DH Exchange\n let {\n p,\n q,\n } = Factorizator.factorize(pq);\n\n // TODO Bring back after `Factorizator` fix.\n p = Helpers.getByteArray(p);\n q = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n\n const pqInnerData = new constructors.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p,\n q,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n });\n\n // sha_digest + data + random_bytes\n let cipherText;\n let targetFingerprint;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n cipherText = await RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes());\n if (cipherText !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (cipherText === undefined) {\n throw new SecurityError('Step 2 could not find a valid key for fingerprints');\n }\n\n const serverDhParams = await sender.send(\n new requests.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p,\n q,\n publicKeyFingerprint: targetFingerprint,\n encryptedData: cipherText,\n }),\n );\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk\n || serverDhParams instanceof constructors.ServerDHParamsFail)) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`);\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server');\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server');\n }\n\n if (serverDhParams instanceof constructors.ServerDHParamsFail) {\n const sh = await Helpers.sha1(Helpers.toSignedLittleBuffer(newNonce, 32)\n .slice(4, 20));\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true);\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server');\n }\n }\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`);\n }\n log.debug('Finished authKey generation step 2');\n log.debug('Starting authKey generation step 3');\n\n // Step 3 sending: Complete DH Exchange\n const {\n key,\n iv,\n } = await Helpers.generateKeyDataFromNonce(resPQ.serverNonce, newNonce);\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch');\n }\n const ige = new IGE(key, iv);\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer);\n const reader = new BinaryReader(plainTextAnswer);\n reader.read(20); // hash sum\n const serverDhInner = reader.tgReadObject();\n if (!(serverDhInner instanceof constructors.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`);\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer');\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 3 Invalid server nonce in encrypted answer');\n }\n const dhPrime = Helpers.readBigIntFromBuffer(serverDhInner.dhPrime, false, false);\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false);\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000);\n const b = Helpers.readBigIntFromBuffer(Helpers.generateRandomBytes(256), false, false);\n const gb = Helpers.modExp(BigInt(serverDhInner.g), b, dhPrime);\n const gab = Helpers.modExp(ga, b, dhPrime);\n\n // Prepare client DH Inner Data\n const clientDhInner = new constructors.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: 0, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([await Helpers.sha1(clientDhInner), clientDhInner]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new requests.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [constructors.DhGenOk, constructors.DhGenRetry, constructors.DhGenFail];\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 const { name } = dhGen.constructor;\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`);\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(`Step 3 invalid ${name} server nonce from server`);\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypes.indexOf(dhGen.constructor);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\n const dhHash = dhGen[`newNonceHash${nonceNumber}`];\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash');\n }\n\n if (!(dhGen instanceof constructors.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return {\n authKey,\n timeOffset,\n };\n}\n\n\nmodule.exports = doAuthentication;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('../extensions/BinaryWriter');\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 this.setReady(true);\n\n if (state) {\n this._pendingStates.push(state);\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {\n })\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state);\n });\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state);\n }\n this.setReady(true);\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 if (!this._queue[this._queue.length - 1]) {\n this._queue = [];\n return undefined;\n }\n let data;\n let buffer = new BinaryWriter(Buffer.alloc(0));\n\n const batch = [];\n let size = 0;\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift();\n size += state.data.length + TLMessage.SIZE_OVERHEAD;\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId;\n if (state.after) {\n afterId = state.after.msgId;\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n );\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className\n || state.request.constructor.name}`);\n batch.push(state);\n continue;\n }\n if (batch.length) {\n this._queue.unshift(state);\n break;\n }\n this._log.warn(`Message payload for ${state.request.className\n || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);\n state.reject('Request Payload is too big');\n size = 0;\n }\n if (!batch.length) {\n return undefined;\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8);\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0);\n b.writeInt32LE(batch.length, 4);\n data = Buffer.concat([b, buffer.getValue()]);\n buffer = new BinaryWriter(Buffer.alloc(0));\n const containerId = await this._state.writeDataAsMessage(\n 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 requestState.reject(new Error('Disconnect'));\n });\n }\n}\n\nmodule.exports = MessagePacker;\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n}\n\nmodule.exports = BinaryWriter;\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst doAuthentication = require('./Authenticator');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n doAuthentication,\n MTProtoSender,\n UpdateConnectionState,\n};\n","const { Mutex } = require('async-mutex');\n\nconst mutex = new Mutex();\n\nconst WebSocketClient = require('websocket').w3cwebsocket;\n\nconst closeError = new Error('WebSocket was closed');\n\nclass PromisedWebSockets {\n constructor() {\n /* CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = undefined;\n this.closed = true;\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0);\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const thisTime = await this.read(number);\n readData = Buffer.concat([readData, thisTime]);\n number -= thisTime.length;\n if (!number) {\n return readData;\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError;\n }\n await this.canRead;\n if (this.closed) {\n throw closeError;\n }\n const toReturn = this.stream.slice(0, number);\n this.stream = this.stream.slice(number);\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 const toReturn = this.stream;\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n\n return toReturn;\n }\n\n getWebSocketLink(ip, port) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`;\n } else {\n return `ws://${ip}:${port}/apiws`;\n }\n }\n\n connect(port, ip) {\n this.stream = 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);\n this.client = new WebSocketClient(this.website, 'binary');\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive();\n resolve(this);\n };\n this.client.onerror = (error) => {\n reject(error);\n };\n this.client.onclose = () => {\n this.resolveRead(false);\n this.closed = true;\n };\n // CONTEST\n // Seems to not be working, at least in a web worker\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('offline', async () => {\n await this.close();\n this.resolveRead(false);\n });\n });\n }\n\n write(data) {\n if (this.closed) {\n throw closeError;\n }\n this.client.send(data);\n }\n\n async close() {\n await this.client.close();\n this.closed = true;\n }\n\n receive() {\n this.client.onmessage = async (message) => {\n const release = await mutex.acquire();\n try {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer());\n this.stream = Buffer.concat([this.stream, data]);\n this.resolveRead(true);\n } finally {\n release();\n }\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\n","class AsyncQueue {\n constructor() {\n this._queue = [];\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n this.canPush = true;\n }\n\n async push(value) {\n await this.canPush;\n this._queue.push(value);\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 const returned = this._queue.pop();\n this.resolvePush(true);\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n}\n\nmodule.exports = AsyncQueue;\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\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 if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\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 */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\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\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result;\n}\n","'use strict'\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","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\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\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\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\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] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\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\n const buf = new Uint32Array(key.length / 4);\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] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","module.exports = `boolFalse#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#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = 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:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# 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 file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# 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:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#f4e096c3 flags:# multiple_allowed:flags.1?true can_forward:flags.2?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string = 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#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = 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#bba51639 call:InputGroupCall time_ms:long scale:int = InputFileLocation;\npeerUser#9db1bc6d user_id:int = Peer;\npeerChat#bad0e5bb chat_id:int = Peer;\npeerChannel#bddde532 channel_id:int = 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#200250ba id:int = User;\nuser#938458c1 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 id:int 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 = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?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#9ba2d800 id:int = Chat;\nchat#3bda1bde flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true id:int 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#7328bdb id:int title:string = Chat;\nchannel#d31a961e 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 id:int access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int version: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 = Chat;\nchannelForbidden#289da732 flags:# broadcast:flags.5?true megagroup:flags.8?true id:int access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#8a1e2983 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:int 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 = ChatFull;\nchannelFull#548c3f93 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 id:int 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?int 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?int 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 = ChatFull;\nchatParticipant#c8d7493e user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantCreator#da13538a user_id:int = ChatParticipant;\nchatParticipantAdmin#e2d6e436 user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3f460fed chat_id:int 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#bce383d2 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 id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int 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 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:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#cbf24940 phone_number:string first_name:string last_name:string vcard:string user_id:int = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# 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#84551347 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 = 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#a6638b9a title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#488a7337 users:Vector = MessageAction;\nmessageActionChatDeleteUser#b2ae9b0c user_id:int = MessageAction;\nmessageActionChatJoinedByLink#f89cf5e8 inviter_id:int = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#51bdb021 channel_id:int = MessageAction;\nmessageActionChannelMigrateFrom#b055eaee title:string chat_id:int = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = 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#abe9affe domain:string = 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#76b9f11a call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\ndialog#2c171f72 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 notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?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.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#df969c2d id:int bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 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 geo_distance:flags.6?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#8af40b25 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;\nuserFull#139a9a77 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 user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?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 = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int 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#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages: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#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#86cadb6c chat_id:int from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int date:int photo:UserProfilePhoto previous:Bool = 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#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int 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#12b9417b user_id:int 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#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#3f2038db flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int 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#e73547e1 flags:# query_id:long user_id:int 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#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int 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#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int 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#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int 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#42f88f2c poll_id:long user_id:int options:Vector = 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#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#6b171718 flags:# channel_id:int 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#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChat#1330a196 chat_id:int = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#a45eb99b chat_id:int call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#f3b3781f flags:# chat_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#7fecb1ec flags:# channel_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#7f9488a user_id:int date:int stopped:Bool qts:int = 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#faeff833 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#1157b858 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int 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 id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?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 saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max: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 = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int 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#4a70994c id:long access_hash:long size:int 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#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int 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;\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;\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;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 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;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int 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 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#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 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 = 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#6e24fc9d flags:# revoked:flags.0?true permanent:flags.5?true link:string admin_id:int date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title: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;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?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 count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = 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#568a748 flags:# same_peer:flags.0?true text:string query:string = 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;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = 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#352dca58 offset:int length:int user_id:int = 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;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = 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#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#50a1dfd6 flags:# left:flags.0?true peer:Peer kicked_by:int 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#2e0709a5 hash:int 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#d5348d85 flags:# multiple_allowed:flags.1?true can_forward:flags.3?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string 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#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM 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.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;\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;\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#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int 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;\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#58fffcd0 pos:int user_id:int 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#cd886e0 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 currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = 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;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#8d0b2415 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:int invoice:Invoice provider_id:int url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials 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#10b555d0 flags:# date:int bot_id:int provider_id:int 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#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int 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#9d4c17c0 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#a26f881b prev_value:int new_value:int = 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#5cdada77 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;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int 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 = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = 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#cac943f2 hash:long bot_id:int 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#5108d648 hash:int sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int 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#e0277a62 id:long access_hash:long size:int 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#badcc1a3 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 = 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 until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 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:int file_size_max:int 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#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int 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#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int 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;\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;\nstatsGroupTopPoster#18f3d0f7 user_id:int messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#6014f412 user_id:int deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#31962a4c user_id:int 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#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int 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#c95c6654 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 id:long access_hash:long participants_count:int params:flags.0?DataJSON title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#b96b25ee 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 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 params:flags.6?DataJSON = 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;\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#1e3e6680 user_id:int date:int = 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#dfd2330f admin_id:int 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;\n---functions---\n// Only needed functions from \\`api.tl\\` are manually copied here to reduce package size\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;\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#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\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#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.getWallPapers#aabb1763 hash:int = account.WallPapers;\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.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.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = 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.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\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#d4982db5 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:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec 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:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id: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#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = 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.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\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.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = 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.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = 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.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = 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#f025bc8b peer:InputPeer = messages.AffectedHistory;\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.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = 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#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = 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.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int 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;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 128\n`;","module.exports = `resPQ#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;\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;\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;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n`;","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst DEFAULT_IPV4_IP = 'venus.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: undefined,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: undefined,\n systemVersion: undefined,\n appVersion: undefined,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n };\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (apiId === undefined || apiHash === undefined) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md');\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts };\n this.apiId = apiId;\n this.apiHash = apiHash;\n this._useIPV6 = args.useIPV6;\n // this._entityCache = new Set()\n if (typeof args.baseLogger === 'string') {\n this._log = new Logger();\n } else {\n this._log = args.baseLogger;\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented');\n } catch (e) {\n session = new MemorySession();\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance');\n }\n\n this.floodSleepLimit = args.floodSleepLimit;\n this._eventBuilders = [];\n\n this._phoneCodeHash = {};\n this.session = session;\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId, 10);\n this.apiHash = apiHash;\n\n this._requestRetries = args.requestRetries;\n this._connectionRetries = args.connectionRetries;\n this._retryDelay = args.retryDelay || 0;\n if (args.proxy) {\n this._log.warn('proxies are not supported');\n }\n this._proxy = args.proxy;\n this._timeout = args.timeout;\n this._autoReconnect = args.autoReconnect;\n\n this._connection = args.connection;\n // TODO add proxy support\n\n this._floodWaitedRequests = {};\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: undefined, // no proxies yet.\n }),\n });\n };\n\n this._args = args;\n // These will be set later\n this._config = undefined;\n this.phoneCodeHashes = [];\n this._borrowedSenderPromises = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n }\n\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession();\n\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log,\n );\n\n await this._sender.connect(connection);\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n this._updateLoop();\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (this.isConnected()) {\n await Helpers.sleep(3 * 1000);\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.Ping({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n })), 1500);\n }, 3, 100);\n } catch (err) {\n await this.disconnect();\n this.connect();\n\n return;\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect();\n }\n\n await Promise.all(\n Object.values(this._borrowedSenderPromises)\n .map((promise) => {\n return promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._borrowedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n await this.disconnect();\n this.session.delete();\n this._eventBuilders = [];\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n const DC = utils.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port);\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n _cleanupBorrowedSender(dcId) {\n delete this._borrowedSenderPromises[dcId];\n }\n\n _borrowExportedSender(dcId) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n let senderPromise = this._borrowedSenderPromises[dcId];\n if (!senderPromise) {\n senderPromise = this._createExportedSender(dcId);\n this._borrowedSenderPromises[dcId] = senderPromise;\n\n senderPromise.then((sender) => {\n if (!sender) {\n delete this._borrowedSenderPromises[dcId];\n }\n });\n }\n return senderPromise;\n }\n\n async _createExportedSender(dcId) {\n const dc = utils.getDC(dcId);\n const sender = new MTProtoSender(this.session.getAuthKey(dcId),\n {\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._cleanupBorrowedSender.bind(this),\n });\n for (let i = 0; i < 5; i++) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ));\n if (this.session.dcId !== dcId) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`);\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId }));\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n }));\n await sender.send(req);\n }\n sender.dcId = dcId;\n return sender;\n } catch (e) {\n await sender.disconnect();\n }\n }\n return undefined;\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise}\n */\n downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args);\n }\n\n downloadMedia(messageOrMedia, args) {\n let media;\n if (messageOrMedia instanceof constructors.Message) {\n media = messageOrMedia.media;\n } else {\n media = messageOrMedia;\n }\n if (typeof media === 'string') {\n throw new Error('not implemented');\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args);\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args);\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args);\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args);\n }\n return undefined;\n }\n\n downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697];\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm';\n let photo;\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity;\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return undefined;\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n );\n }\n photo = entity.photo;\n }\n\n let dcId;\n let loc;\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId;\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: isBig,\n });\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return undefined;\n }\n return this.downloadFile(loc, {\n dcId,\n });\n }\n\n downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumbs || !stickerSet.thumbs.length) {\n return undefined;\n }\n\n const { thumbVersion } = stickerSet;\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash,\n }),\n thumbVersion,\n }),\n { dcId: stickerSet.thumbDcId },\n );\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i]);\n if (size) {\n return size;\n }\n }\n return undefined;\n }\n\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.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: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadWebDocument(media, args) {\n throw new Error('not implemented');\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n try {\n const promise = this._sender.send(request);\n const result = await promise;\n // this.session.processEntities(result)\n // this._entityCache.add(result)\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0];\n } catch (e) {\n this._log.warn('error while getting me');\n this._log.warn(e);\n }\n return undefined;\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect();\n }\n\n if (await checkAuthorization(this)) {\n return;\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash,\n };\n\n await authFlow(this, apiCredentials, authParams);\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams);\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback]);\n }\n\n _handleUpdate(update) {\n // this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = [];\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x);\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities);\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, undefined);\n } else {\n this._processUpdate(update, undefined);\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || [];\n const args = {\n update,\n others,\n };\n this._dispatchUpdate(args);\n }\n\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise}\n * @private\n */\n /* CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n 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\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\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.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\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 peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.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 utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\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 Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","exports.endianness = function () { return 'LE' };\n\nexports.hostname = function () {\n if (typeof location !== 'undefined') {\n return location.hostname\n }\n else return '';\n};\n\nexports.loadavg = function () { return [] };\n\nexports.uptime = function () { return 0 };\n\nexports.freemem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.totalmem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.cpus = function () { return [] };\n\nexports.type = function () { return 'Browser' };\n\nexports.release = function () {\n if (typeof navigator !== 'undefined') {\n return navigator.appVersion;\n }\n return '';\n};\n\nexports.networkInterfaces\n= exports.getNetworkInterfaces\n= function () { return {} };\n\nexports.arch = function () { return 'javascript' };\n\nexports.platform = function () { return 'browser' };\n\nexports.tmpdir = exports.tmpDir = function () {\n return '/tmp';\n};\n\nexports.EOL = '\\n';\n\nexports.homedir = function () {\n\treturn '/'\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","const BigInt = require('big-integer');\nconst { modExp } = require('../Helpers');\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(BigInt.zero)) {\n const temp = b;\n b = a.remainder(b);\n a = temp;\n }\n return a;\n }\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 static factorize(pq) {\n if (pq.remainder(2)\n .equals(BigInt.zero)) {\n return {\n p: BigInt(2),\n q: pq.divide(BigInt(2)),\n };\n }\n let y = BigInt.randBetween(BigInt(1), pq.minus(1));\n const c = BigInt.randBetween(BigInt(1), pq.minus(1));\n const m = BigInt.randBetween(BigInt(1), pq.minus(1));\n\n let g = BigInt.one;\n let r = BigInt.one;\n let q = BigInt.one;\n let x = BigInt.zero;\n let ys = BigInt.zero;\n let k;\n\n while (g.eq(BigInt.one)) {\n x = y;\n for (let i = 0; BigInt(i)\n .lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n }\n k = BigInt.zero;\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n ys = y;\n const condition = BigInt.min(m, r.minus(k));\n for (let i = 0; BigInt(i)\n .lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n q = q.multiply(x.minus(y)\n .abs())\n .remainder(pq);\n }\n g = Factorizator.gcd(q, pq);\n k = k.add(m);\n }\n\n r = r.multiply(2);\n }\n\n\n if (g.eq(pq)) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c)\n .remainder(pq);\n g = Factorizator.gcd(x.minus(ys)\n .abs(), pq);\n\n if (g.greater(1)) {\n break;\n }\n }\n }\n const p = g;\n q = pq.divide(g);\n return p < q ? {\n p,\n q,\n } : {\n p: q,\n q: p,\n };\n }\n}\n\nmodule.exports = Factorizator;\n","/* eslint-disable max-len */\nconst BigInt = require('big-integer');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n generateRandomBytes,\n modExp,\n} = require('../Helpers');\n\nconst PUBLIC_KEYS = [{\n fingerprint: [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],\n n: BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),\n e: 65537,\n}, {\n fingerprint: [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],\n n: BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),\n e: 65537,\n}, {\n fingerprint: [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],\n n: BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),\n e: 65537,\n}, {\n fingerprint: [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],\n n: BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),\n e: 65537,\n}];\n\nconst _serverKeys = {};\n\nPUBLIC_KEYS.forEach(({\n fingerprint,\n ...keyInfo\n}) => {\n _serverKeys[readBigIntFromBuffer(fingerprint.slice(-8), true, true)] = keyInfo;\n});\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 None if no key matching this fingerprint is found.\n */\nasync function encrypt(fingerprint, data) {\n const key = _serverKeys[fingerprint];\n if (!key) {\n return undefined;\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length);\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand]);\n\n // 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 const payload = readBigIntFromBuffer(toEncrypt, false);\n const encrypted = modExp(payload, BigInt(key.e), key.n);\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false);\n}\n\nmodule.exports = {\n encrypt,\n};\n","class 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\nmodule.exports = RequestState;\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex_1 = require(\"./Mutex\");\nexports.Mutex = Mutex_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._queue = [];\n this._pending = false;\n }\n Mutex.prototype.isLocked = function () {\n return this._pending;\n };\n Mutex.prototype.acquire = function () {\n var _this = this;\n var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); });\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this\n .acquire()\n .then(function (release) {\n var result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw (e);\n }\n return Promise\n .resolve(result)\n .then(function (x) { return (release(), x); }, function (e) {\n release();\n throw e;\n });\n });\n };\n Mutex.prototype._dispatchNext = function () {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","var _global = (function () {\n\tif (!this && typeof global !== 'undefined') {\n\t\treturn global;\n\t}\n\treturn this;\n})();\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar websocket_version = require('./version');\n\n\n/**\n * Expose a W3C WebSocket class with just one or two arguments.\n */\nfunction W3CWebSocket(uri, protocols) {\n\tvar native_instance;\n\n\tif (protocols) {\n\t\tnative_instance = new NativeWebSocket(uri, protocols);\n\t}\n\telse {\n\t\tnative_instance = new NativeWebSocket(uri);\n\t}\n\n\t/**\n\t * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket\n\t * class). Since it is an Object it will be returned as it is when creating an\n\t * instance of W3CWebSocket via 'new W3CWebSocket()'.\n\t *\n\t * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2\n\t */\n\treturn native_instance;\n}\nif (NativeWebSocket) {\n\t['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {\n\t\tObject.defineProperty(W3CWebSocket, prop, {\n\t\t\tget: function() { return NativeWebSocket[prop]; }\n\t\t});\n\t});\n}\n\n/**\n * Module exports.\n */\nmodule.exports = {\n 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,\n 'version' : websocket_version\n};\n","module.exports = require('../package.json').version;\n","const crypto = require('./crypto');\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !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.from(this.cipher.update(data));\n }\n}\n\nmodule.exports = CTR;\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n const me = 'phoneNumber' in authParams\n ? await signInUser(client, apiCredentials, authParams)\n : await signInBot(client, apiCredentials, authParams);\n\n // TODO @logger\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, 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 authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\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.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\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 Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep } from '../Helpers';\n\nexport interface progressCallback {\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst REQUEST_TIMEOUT = 15000;\n\n\nclass Foreman {\n private deferred: Deferred | undefined;\n\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\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\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let {\n partSizeKb, end,\n } = fileParams;\n const {\n fileSize, workers = 1,\n } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n let sender: any;\n if (dcId) {\n try {\n sender = await client._borrowExportedSender(dcId);\n } catch (e) {\n // This should never raise\n client._log.error(e);\n if (e.message === 'DC_ID_INVALID') {\n // Can't export a sender for the ID we are currently in\n sender = client._sender;\n } else {\n throw e;\n }\n }\n } else {\n sender = client._sender;\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - (offset % ONE_MB);\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n await foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async () => {\n try {\n const result = await Promise.race([\n await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset,\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(REQUEST_TIMEOUT).then(() => Promise.reject(new Error('REQUEST_TIMEOUT'))),\n ]);\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n return result.bytes;\n } catch (err) {\n hasEnded = true;\n throw err;\n } finally {\n foreman.releaseWorker();\n }\n })());\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n\n\nfunction createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve: resolve!,\n };\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\n\ninterface OnProgress {\n isCanceled?: boolean;\n\n // Float between 0 and 1.\n (progress: number): void;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst UPLOAD_TIMEOUT = 15 * 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // We always upload from the DC we are in.\n const sender = await client._borrowExportedSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\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 if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n // eslint-disable-next-line no-loop-func\n sendingParts.push((async () => {\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: j,\n fileTotalParts: partCount,\n bytes,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: j,\n bytes,\n }),\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 }\n try {\n await Promise.race([\n await Promise.all(sendingParts),\n sleep(UPLOAD_TIMEOUT * workers).then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n } catch (err) {\n if (err.message === 'TIMEOUT') {\n // eslint-disable-next-line no-console\n console.warn('Upload timeout. Retrying...');\n i -= workers;\n continue;\n }\n\n throw err;\n }\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new 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\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\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\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\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 */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\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 Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : 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 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 Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","module.exports = '0.0.2';\n","const NewMessage = require('./NewMessage');\nconst Raw = require('./Raw');\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = {\n NewMessage,\n StopPropagation,\n Raw,\n};\n","const { EventBuilder } = require('./common');\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: undefined,\n func: undefined,\n }) {\n super();\n if (!args.types) {\n this.types = true;\n } else {\n this.types = args.types;\n }\n }\n\n build(update) {\n return update;\n }\n}\n\nmodule.exports = Raw;\n","class EventBuilder {\n constructor(args = {\n chats: undefined,\n blacklistChats: undefined,\n func: undefined,\n }) {\n this.chats = args.chats;\n this.blacklistChats = Boolean(args.blacklistChats);\n this.resolved = false;\n this.func = args.func;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n build(update) {\n\n }\n}\n\n\nmodule.exports = {\n EventBuilder,\n};\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends 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\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\n * You can use custom `encode` and `decode` functions, if present:\n\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 = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\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;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs && stickerSet.thumbs.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: result.hash,\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport { buildApiWallpaper, buildApiSession, buildPrivacyRules } from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n hash: result.hash,\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: number) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildPeer(chatOrUserId),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions() {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }), true);\n\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updateLocalDb(result);\n }\n}\n\nexport async function fetchNotificationSettings() {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent || (typeof privateMuteUntil === 'number' && Date.now() < privateMuteUntil * 1000)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number' && Date.now() < groupMuteUntil * 1000)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number' && Date.now() < broadcastMuteUntil * 1000)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : undefined,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: { sourceLangPacks: string[]; langCode: string }) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: IInputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nfunction updateLocalDb(\n result: GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined,\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\n\nexport async function validateRequestedInfo({\n messageId,\n requestInfo,\n shouldSave,\n}: {\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n messageId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n messageId: number;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n messageId,\n}: {\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n msgId: messageId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({ msgId }));\n if (!result) {\n return undefined;\n }\n return buildReceipt(result);\n}\n","import {\n ApiOnProgress, ApiSessionData, ApiUpdate, OnApiUpdate,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, sessionData);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/7.3c4397f983ad7c01b144.js b/dist/7.4122a010f2ae7876c212.js similarity index 98% rename from dist/7.3c4397f983ad7c01b144.js rename to dist/7.4122a010f2ae7876c212.js index 49e5632b..15e7aa0e 100644 --- a/dist/7.3c4397f983ad7c01b144.js +++ b/dist/7.4122a010f2ae7876c212.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{136:function(t,e,i){"use strict";function s(t,e){return e-Math.floor(e/t)*t}i.d(e,"a",(function(){return s}))},194:function(t,e,i){"use strict";i.r(e);var s=i(311),n=i.n(s),r=i(7),a=i(28);function h(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class o{constructor(t){this.worker=t,h(this,"requestStates",new Map),h(this,"requestStatesByCallback",new Map),this.subscribe()}request(t){const{worker:e,requestStates:i,requestStatesByCallback:s}=this,n=Object(a.a)(i),r={type:"callMethod",messageId:n,...t},h={messageId:n},o=new Promise((t,e)=>{Object.assign(h,{resolve:t,reject:e})});if("function"==typeof r.args[r.args.length-1]){const t=r.args.pop();h.callback=t,s.set(t,h)}return i.set(n,h),o.catch(()=>{}).finally(()=>{i.delete(n),h.callback&&s.delete(h.callback)}),e.postMessage(r),o}cancelCallback(t){t.isCanceled=!0;const{messageId:e}=this.requestStatesByCallback.get(t)||{};e&&this.worker.postMessage({type:"cancelProgress",messageId:e})}subscribe(){const{worker:t,requestStates:e}=this;t.addEventListener("message",({data:t})=>{if("methodResponse"===t.type){const i=e.get(t.messageId);i&&(t.error?i.reject(t.error):i.resolve(t.response))}else if("methodCallback"===t.type){const i=e.get(t.messageId);i&&i.callback&&i.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}}var d=i(62),c=i(136);function u(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const m=r.g?.75:1,l=.75,p=r.j?2:4,g=new Array(4).fill(void 0).map(()=>new o(new n.a));let k=-1;e.default=class{constructor(t,e,i,s={},n){this.id=t,this.container=e,this.animationData=i,this.params=s,this.onLoad=n,u(this,"imgSize",void 0),u(this,"key",void 0),u(this,"msPerFrame",void 0),u(this,"reduceFactor",void 0),u(this,"cacheModulo",void 0),u(this,"chunkSize",void 0),u(this,"workerIndex",void 0),u(this,"chunks",[]),u(this,"framesCount",void 0),u(this,"chunksCount",void 0),u(this,"canvas",document.createElement("canvas")),u(this,"ctx",this.canvas.getContext("2d")),u(this,"isAnimating",!1),u(this,"isWaiting",!0),u(this,"isOnLoadFired",!1),u(this,"isDestroyed",!1),u(this,"approxFrameIndex",0),u(this,"prevFrameIndex",-1),u(this,"stopFrameIndex",0),u(this,"speed",1),u(this,"direction",1),u(this,"lastRenderAt",void 0),this.initContainer(),this.initConfig(),this.initRenderer()}isPlaying(){return this.isAnimating||this.isWaiting}play(){this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}pause(){this.isWaiting?this.stopFrameIndex=this.approxFrameIndex:this.isAnimating=!1;const t=this.getChunkIndex(this.approxFrameIndex);this.chunks=this.chunks.map((e,i)=>i===t?e:void 0)}goToAndPlay(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}goToAndStop(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(t/this.reduceFactor),this.direction=1,this.doPlay()}playSegment([t,e]){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(e/this.reduceFactor),this.direction=t{if(this.isDestroyed)return!1;if(!this.isAnimating&&this.isOnLoadFired)return!1;const t=Math.round(this.approxFrameIndex),e=this.getChunkIndex(t);if(!this.chunks[e])return this.requestChunk(e),this.isAnimating=!1,this.isWaiting=!0,!1;if(this.cacheModulo&&e%this.cacheModulo==0&&this.cleanupPrevChunk(e),this.requestNextChunk(e),t!==this.prevFrameIndex){const e=this.getFrame(t);if(!e)return this.isAnimating=!1,this.isWaiting=!0,!1;const i=new ImageData(new Uint8ClampedArray(e),this.imgSize,this.imgSize);this.ctx.putImageData(i,0,0),this.onLoad&&!this.isOnLoadFired&&(this.isOnLoadFired=!0,this.onLoad()),this.prevFrameIndex=t}const i=Date.now(),s=this.lastRenderAt?this.msPerFrame/(i-this.lastRenderAt):1,n=Math.min(1,this.direction*this.speed/s),r=Math.round(this.approxFrameIndex+n);if(this.lastRenderAt=i,n>0&&(t===this.framesCount-1||r>this.framesCount-1)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=0}else if(n<0&&(0===t||r<0)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=this.framesCount-1}else{if(void 0!==this.stopFrameIndex&&(t===this.stopFrameIndex||n>0&&r>this.stopFrameIndex||n<0&&r{Object.assign(h,{resolve:t,reject:e})});if("function"==typeof r.args[r.args.length-1]){const t=r.args.pop();h.callback=t,s.set(t,h)}return i.set(n,h),o.catch(()=>{}).finally(()=>{i.delete(n),h.callback&&s.delete(h.callback)}),e.postMessage(r),o}cancelCallback(t){t.isCanceled=!0;const{messageId:e}=this.requestStatesByCallback.get(t)||{};e&&this.worker.postMessage({type:"cancelProgress",messageId:e})}subscribe(){const{worker:t,requestStates:e}=this;t.addEventListener("message",({data:t})=>{if("methodResponse"===t.type){const i=e.get(t.messageId);i&&(t.error?i.reject(t.error):i.resolve(t.response))}else if("methodCallback"===t.type){const i=e.get(t.messageId);i&&i.callback&&i.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}}var d=i(62),c=i(136);function u(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const m=r.g?.75:1,l=.75,p=r.j?2:4,g=new Array(4).fill(void 0).map(()=>new o(new n.a));let k=-1;e.default=class{constructor(t,e,i,s={},n){this.id=t,this.container=e,this.animationData=i,this.params=s,this.onLoad=n,u(this,"imgSize",void 0),u(this,"key",void 0),u(this,"msPerFrame",void 0),u(this,"reduceFactor",void 0),u(this,"cacheModulo",void 0),u(this,"chunkSize",void 0),u(this,"workerIndex",void 0),u(this,"chunks",[]),u(this,"framesCount",void 0),u(this,"chunksCount",void 0),u(this,"canvas",document.createElement("canvas")),u(this,"ctx",this.canvas.getContext("2d")),u(this,"isAnimating",!1),u(this,"isWaiting",!0),u(this,"isOnLoadFired",!1),u(this,"isDestroyed",!1),u(this,"approxFrameIndex",0),u(this,"prevFrameIndex",-1),u(this,"stopFrameIndex",0),u(this,"speed",1),u(this,"direction",1),u(this,"lastRenderAt",void 0),this.initContainer(),this.initConfig(),this.initRenderer()}isPlaying(){return this.isAnimating||this.isWaiting}play(){this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}pause(){this.isWaiting?this.stopFrameIndex=this.approxFrameIndex:this.isAnimating=!1;const t=this.getChunkIndex(this.approxFrameIndex);this.chunks=this.chunks.map((e,i)=>i===t?e:void 0)}goToAndPlay(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}goToAndStop(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(t/this.reduceFactor),this.direction=1,this.doPlay()}playSegment([t,e]){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(e/this.reduceFactor),this.direction=t{if(this.isDestroyed)return!1;if(!this.isAnimating&&this.isOnLoadFired)return!1;const t=Math.round(this.approxFrameIndex),e=this.getChunkIndex(t);if(!this.chunks[e])return this.requestChunk(e),this.isAnimating=!1,this.isWaiting=!0,!1;if(this.cacheModulo&&e%this.cacheModulo==0&&this.cleanupPrevChunk(e),this.requestNextChunk(e),t!==this.prevFrameIndex){const e=this.getFrame(t);if(!e)return this.isAnimating=!1,this.isWaiting=!0,!1;const i=new ImageData(new Uint8ClampedArray(e),this.imgSize,this.imgSize);this.ctx.putImageData(i,0,0),this.onLoad&&!this.isOnLoadFired&&(this.isOnLoadFired=!0,this.onLoad()),this.prevFrameIndex=t}const i=Date.now(),s=this.lastRenderAt?this.msPerFrame/(i-this.lastRenderAt):1,n=Math.min(1,this.direction*this.speed/s),r=Math.round(this.approxFrameIndex+n);if(this.lastRenderAt=i,n>0&&(t===this.framesCount-1||r>this.framesCount-1)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=0}else if(n<0&&(0===t||r<0)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=this.framesCount-1}else{if(void 0!==this.stopFrameIndex&&(t===this.stopFrameIndex||n>0&&r>this.stopFrameIndex||n<0&&r();\n\n private requestStatesByCallback = new Map();\n\n constructor(private worker: Worker) {\n this.subscribe();\n }\n\n request(messageData: { name: string; args: any }) {\n const { worker, requestStates, requestStatesByCallback } = this;\n\n const messageId = generateIdFor(requestStates);\n const payload: CallMethodData = {\n type: 'callMethod',\n messageId,\n ...messageData,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[payload.args.length - 1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n }\n\n cancelCallback(progressCallback: CancellableCallback) {\n progressCallback.isCanceled = true;\n\n const { messageId } = this.requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n this.worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n }\n\n private subscribe() {\n const { worker, requestStates } = this;\n\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n }\n}\n","import Worker from 'worker-loader!./rlottie.worker';\n\nimport {\n DPR,\n IS_MOBILE_SCREEN,\n IS_SAFARI,\n} from '../../util/environment';\nimport WorkerConnector from '../../util/WorkerConnector';\nimport { animate } from '../../util/animation';\nimport cycleRestrict from '../../util/cycleRestrict';\n\ninterface Params {\n noLoop?: boolean;\n size?: number;\n quality?: number;\n isLowPriority?: boolean;\n}\n\ntype Frames = ArrayBuffer[];\ntype Chunks = (Frames | undefined)[];\n\n// TODO Consider removing chunks\nconst CHUNK_SIZE = 1;\nconst MAX_WORKERS = 4;\nconst HIGH_PRIORITY_QUALITY = IS_MOBILE_SCREEN ? 0.75 : 1;\nconst LOW_PRIORITY_QUALITY = 0.75;\nconst HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\nconst HIGH_PRIORITY_CACHE_MODULO = IS_SAFARI ? 2 : 4;\nconst LOW_PRIORITY_CACHE_MODULO = 0;\n\nconst workers = new Array(MAX_WORKERS).fill(undefined).map(() => new WorkerConnector(new Worker()));\nlet lastWorkerIndex = -1;\n\nclass RLottie {\n // Config\n\n private imgSize!: number;\n\n private key!: string;\n\n private msPerFrame!: number;\n\n private reduceFactor!: number;\n\n private cacheModulo!: number;\n\n private chunkSize!: number;\n\n private workerIndex!: number;\n\n private chunks: Chunks = [];\n\n private framesCount?: number;\n\n private chunksCount?: number;\n\n // Container\n\n private canvas = document.createElement('canvas');\n\n private ctx = this.canvas.getContext('2d')!;\n\n // State\n\n private isAnimating = false;\n\n private isWaiting = true;\n\n private isOnLoadFired = false;\n\n private isDestroyed = false;\n\n private approxFrameIndex = 0;\n\n private prevFrameIndex = -1;\n\n private stopFrameIndex? = 0;\n\n private speed = 1;\n\n private direction: 1 | -1 = 1;\n\n private lastRenderAt?: number;\n\n constructor(\n private id: string,\n private container: HTMLDivElement,\n private animationData: AnyLiteral,\n private params: Params = {},\n private onLoad?: () => void,\n ) {\n this.initContainer();\n this.initConfig();\n this.initRenderer();\n }\n\n isPlaying() {\n return this.isAnimating || this.isWaiting;\n }\n\n play() {\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n pause() {\n if (this.isWaiting) {\n this.stopFrameIndex = this.approxFrameIndex;\n } else {\n this.isAnimating = false;\n }\n\n const currentChunkIndex = this.getChunkIndex(this.approxFrameIndex);\n this.chunks = this.chunks.map((chunk, i) => (i === currentChunkIndex ? chunk : undefined));\n }\n\n goToAndPlay(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n goToAndStop(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.direction = 1;\n this.doPlay();\n }\n\n playSegment([startFrameIndex, stopFrameIndex]: [number, number]) {\n this.approxFrameIndex = Math.floor(startFrameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(stopFrameIndex / this.reduceFactor);\n this.direction = startFrameIndex < stopFrameIndex ? 1 : -1;\n this.doPlay();\n }\n\n setSpeed(speed: number) {\n this.speed = speed;\n }\n\n destroy() {\n this.isDestroyed = true;\n this.pause();\n this.destroyRenderer();\n this.destroyContainer();\n }\n\n private initContainer() {\n if (!(this.container.parentNode instanceof HTMLElement)) {\n throw new Error('[RLottie] Container is not mounted');\n }\n\n let { size } = this.params;\n\n if (!size) {\n size = (\n this.container.offsetWidth\n || parseInt(this.container.style.width, 10)\n || this.container.parentNode.offsetWidth\n );\n\n if (!size) {\n throw new Error('[RLottie] Failed to detect width from container');\n }\n }\n\n this.canvas.style.width = `${size}px`;\n this.canvas.style.height = `${size}px`;\n\n const { isLowPriority, quality = isLowPriority ? LOW_PRIORITY_QUALITY : HIGH_PRIORITY_QUALITY } = this.params;\n // Reduced quality only looks acceptable on high DPR screens\n const imgSize = Math.round(size * Math.max(DPR * quality, 1));\n\n this.canvas.width = imgSize;\n this.canvas.height = imgSize;\n\n this.container.appendChild(this.canvas);\n\n this.imgSize = imgSize;\n }\n\n private initConfig() {\n this.key = `${this.id}_${this.imgSize}`;\n\n const { isLowPriority } = this.params;\n\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = this.animationData.fr || maxFps;\n this.reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n this.msPerFrame = 1000 / (sourceFps / this.reduceFactor);\n this.cacheModulo = isLowPriority ? LOW_PRIORITY_CACHE_MODULO : HIGH_PRIORITY_CACHE_MODULO;\n this.chunkSize = CHUNK_SIZE;\n }\n\n private destroyContainer() {\n this.canvas.remove();\n }\n\n private initRenderer() {\n this.workerIndex = cycleRestrict(MAX_WORKERS, ++lastWorkerIndex);\n\n workers[this.workerIndex].request({\n name: 'init',\n args: [\n this.key,\n this.animationData,\n this.imgSize,\n this.params.isLowPriority,\n this.reduceFactor,\n this.onRendererInit.bind(this),\n ],\n });\n }\n\n private destroyRenderer() {\n workers[this.workerIndex].request({\n name: 'destroy',\n args: [this.key],\n });\n }\n\n private onRendererInit(framesCount: number) {\n this.framesCount = framesCount;\n this.chunksCount = Math.ceil(framesCount / this.chunkSize);\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n\n private doPlay() {\n if (!this.framesCount) {\n return;\n }\n\n if (this.isDestroyed) {\n return;\n }\n\n if (this.isAnimating) {\n return;\n }\n\n if (!this.isWaiting) {\n this.lastRenderAt = undefined;\n }\n\n this.isAnimating = true;\n this.isWaiting = false;\n\n animate(() => {\n if (this.isDestroyed) {\n return false;\n }\n\n // Paused from outside\n if (!this.isAnimating && this.isOnLoadFired) {\n return false;\n }\n\n const frameIndex = Math.round(this.approxFrameIndex);\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n this.requestChunk(chunkIndex);\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n if (this.cacheModulo && chunkIndex % this.cacheModulo === 0) {\n this.cleanupPrevChunk(chunkIndex);\n }\n\n this.requestNextChunk(chunkIndex);\n\n if (frameIndex !== this.prevFrameIndex) {\n const frame = this.getFrame(frameIndex);\n if (!frame) {\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n const imageData = new ImageData(new Uint8ClampedArray(frame), this.imgSize, this.imgSize);\n this.ctx.putImageData(imageData, 0, 0);\n\n if (this.onLoad && !this.isOnLoadFired) {\n this.isOnLoadFired = true;\n this.onLoad();\n }\n\n this.prevFrameIndex = frameIndex;\n }\n\n const now = Date.now();\n const currentSpeed = this.lastRenderAt ? this.msPerFrame / (now - this.lastRenderAt) : 1;\n const delta = Math.min(1, (this.direction * this.speed) / currentSpeed);\n const expectedNextFrameIndex = Math.round(this.approxFrameIndex + delta);\n\n this.lastRenderAt = now;\n\n // Forward animation finished\n if (delta > 0 && (frameIndex === this.framesCount! - 1 || expectedNextFrameIndex > this.framesCount! - 1)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = 0;\n\n // Backward animation finished\n } else if (delta < 0 && (frameIndex === 0 || expectedNextFrameIndex < 0)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = this.framesCount! - 1;\n\n // Stop frame reached\n } else if (\n this.stopFrameIndex !== undefined\n && (frameIndex === this.stopFrameIndex\n || (\n (delta > 0 && expectedNextFrameIndex > this.stopFrameIndex)\n || (delta < 0 && expectedNextFrameIndex < this.stopFrameIndex)\n ))\n ) {\n this.stopFrameIndex = undefined;\n this.isAnimating = false;\n return false;\n\n // Preparing next frame\n } else {\n this.approxFrameIndex += delta;\n }\n\n const nextFrameIndex = Math.round(this.approxFrameIndex);\n\n if (!this.getFrame(nextFrameIndex)) {\n this.requestChunk(this.getChunkIndex(nextFrameIndex));\n this.isWaiting = true;\n this.isAnimating = false;\n return false;\n }\n\n return true;\n });\n }\n\n private getFrame(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const indexInChunk = this.getFrameIndexInChunk(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n return undefined;\n }\n\n return chunk[indexInChunk];\n }\n\n private getFrameIndexInChunk(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n return frameIndex - chunkIndex * this.chunkSize;\n }\n\n private getChunkIndex(frameIndex: number) {\n return Math.floor(frameIndex / this.chunkSize);\n }\n\n private requestChunk(chunkIndex: number) {\n if (this.chunks[chunkIndex]) {\n return;\n }\n\n this.chunks[chunkIndex] = [];\n\n const fromIndex = chunkIndex * this.chunkSize;\n const toIndex = Math.min(fromIndex + this.chunkSize - 1, this.framesCount! - 1);\n\n workers[this.workerIndex].request({\n name: 'renderFrames',\n args: [this.key, fromIndex, toIndex, this.onFrameLoad.bind(this)],\n });\n }\n\n private cleanupPrevChunk(chunkIndex: number) {\n if (this.chunksCount! < 3) {\n return;\n }\n\n const prevChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex - 1);\n this.chunks[prevChunkIndex] = undefined;\n }\n\n private requestNextChunk(chunkIndex: number) {\n if (this.chunksCount === 1) {\n return;\n }\n\n const nextChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex + 1);\n\n if (!this.chunks[nextChunkIndex]) {\n this.requestChunk(nextChunkIndex);\n }\n }\n\n private onFrameLoad(frameIndex: number, arrayBuffer: ArrayBuffer) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n // Frame can be skipped and chunk can be already cleaned up\n if (!chunk) {\n return;\n }\n\n chunk[this.getFrameIndexInChunk(frameIndex)] = arrayBuffer;\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n}\n\nexport default RLottie;\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"056df1c2528f8941f699.worker.js\");\n};"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///./src/util/cycleRestrict.ts","webpack:///./src/util/WorkerConnector.ts","webpack:///./src/lib/rlottie/RLottie.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["cycleRestrict","length","index","Math","floor","WorkerConnector","constructor","worker","Map","this","subscribe","request","messageData","requestStates","requestStatesByCallback","messageId","generateIdFor","payload","type","requestState","promise","Promise","resolve","reject","Object","assign","args","callback","pop","set","catch","finally","delete","postMessage","cancelCallback","progressCallback","isCanceled","get","addEventListener","data","error","response","callbackArgs","HIGH_PRIORITY_QUALITY","IS_MOBILE_SCREEN","LOW_PRIORITY_QUALITY","HIGH_PRIORITY_CACHE_MODULO","IS_SAFARI","workers","Array","fill","undefined","map","Worker","lastWorkerIndex","RLottie","id","container","animationData","params","onLoad","document","createElement","canvas","getContext","initContainer","initConfig","initRenderer","isPlaying","isAnimating","isWaiting","play","stopFrameIndex","direction","doPlay","pause","approxFrameIndex","currentChunkIndex","getChunkIndex","chunks","chunk","i","goToAndPlay","frameIndex","reduceFactor","goToAndStop","playSegment","startFrameIndex","setSpeed","speed","destroy","isDestroyed","destroyRenderer","destroyContainer","parentNode","HTMLElement","Error","size","offsetWidth","parseInt","style","width","height","isLowPriority","quality","imgSize","round","max","DPR","appendChild","key","maxFps","sourceFps","fr","msPerFrame","cacheModulo","chunkSize","remove","workerIndex","name","onRendererInit","bind","framesCount","chunksCount","ceil","lastRenderAt","animate","isOnLoadFired","chunkIndex","requestChunk","cleanupPrevChunk","requestNextChunk","prevFrameIndex","frame","getFrame","imageData","ImageData","Uint8ClampedArray","ctx","putImageData","now","Date","currentSpeed","delta","min","expectedNextFrameIndex","noLoop","nextFrameIndex","indexInChunk","getFrameIndexInChunk","fromIndex","toIndex","onFrameLoad","prevChunkIndex","nextChunkIndex","arrayBuffer","module","exports"],"mappings":"0FAAe,SAASA,EAAcC,EAAgBC,GACpD,OAAOA,EAAQC,KAAKC,MAAMF,EAAQD,GAAUA,EAD9C,mC,qMCqDe,MAAMI,EAKnBC,YAAoBC,GAAgB,KAAhBA,SAAgB,uBAJZ,IAAIC,K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.4122a010f2ae7876c212.js","sourcesContent":["export default function cycleRestrict(length: number, index: number) {\n return index - Math.floor(index / length) * length;\n}\n","import generateIdFor from './generateIdFor';\n\nexport interface CancellableCallback {\n (\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\ntype CallMethodData = {\n type: 'callMethod';\n messageId?: string;\n name: string;\n args: any;\n};\n\ntype OriginMessageData = CallMethodData | {\n type: 'cancelProgress';\n messageId: string;\n};\n\nexport interface OriginMessageEvent {\n data: OriginMessageData;\n}\n\nexport type WorkerMessageData = {\n type: 'methodResponse';\n messageId: string;\n response?: any;\n error?: { message: string };\n} | {\n type: 'methodCallback';\n messageId: string;\n callbackArgs: any[];\n} | {\n type: 'unhandledError';\n error?: { message: string };\n};\n\nexport interface WorkerMessageEvent {\n data: WorkerMessageData;\n}\n\ninterface RequestStates {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback: AnyToVoidFunction;\n}\n\n// TODO Replace `any` with proper generics\nexport default class WorkerConnector {\n private requestStates = new Map();\n\n private requestStatesByCallback = new Map();\n\n constructor(private worker: Worker) {\n this.subscribe();\n }\n\n request(messageData: { name: string; args: any }) {\n const { worker, requestStates, requestStatesByCallback } = this;\n\n const messageId = generateIdFor(requestStates);\n const payload: CallMethodData = {\n type: 'callMethod',\n messageId,\n ...messageData,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[payload.args.length - 1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n }\n\n cancelCallback(progressCallback: CancellableCallback) {\n progressCallback.isCanceled = true;\n\n const { messageId } = this.requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n this.worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n }\n\n private subscribe() {\n const { worker, requestStates } = this;\n\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n }\n}\n","import Worker from 'worker-loader!./rlottie.worker';\n\nimport {\n DPR,\n IS_MOBILE_SCREEN,\n IS_SAFARI,\n} from '../../util/environment';\nimport WorkerConnector from '../../util/WorkerConnector';\nimport { animate } from '../../util/animation';\nimport cycleRestrict from '../../util/cycleRestrict';\n\ninterface Params {\n noLoop?: boolean;\n size?: number;\n quality?: number;\n isLowPriority?: boolean;\n}\n\ntype Frames = ArrayBuffer[];\ntype Chunks = (Frames | undefined)[];\n\n// TODO Consider removing chunks\nconst CHUNK_SIZE = 1;\nconst MAX_WORKERS = 4;\nconst HIGH_PRIORITY_QUALITY = IS_MOBILE_SCREEN ? 0.75 : 1;\nconst LOW_PRIORITY_QUALITY = 0.75;\nconst HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\nconst HIGH_PRIORITY_CACHE_MODULO = IS_SAFARI ? 2 : 4;\nconst LOW_PRIORITY_CACHE_MODULO = 0;\n\nconst workers = new Array(MAX_WORKERS).fill(undefined).map(() => new WorkerConnector(new Worker()));\nlet lastWorkerIndex = -1;\n\nclass RLottie {\n // Config\n\n private imgSize!: number;\n\n private key!: string;\n\n private msPerFrame!: number;\n\n private reduceFactor!: number;\n\n private cacheModulo!: number;\n\n private chunkSize!: number;\n\n private workerIndex!: number;\n\n private chunks: Chunks = [];\n\n private framesCount?: number;\n\n private chunksCount?: number;\n\n // Container\n\n private canvas = document.createElement('canvas');\n\n private ctx = this.canvas.getContext('2d')!;\n\n // State\n\n private isAnimating = false;\n\n private isWaiting = true;\n\n private isOnLoadFired = false;\n\n private isDestroyed = false;\n\n private approxFrameIndex = 0;\n\n private prevFrameIndex = -1;\n\n private stopFrameIndex? = 0;\n\n private speed = 1;\n\n private direction: 1 | -1 = 1;\n\n private lastRenderAt?: number;\n\n constructor(\n private id: string,\n private container: HTMLDivElement,\n private animationData: AnyLiteral,\n private params: Params = {},\n private onLoad?: () => void,\n ) {\n this.initContainer();\n this.initConfig();\n this.initRenderer();\n }\n\n isPlaying() {\n return this.isAnimating || this.isWaiting;\n }\n\n play() {\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n pause() {\n if (this.isWaiting) {\n this.stopFrameIndex = this.approxFrameIndex;\n } else {\n this.isAnimating = false;\n }\n\n const currentChunkIndex = this.getChunkIndex(this.approxFrameIndex);\n this.chunks = this.chunks.map((chunk, i) => (i === currentChunkIndex ? chunk : undefined));\n }\n\n goToAndPlay(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n goToAndStop(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.direction = 1;\n this.doPlay();\n }\n\n playSegment([startFrameIndex, stopFrameIndex]: [number, number]) {\n this.approxFrameIndex = Math.floor(startFrameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(stopFrameIndex / this.reduceFactor);\n this.direction = startFrameIndex < stopFrameIndex ? 1 : -1;\n this.doPlay();\n }\n\n setSpeed(speed: number) {\n this.speed = speed;\n }\n\n destroy() {\n this.isDestroyed = true;\n this.pause();\n this.destroyRenderer();\n this.destroyContainer();\n }\n\n private initContainer() {\n if (!(this.container.parentNode instanceof HTMLElement)) {\n throw new Error('[RLottie] Container is not mounted');\n }\n\n let { size } = this.params;\n\n if (!size) {\n size = (\n this.container.offsetWidth\n || parseInt(this.container.style.width, 10)\n || this.container.parentNode.offsetWidth\n );\n\n if (!size) {\n throw new Error('[RLottie] Failed to detect width from container');\n }\n }\n\n this.canvas.style.width = `${size}px`;\n this.canvas.style.height = `${size}px`;\n\n const { isLowPriority, quality = isLowPriority ? LOW_PRIORITY_QUALITY : HIGH_PRIORITY_QUALITY } = this.params;\n // Reduced quality only looks acceptable on high DPR screens\n const imgSize = Math.round(size * Math.max(DPR * quality, 1));\n\n this.canvas.width = imgSize;\n this.canvas.height = imgSize;\n\n this.container.appendChild(this.canvas);\n\n this.imgSize = imgSize;\n }\n\n private initConfig() {\n this.key = `${this.id}_${this.imgSize}`;\n\n const { isLowPriority } = this.params;\n\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = this.animationData.fr || maxFps;\n this.reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n this.msPerFrame = 1000 / (sourceFps / this.reduceFactor);\n this.cacheModulo = isLowPriority ? LOW_PRIORITY_CACHE_MODULO : HIGH_PRIORITY_CACHE_MODULO;\n this.chunkSize = CHUNK_SIZE;\n }\n\n private destroyContainer() {\n this.canvas.remove();\n }\n\n private initRenderer() {\n this.workerIndex = cycleRestrict(MAX_WORKERS, ++lastWorkerIndex);\n\n workers[this.workerIndex].request({\n name: 'init',\n args: [\n this.key,\n this.animationData,\n this.imgSize,\n this.params.isLowPriority,\n this.reduceFactor,\n this.onRendererInit.bind(this),\n ],\n });\n }\n\n private destroyRenderer() {\n workers[this.workerIndex].request({\n name: 'destroy',\n args: [this.key],\n });\n }\n\n private onRendererInit(framesCount: number) {\n this.framesCount = framesCount;\n this.chunksCount = Math.ceil(framesCount / this.chunkSize);\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n\n private doPlay() {\n if (!this.framesCount) {\n return;\n }\n\n if (this.isDestroyed) {\n return;\n }\n\n if (this.isAnimating) {\n return;\n }\n\n if (!this.isWaiting) {\n this.lastRenderAt = undefined;\n }\n\n this.isAnimating = true;\n this.isWaiting = false;\n\n animate(() => {\n if (this.isDestroyed) {\n return false;\n }\n\n // Paused from outside\n if (!this.isAnimating && this.isOnLoadFired) {\n return false;\n }\n\n const frameIndex = Math.round(this.approxFrameIndex);\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n this.requestChunk(chunkIndex);\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n if (this.cacheModulo && chunkIndex % this.cacheModulo === 0) {\n this.cleanupPrevChunk(chunkIndex);\n }\n\n this.requestNextChunk(chunkIndex);\n\n if (frameIndex !== this.prevFrameIndex) {\n const frame = this.getFrame(frameIndex);\n if (!frame) {\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n const imageData = new ImageData(new Uint8ClampedArray(frame), this.imgSize, this.imgSize);\n this.ctx.putImageData(imageData, 0, 0);\n\n if (this.onLoad && !this.isOnLoadFired) {\n this.isOnLoadFired = true;\n this.onLoad();\n }\n\n this.prevFrameIndex = frameIndex;\n }\n\n const now = Date.now();\n const currentSpeed = this.lastRenderAt ? this.msPerFrame / (now - this.lastRenderAt) : 1;\n const delta = Math.min(1, (this.direction * this.speed) / currentSpeed);\n const expectedNextFrameIndex = Math.round(this.approxFrameIndex + delta);\n\n this.lastRenderAt = now;\n\n // Forward animation finished\n if (delta > 0 && (frameIndex === this.framesCount! - 1 || expectedNextFrameIndex > this.framesCount! - 1)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = 0;\n\n // Backward animation finished\n } else if (delta < 0 && (frameIndex === 0 || expectedNextFrameIndex < 0)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = this.framesCount! - 1;\n\n // Stop frame reached\n } else if (\n this.stopFrameIndex !== undefined\n && (frameIndex === this.stopFrameIndex\n || (\n (delta > 0 && expectedNextFrameIndex > this.stopFrameIndex)\n || (delta < 0 && expectedNextFrameIndex < this.stopFrameIndex)\n ))\n ) {\n this.stopFrameIndex = undefined;\n this.isAnimating = false;\n return false;\n\n // Preparing next frame\n } else {\n this.approxFrameIndex += delta;\n }\n\n const nextFrameIndex = Math.round(this.approxFrameIndex);\n\n if (!this.getFrame(nextFrameIndex)) {\n this.requestChunk(this.getChunkIndex(nextFrameIndex));\n this.isWaiting = true;\n this.isAnimating = false;\n return false;\n }\n\n return true;\n });\n }\n\n private getFrame(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const indexInChunk = this.getFrameIndexInChunk(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n return undefined;\n }\n\n return chunk[indexInChunk];\n }\n\n private getFrameIndexInChunk(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n return frameIndex - chunkIndex * this.chunkSize;\n }\n\n private getChunkIndex(frameIndex: number) {\n return Math.floor(frameIndex / this.chunkSize);\n }\n\n private requestChunk(chunkIndex: number) {\n if (this.chunks[chunkIndex]) {\n return;\n }\n\n this.chunks[chunkIndex] = [];\n\n const fromIndex = chunkIndex * this.chunkSize;\n const toIndex = Math.min(fromIndex + this.chunkSize - 1, this.framesCount! - 1);\n\n workers[this.workerIndex].request({\n name: 'renderFrames',\n args: [this.key, fromIndex, toIndex, this.onFrameLoad.bind(this)],\n });\n }\n\n private cleanupPrevChunk(chunkIndex: number) {\n if (this.chunksCount! < 3) {\n return;\n }\n\n const prevChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex - 1);\n this.chunks[prevChunkIndex] = undefined;\n }\n\n private requestNextChunk(chunkIndex: number) {\n if (this.chunksCount === 1) {\n return;\n }\n\n const nextChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex + 1);\n\n if (!this.chunks[nextChunkIndex]) {\n this.requestChunk(nextChunkIndex);\n }\n }\n\n private onFrameLoad(frameIndex: number, arrayBuffer: ArrayBuffer) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n // Frame can be skipped and chunk can be already cleaned up\n if (!chunk) {\n return;\n }\n\n chunk[this.getFrameIndexInChunk(frameIndex)] = arrayBuffer;\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n}\n\nexport default RLottie;\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"24a861ad9dabd3acfe82.worker.js\");\n};"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/index.html b/dist/index.html index 9ab4a4d9..7b3652d2 100644 --- a/dist/index.html +++ b/dist/index.html @@ -1 +1 @@ -Telegram
\ No newline at end of file +Telegram
\ No newline at end of file diff --git a/dist/main.a578e966316fd5919f1a.js b/dist/main.a06c93992fe858fca979.js similarity index 99% rename from dist/main.a578e966316fd5919f1a.js rename to dist/main.a06c93992fe858fca979.js index 16eb25f3..66cecd90 100644 --- a/dist/main.a578e966316fd5919f1a.js +++ b/dist/main.a06c93992fe858fca979.js @@ -1,2 +1,2 @@ -!function(e){function t(t){for(var n,r,d=t[0],o=t[1],c=0,a=[];c=0&&w(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),I[n].renderTimes.push(t),I[n].renderCount++}}catch(t){Object(c.a)(t),u=e.renderedValue}if(e.isMounted&&u===e.renderedValue)return e.$element;e.renderedValue=u;const d=O(u);return e.$element=y(e,[d]),e.$element}function C(e,t){return typeof e!=typeof t||(e.type!==t.type||(b(e)&&b(t)?e.value!==t.value:h(e)&&h(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!m(e)||!m(t))&&(e.componentInstance.Component!==t.componentInstance.Component||e.props.key!==t.props.key)))}function E(e){p(e)&&(m(e)?function(e){if(!e.isMounted)return;e.hooks.memos.byCursor.forEach(e=>{e.current=null}),e.hooks.effects.byCursor.forEach(({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}}),e.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach(e=>{e.cleanup=null,e.effect=null,e.dependencies=null}),e.hooks.state.byCursor.forEach(e=>{e.value=null,e.nextValue=null,e.setter=null}),e.hooks.memos.byCursor.forEach(e=>{e.dependencies=null}),e.hooks=null,e.$element=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(e)}(e.componentInstance):e.target&&(Object(a.b)(e.target),e.target=null),e.children.forEach(E))}function S(e){return j(e),e.isMounted=!0,e.$element}function M(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;j(e),e.$element!==t&&e.onUpdate()}function A(e){return m(e)?A(e.children[0]):e.target}function k(e,t){m(e)?k(e.children[0],t):e.target=t}function T(e){const{cursor:t,byCursor:n}=f.hooks.state;var d;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(d=f,e=>{n[t].nextValue!==e&&(n[t].nextValue="function"==typeof e?e(n[t].value):e,d.prepareForFrame&&d.forceUpdate||(d.prepareForFrame=Object(u.h)(()=>function e(t){t.isMounted&&(t.hooks.state.byCursor.forEach(e=>{e.value=e.nextValue}),t.prepareForFrame=Object(u.h)(()=>e(t)),t.forceUpdate=Object(u.i)(()=>M(t)))}(d)),d.forceUpdate=Object(u.i)(()=>M(d))),d.prepareForFrame(),d.forceUpdate(),r.r&&console.log("[Teact.useState]",d.name,d.Component&&d.Component.DEBUG_contentComponentName?"> "+d.Component.DEBUG_contentComponentName:"",`Forced update at cursor #${t}, next value: `,n[t].nextValue))})}),f.hooks.state.cursor++,[n[t].value,n[t].setter]}function N(e,t,n){const{cursor:r,byCursor:u}=f.hooks.effects,d=f,o=()=>{if(!d.isMounted)return;const{cleanup:e}=u[r];if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}u[r].cleanup=t()};void 0!==u[r]&&n&&u[r].dependencies?n.some((e,t)=>e!==u[r].dependencies[t])&&e(o):e(o),u[r]={effect:t,dependencies:n,cleanup:u[r]?u[r].cleanup:void 0},f.hooks.effects.cursor++}function P(e,t){return N(u.b,e,t)}function D(e,t){return N(u.d,e,t)}function L(e,t){const{cursor:n,byCursor:r}=f.hooks.memos;let{current:u}=r[n]||{};return(void 0===r[n]||t.some((e,t)=>e!==r[n].dependencies[t]))&&(u=e()),r[n]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function F(e,t){return L(()=>e,t)}function B(e){return L(()=>({current:e}),[])}function x(e,t=o.a,n=!1){return function(u){const d=B(u),c=B();return(!c.current||d.current&&!t(d.current,u))&&(r.p&&n&&console.log(`[Teact.memo] ${e.name}: Update is caused by:`,Object(o.b)(d.current,u).join(", ")),d.current=u,c.current=g(e,u)),c.current}}document.addEventListener("dblclick",()=>{console.log("COMPONENTS",Object(d.k)(Object.values(I),"renderCount","desc"))}),t.a={createElement:g,Fragment:s}},function(e,t,n){"use strict";n.d(t,"eb",(function(){return r})),n.d(t,"D",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"g",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"r",(function(){return a})),n.d(t,"E",(function(){return i})),n.d(t,"q",(function(){return s})),n.d(t,"nb",(function(){return f})),n.d(t,"H",(function(){return l})),n.d(t,"A",(function(){return b})),n.d(t,"B",(function(){return h})),n.d(t,"z",(function(){return m})),n.d(t,"C",(function(){return p})),n.d(t,"M",(function(){return g})),n.d(t,"N",(function(){return y})),n.d(t,"O",(function(){return v})),n.d(t,"P",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"F",(function(){return I})),n.d(t,"Y",(function(){return C})),n.d(t,"U",(function(){return E})),n.d(t,"V",(function(){return S})),n.d(t,"W",(function(){return M})),n.d(t,"i",(function(){return A})),n.d(t,"k",(function(){return k})),n.d(t,"j",(function(){return T})),n.d(t,"ob",(function(){return N})),n.d(t,"X",(function(){return P})),n.d(t,"y",(function(){return D})),n.d(t,"R",(function(){return L})),n.d(t,"Q",(function(){return F})),n.d(t,"fb",(function(){return B})),n.d(t,"Db",(function(){return x})),n.d(t,"a",(function(){return R})),n.d(t,"e",(function(){return U})),n.d(t,"d",(function(){return _})),n.d(t,"s",(function(){return G})),n.d(t,"u",(function(){return $})),n.d(t,"v",(function(){return W})),n.d(t,"w",(function(){return H})),n.d(t,"kb",(function(){return K})),n.d(t,"jb",(function(){return z})),n.d(t,"ab",(function(){return V})),n.d(t,"Z",(function(){return q})),n.d(t,"db",(function(){return J})),n.d(t,"cb",(function(){return Y})),n.d(t,"bb",(function(){return Q})),n.d(t,"J",(function(){return Z})),n.d(t,"c",(function(){return X})),n.d(t,"vb",(function(){return ee})),n.d(t,"wb",(function(){return te})),n.d(t,"qb",(function(){return ne})),n.d(t,"rb",(function(){return re})),n.d(t,"yb",(function(){return ue})),n.d(t,"ub",(function(){return de})),n.d(t,"zb",(function(){return oe})),n.d(t,"Ab",(function(){return ce})),n.d(t,"xb",(function(){return ae})),n.d(t,"Bb",(function(){return ie})),n.d(t,"sb",(function(){return se})),n.d(t,"tb",(function(){return fe})),n.d(t,"S",(function(){return le})),n.d(t,"T",(function(){return be})),n.d(t,"pb",(function(){return he})),n.d(t,"l",(function(){return me})),n.d(t,"gb",(function(){return pe})),n.d(t,"ib",(function(){return ge})),n.d(t,"hb",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"b",(function(){return we})),n.d(t,"h",(function(){return Oe})),n.d(t,"L",(function(){return Ie})),n.d(t,"K",(function(){return je})),n.d(t,"lb",(function(){return Ce})),n.d(t,"G",(function(){return Ee})),n.d(t,"Cb",(function(){return Se})),n.d(t,"x",(function(){return Me})),n.d(t,"I",(function(){return Ae})),n.d(t,"n",(function(){return ke})),n.d(t,"o",(function(){return Te})),n.d(t,"t",(function(){return Ne}));const r="Telegram",u=" [Inactive]",d="Telegram WebZ",o="e319dcb",c=!1,a=!1,i=!1,s="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",f="user_auth",l="GramJs:sessionId",b=!1,h="tt-global-state",m=30,p=5e3,g=!1,y="tt-media",v="tt-media-avatars",w="tt-media-progressive",O="tt-custom-bg",I="tt-lang-packs-v4",j=(new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight>=900),C=1,E=750,S=j?60:40,M=2*S,A=72,k=j?30:25,T=100,N=42,P=42,D=20,L=30,F=200,B=500,x=20,R=!1,U=2,_=U,G=16,$=1e4,W="editable-message-text",H="editable-message-text-modal",K=1440,z=1150,V=1275,q=925,J=600,Y=950,Q=450,Z=1e9,X=100,ee=13,te=11,ne=160,re=120,ue=64,de=48,oe=32,ce=64,ae=64,ie=160,se=140,fe=80,le="MEMOJI_STICKER",be=200,he=450,me="image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime",pe="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",ge=/^(?:https?:\/\/)?(?:t\.me\/)([\d\w_]+)(?:\/([\d]+))?$/gm,ye=/^(?:https?:\/\/)?(?:t\.me\/joinchat\/)([\d\w_]+)?$/gm,ve=777e3,we=0,Oe=1,Ie=10,je=5,Ce=2147483646,Ee=["android","ios","tdesktop","macos"],Se="TelegramTips",Me="https://bugs.telegram.org/?tag_ids=41&sort=time",Ae="#A2AF8E",ke="#0F0F0F",Te="#0a0a0a8c",Ne="rgba(90, 110, 70, 0.6)"},function(e,t,n){"use strict";n.d(t,"g",(function(){return v})),n.d(t,"e",(function(){return w})),n.d(t,"d",(function(){return O})),n.d(t,"b",(function(){return I})),n.d(t,"a",(function(){return j})),n.d(t,"f",(function(){return C})),n.d(t,"h",(function(){return E}));var r=n(0),u=n(1),d=n(26),o=n(28),c=n(9),a=n(24),i=n(3),s=n(21);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],m={},p=new Map;function g(){h.forEach(e=>e(l))}const y=Object(c.i)(g);function v(e,t=!1){"object"==typeof e&&e!==l&&(l=e,t?g():y())}function w(){return l}function O(){return m}function I(e,t){b[e]||(b[e]=[],m[e]=(t,n=!1)=>{!function(e,t,n){b[e]&&b[e].forEach(e=>{const r=e(l,m,t);r&&v(r,n)})}(e,t,n)}),b[e].push(t)}function j(e){h.push(e)}function C(e){const t=h.indexOf(e);-1!==t&&h.splice(t,1)}function E(e=(()=>({})),t=(()=>({}))){return n=>function u(c){u.DEBUG_contentComponentName=n.name;const[i]=Object(r.r)(Object(o.a)(p)),b=Object(d.a)();Object(r.n)(()=>()=>{p.delete(i)},[i]);let h=p.get(i);if(h||(h={mapStateToProps:e,mapReducersToProps:t,ownProps:c,areMappedPropsChanged:!1,forceUpdate:b,DEBUG_updates:0,DEBUG_componentName:n.name},p.set(i,h)),h.areMappedPropsChanged&&(h.areMappedPropsChanged=!1),!h.mappedProps||!Object(a.a)(h.ownProps,c)){h.ownProps=c;try{h.mappedProps={...e(l,c),...t(v,m)}}catch(e){Object(s.a)(e)}}return r.a.createElement(n,f({},h.mappedProps,c))}}u.p&&(window.getGlobal=w,document.addEventListener("dblclick",()=>{console.log("GLOBAL CONTAINERS",Object(i.k)(Object.values(p),"DEBUG_updates","desc"))}))},function(e,t,n){"use strict";function r(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function u(e,t){return Object.keys(e).reduce((n,r,u)=>(n[r]=t(e[r],r,u,e),n),{})}function d(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function o(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}function c(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter(e=>!n.has(e)))}function a(e,t,n="asc"){return e.sort((e,r)=>{if(Array.isArray(t)){const[u,d]=Array.isArray(n)?n:[n,n],[o,c]=t;let a,i;if("function"==typeof o?(a=o(e)||0,i=o(r)||0):"string"==typeof o&&(a=e[o]||0,i=r[o]||0),a!==i)return"asc"===u?a-i:i-a;{let t,n;return"function"==typeof c?(t=c(e)||0,n=c(r)||0):"string"==typeof c&&(t=e[c]||0,n=r[c]||0),"asc"===d?t-n:n-t}}let u,d;return"function"==typeof t?(u=t(e)||0,d=t(r)||0):"string"==typeof t&&(u=e[t]||0,d=r[t]||0),"asc"===n?u-d:d-u})}function i(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e),[])}function s(e){return Array.from(new Set(e))}function f(e){return e.filter(Boolean)}function l(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function b(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function h(e,t){return e.filter(e=>t.has(e))}function m(e,t){const n=[];for(let r=0;r(t[n]=p(e[n]),t),{})}function g(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,"c",(function(){return r})),n.d(t,"i",(function(){return u})),n.d(t,"l",(function(){return d})),n.d(t,"m",(function(){return o})),n.d(t,"j",(function(){return c})),n.d(t,"k",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"d",(function(){return p})),n.d(t,"g",(function(){return g}))},function(e,t,n){"use strict";n.d(t,"Y",(function(){return r.b})),n.d(t,"Z",(function(){return r.c})),n.d(t,"ab",(function(){return r.d})),n.d(t,"xb",(function(){return r.g})),n.d(t,"pb",(function(){return r.e})),n.d(t,"wb",(function(){return r.f})),n.d(t,"Eb",(function(){return r.h})),n.d(t,"X",(function(){return r.a})),n.d(t,"lb",(function(){return u.w})),n.d(t,"kb",(function(){return u.v})),n.d(t,"ib",(function(){return u.t})),n.d(t,"nb",(function(){return u.y})),n.d(t,"jb",(function(){return u.u})),n.d(t,"ob",(function(){return u.z})),n.d(t,"m",(function(){return u.j})),n.d(t,"U",(function(){return u.p})),n.d(t,"l",(function(){return u.i})),n.d(t,"g",(function(){return u.e})),n.d(t,"h",(function(){return u.f})),n.d(t,"f",(function(){return u.d})),n.d(t,"mb",(function(){return u.x})),n.d(t,"gb",(function(){return u.r})),n.d(t,"q",(function(){return u.m})),n.d(t,"yb",(function(){return u.A})),n.d(t,"e",(function(){return u.c})),n.d(t,"c",(function(){return u.a})),n.d(t,"K",(function(){return u.o})),n.d(t,"k",(function(){return u.h})),n.d(t,"j",(function(){return u.g})),n.d(t,"hb",(function(){return u.s})),n.d(t,"Cb",(function(){return u.D})),n.d(t,"d",(function(){return u.b})),n.d(t,"Bb",(function(){return u.C})),n.d(t,"Ab",(function(){return u.B})),n.d(t,"p",(function(){return u.l})),n.d(t,"o",(function(){return u.k})),n.d(t,"fb",(function(){return u.q})),n.d(t,"J",(function(){return u.n})),n.d(t,"Db",(function(){return u.E})),n.d(t,"A",(function(){return i})),n.d(t,"zb",(function(){return s})),n.d(t,"F",(function(){return f})),n.d(t,"N",(function(){return l})),n.d(t,"O",(function(){return b})),n.d(t,"x",(function(){return h})),n.d(t,"L",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"tb",(function(){return g})),n.d(t,"ub",(function(){return y})),n.d(t,"qb",(function(){return v})),n.d(t,"db",(function(){return w})),n.d(t,"vb",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"V",(function(){return j})),n.d(t,"W",(function(){return C})),n.d(t,"sb",(function(){return E})),n.d(t,"rb",(function(){return S})),n.d(t,"v",(function(){return k})),n.d(t,"cb",(function(){return T})),n.d(t,"G",(function(){return N})),n.d(t,"P",(function(){return P})),n.d(t,"I",(function(){return D})),n.d(t,"t",(function(){return L})),n.d(t,"u",(function(){return F})),n.d(t,"M",(function(){return B})),n.d(t,"y",(function(){return x})),n.d(t,"H",(function(){return R})),n.d(t,"z",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"R",(function(){return G})),n.d(t,"E",(function(){return $})),n.d(t,"D",(function(){return W})),n.d(t,"C",(function(){return K})),n.d(t,"B",(function(){return z})),n.d(t,"b",(function(){return q})),n.d(t,"i",(function(){return J})),n.d(t,"S",(function(){return Y})),n.d(t,"T",(function(){return Q})),n.d(t,"bb",(function(){return Z})),n.d(t,"s",(function(){return X})),n.d(t,"w",(function(){return ee})),n.d(t,"r",(function(){return te})),n.d(t,"a",(function(){return ne}));var r=n(30),u=n(31),d=n(5),o=n(1),c=n(65);const a=new RegExp(o.gb,"i");function i(e){const{chatId:t,id:n}=e;return`msg${t}-${n}`}function s(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:Number(t[1]),messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function l(e,t,n=!1){const{text:r,photo:u,video:d,audio:o,voice:c,document:a,sticker:i,contact:s,poll:f,invoice:l}=t.content;if(t.groupedId)return`${n?"":"🖼 "}${r?r.text:e("lng_in_dlg_album")}`;if(u)return`${n?"":"🖼 "}${r?r.text:e("AttachPhoto")}`;if(d)return`${n?"":"📹 "}${r?r.text:e(d.isGif?"AttachGif":"AttachVideo")}`;if(i)return`${i.emoji} ${e("AttachSticker")} `;if(o){return`${n?"":"🎧 "}${[o.title,o.performer].filter(Boolean).join(" — ")||r&&r.text||e("AttachMusic")}`}return c?`${n?"":"🎤 "}${r?r.text:e("AttachAudio")}`:a?`${n?"":"📎 "}${r?r.text:a.fileName}`:s?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:l?"Invoice":r?r.text:"The message is not supported on this version of Telegram"}function b(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:c,poll:a,webPage:i,contact:s,invoice:f}=e.content;return t?t.text:n||r||u||d||o||c||s||a||i||f?void 0:"The message is not supported on this version of Telegram"}function h(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:a,poll:i,webPage:s,contact:f}=e.content;return!!(n||u&&u.isRound)||!(!t||r||u||d||o||a||i||s||f)&&(Object(c.a)(t.text)||!1)}function m(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===h(e))return t.text}function p(e){const{text:t}=e.content;let n;if(t&&t.entities){let e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.TextUrl);if(e&&(n=e.url.match(a)),!n&&(e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.Url),e)){const{offset:r,length:u}=e;n=t.text.substring(r,r+u).match(a)}}if(!n&&t&&(n=t.text.match(a)),n)return{url:n[0],domain:n[3]}}function g(e){return e.isOutgoing}function y(e){return Boolean(e.replyToMessageId)}function v(e){return Boolean(e.forwardInfo)}function w(e){return!!e.content.action}function O(e){return e.chatId===o.mb&&E(e)}function I(e){return Boolean(e.senderId)&&e.senderId<0&&g(e)}function j(e,t){return t.id>0?Object(r.c)(t):Object(u.i)(e,t)}function C(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function E(e){return e.id>=o.J}function S(e){return e.content.action&&"historyClear"===e.content.action.type}var M=n(7),A=n(60);function k(e){return e.content}function T(e){return Boolean(N(e)||P(e)||x(e)||B(e)||function(e){return e.content.contact}(e)||R(e)||L(e)||F(e)||function(e){return e.content.voice}(e))}function N(e){return e.content.photo}function P(e){return e.content.video}function D(e){const{video:t}=e.content;return t&&t.isRound?t:void 0}function L(e){return e.content.action}function F(e){return e.content.audio}function B(e){return e.content.sticker}function x(e){return e.content.document}function R(e){return e.content.poll}function U(e){return e.content.invoice}function _(e){return e.content.webPage}function G(e){const t=_(e);return t?t.photo:void 0}function $(e){const t=function(e){const t=N(e)||P(e)||x(e)||B(e)||G(e);if(t)return t.thumbnail}(e);return t?t.dataUri:void 0}function W(e,t){const{photo:n,video:r,sticker:u,audio:d,voice:o,document:c}=e.content,a=G(e);if(!(n||r||u||a||d||o||c))return;const s=i(e);if(n||a)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return s+"?size=x";case"viewerPreview":return s+"?size=x";case"viewerFull":return s+"?size=z"}if(r)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return q(r)?H(r,s):s+"?size=z";case"viewerPreview":return s+"?size=m";case"viewerFull":return H(r,s);case"download":return s+"?download"}if(c)switch(t){case"micro":case"pictogram":case"inline":if(!Object(A.c)(c)||V(e))return;return s+"?size=m";default:return s}if(u)switch(t){case"micro":return;case"pictogram":return s+"?size=m";default:return s}if(d)switch(t){case"micro":case"pictogram":return;default:return H(d,s)}if(o)switch(t){case"micro":case"pictogram":return;default:return s}}function H(e,t){return M.i&&M.j?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function K(e,t){const{sticker:n,video:r,audio:u,voice:o}=e.content;return n&&"inline"===t&&n.isAnimated?d.ApiMediaFormat.Lottie:r&&M.i&&("viewerFull"===t||"inline"===t&&q(r))?d.ApiMediaFormat.Progressive:u||o?o&&!M.h?d.ApiMediaFormat.BlobUrl:d.ApiMediaFormat.Progressive:d.ApiMediaFormat.BlobUrl}function z(e){const{photo:t,video:n,webPage:r}=e.content;return t||r&&r.photo?`photo${e.date}.jpeg`:n?n.fileName:void 0}function V(e){const{photo:t,video:n,document:r}=e.content;return t&&t.blobUrl||n&&n.blobUrl||r&&r.previewBlobUrl}function q(e){return e.isGif||e.isRound||e.size<=10485760}function J(e,t,n=!1){const r=ee(e,t,"media");return n?r.reverse():r}function Y(e){return e.sizes.find(e=>"z"===e.type)||e.sizes.find(e=>"y"===e.type)||Q(e)}function Q(e){return e.sizes.find(e=>"x"===e.type)||e.sizes.find(e=>"m"===e.type)||e.sizes.find(e=>"s"===e.type)||e.thumbnail}function Z(e){if(e.width&&e.height)return e}function X(e,t,n=!1){const r=E(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ee(e,t,n){let r;switch(n){case"media":r=e=>{const t=P(e);return N(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=x;break;case"links":r=e=>_(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(a);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=F;break;default:return[]}return t.reduce((t,n)=>(e[n]&&r(e[n])&&t.push(n),t),[])}function te(e){const{audio:t,voice:n,video:r}=k(e),u=t||n||r;if(u)return u.duration}function ne(e,t){return`${e}_${t}`}n(61)},function(e,t,n){"use strict";var r=n(69);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat})),n.o(r,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return r.ApiMessageEntityTypes})),n.o(r,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return r.MAIN_THREAD_ID})),n.o(r,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return r.MESSAGE_DELETED}));var u=n(70);n.o(u,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return u.ApiMediaFormat})),n.o(u,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return u.ApiMessageEntityTypes})),n.o(u,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return u.MAIN_THREAD_ID})),n.o(u,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return u.MESSAGE_DELETED}));var d=n(71);n.d(t,"ApiMessageEntityTypes",(function(){return d.a})),n.d(t,"MAIN_THREAD_ID",(function(){return d.b})),n.d(t,"MESSAGE_DELETED",(function(){return d.c}));var o=n(72);n.o(o,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return o.ApiMediaFormat}));var c=n(73);n.d(t,"ApiMediaFormat",(function(){return c.a}));n(74),n(75),n(76)},function(e,t,n){"use strict";n.d(t,"T",(function(){return Le})),n.d(t,"nb",(function(){return Fe})),n.d(t,"W",(function(){return Be})),n.d(t,"Gb",(function(){return a})),n.d(t,"f",(function(){return f})),n.d(t,"o",(function(){return l})),n.d(t,"P",(function(){return b})),n.d(t,"O",(function(){return h})),n.d(t,"Ab",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"g",(function(){return g})),n.d(t,"L",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"M",(function(){return w})),n.d(t,"j",(function(){return O})),n.d(t,"i",(function(){return I})),n.d(t,"N",(function(){return j})),n.d(t,"h",(function(){return C})),n.d(t,"q",(function(){return E})),n.d(t,"y",(function(){return D})),n.d(t,"r",(function(){return L})),n.d(t,"m",(function(){return F})),n.d(t,"qb",(function(){return B})),n.d(t,"Y",(function(){return R})),n.d(t,"gb",(function(){return U})),n.d(t,"x",(function(){return _})),n.d(t,"Hb",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"ob",(function(){return W})),n.d(t,"rb",(function(){return H})),n.d(t,"mb",(function(){return K})),n.d(t,"C",(function(){return z})),n.d(t,"E",(function(){return V})),n.d(t,"B",(function(){return q})),n.d(t,"cb",(function(){return J})),n.d(t,"Cb",(function(){return Y})),n.d(t,"G",(function(){return Q})),n.d(t,"Db",(function(){return Z})),n.d(t,"Eb",(function(){return X})),n.d(t,"Bb",(function(){return ee})),n.d(t,"a",(function(){return te})),n.d(t,"X",(function(){return ne})),n.d(t,"k",(function(){return re})),n.d(t,"pb",(function(){return ue})),n.d(t,"D",(function(){return de})),n.d(t,"l",(function(){return oe})),n.d(t,"I",(function(){return ce})),n.d(t,"U",(function(){return ae})),n.d(t,"fb",(function(){return ie})),n.d(t,"tb",(function(){return se})),n.d(t,"K",(function(){return fe})),n.d(t,"b",(function(){return le})),n.d(t,"e",(function(){return be})),n.d(t,"Fb",(function(){return he})),n.d(t,"lb",(function(){return me})),n.d(t,"H",(function(){return pe})),n.d(t,"R",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"S",(function(){return ve})),n.d(t,"V",(function(){return we})),n.d(t,"J",(function(){return Oe})),n.d(t,"ab",(function(){return Ie})),n.d(t,"Q",(function(){return je})),n.d(t,"sb",(function(){return Ce})),n.d(t,"bb",(function(){return Ee})),n.d(t,"ub",(function(){return Se})),n.d(t,"vb",(function(){return Me})),n.d(t,"wb",(function(){return Ae})),n.d(t,"t",(function(){return xe})),n.d(t,"A",(function(){return ke})),n.d(t,"w",(function(){return Te})),n.d(t,"v",(function(){return Ne})),n.d(t,"Z",(function(){return Pe})),n.d(t,"u",(function(){return De})),n.d(t,"z",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"xb",(function(){return k})),n.d(t,"yb",(function(){return T})),n.d(t,"c",(function(){return N})),n.d(t,"F",(function(){return P})),n.d(t,"hb",(function(){return Re})),n.d(t,"ib",(function(){return Ue})),n.d(t,"kb",(function(){return _e})),n.d(t,"zb",(function(){return Ge})),n.d(t,"eb",(function(){return i})),n.d(t,"db",(function(){return s}));var r=n(19),u=n(7),d=n(5),o=n(1),c=n(4);function a(e,t){return e.users.byId[t]}function i(e){return e.settings.byKey}function s(e){return e.settings.notifyExceptions}function f(e,t){return e.chats.byId[t]}function l(e,t){const n=Object(c.U)(t);return!!n&&a(e,n)}function b(e,t){return t===e.currentUserId}function h(e,t){const n=l(e,t);return n&&Object(c.wb)(n)}function m(e){return Object.values(e.chats.byId).find(({isSupport:e})=>e)}function p(e,t){if(!Object(c.lb)(t.id)&&!Object(c.jb)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==o.Q?t.fullInfo.members.reduce((t,{userId:n})=>e.users.byId[n]&&Object(c.xb)(e.users.byId[n])&&n!==e.currentUserId?t+1:t,0):t.fullInfo.onlineCount}function g(e,t){const n=f(e,t),r=n&&Object(c.U)(n),u=r&&a(e,r);if(u&&Object(c.wb)(u))return u}function y(e,t){const n=f(e,t),r=g(e,t);if(!n||!r)return!1;if(n.lastMessage&&Object(c.rb)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:o}=u.threadsById[d.MAIN_THREAD_ID]||{};return o&&!o.length}function v(e){return Boolean(e.chats.listIds.active)}function w(e,t,n){const{listIds:r}=e.chats;if(n){const e=r[n];return Boolean(e&&e.includes(t))}return Object.values(r).some(e=>e&&e.includes(t))}function O(e,t){const n=f(e,t);if(n&&w(e,t))return n.folderId===o.h?"archived":"active"}function I(e,t){return e.chatFolders.byId[t]}function j(e,t,n=o.b){const{active:r,archived:u}=e.chats.orderedPinnedIds;if(n===o.b)return!!r&&r.includes(t);if(n===o.h)return!!u&&u.includes(t);const{byId:d}=e.chatFolders,{pinnedChatIds:c}=d[n]||{};return!!c&&c.includes(t)}function C(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find(e=>e.username&&e.username.toLowerCase()===n)}function E(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId;return t.reduce((t,r)=>{const u=n[r];return u&&u.unreadCount&&!Object(c.Cb)(u,i(e),s(e))?t+u.unreadCount:t},0)}var S=n(3);function M(e){return e.stickers.search}function A(e){return e.gifs.search}function k(e,t){return e.stickers.setsById[t]}function T(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach(({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))}),r}function N(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=t.replace("️","");return n.stickers.find(e=>e.emoji===t||e.emoji===r)}function P(e,t){return e.emojiKeywords[t]&&void 0!==e.emojiKeywords[t]?e.emojiKeywords[t]:void 0}function D(e){const{messageLists:t}=e.messages;if(t&&t.length)return t[t.length-1]}function L(e){const{chatId:t}=D(e)||{};return t?f(e,t):void 0}function F(e,t){const n=e.messages.byChatId[t];return n?n.byId:void 0}function B(e,t){const n=e.scheduledMessages.byChatId[t];return n?n.byId:void 0}function x(e,t,n,r){const u=e.messages.byChatId[t];if(!u)return;const d=u.threadsById[n];return d?d[r]:void 0}function R(e,t,n){return x(e,t,n,"listedIds")}function U(e,t,n){return x(e,t,n,"outlyingIds")}function _(e,t,n,r){switch(r){case"thread":return G(e,t,n);case"pinned":return $(e,t);case"scheduled":return W(e,t)}}function G(e,t,n){return x(e,t,n,"viewportIds")}function $(e,t){return x(e,t,d.MAIN_THREAD_ID,"pinnedIds")}function W(e,t){return x(e,t,d.MAIN_THREAD_ID,"scheduledIds")}function H(e,t,n){return x(e,t,n,"scrollOffset")}function K(e,t,n){return x(e,t,n,"replyingToId")}function z(e,t,n){return x(e,t,n,"editingId")}function V(e,t){return x(e,t,d.MAIN_THREAD_ID,"editingScheduledId")}function q(e,t,n){return x(e,t,n,"draft")}function J(e,t,n){return x(e,t,n,"noWebPage")}function Y(e,t,n){return x(e,t,n,"threadInfo")}function Q(e,t,n){return x(e,t,n,"firstMessageId")}function Z(e,t,n){if(n===d.MAIN_THREAD_ID)return f(e,t);const r=Y(e,t,n);return r?f(e,r.originChannelId||t):void 0}function X(e,t,n){if(n===d.MAIN_THREAD_ID)return;const r=Y(e,t,n);return r?r.topMessageId:void 0}function ee(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:u,replyToTopMessageId:d}=n;return u||d?Object.values(r.threadsById).find(e=>e.threadInfo&&(u&&u===e.threadInfo.topMessageId||d&&d===e.threadInfo.topMessageId)):void 0}function te(e,t,n){const r=D(e);if(!r)return!1;const{threadInfo:u}=ee(e,t,n)||{};return t===r.chatId&&(r.threadId===d.MAIN_THREAD_ID||u&&r.threadId===u.threadId)}function ne(e,t,n){const r=G(e,t,n);if(!r||!r.length)return!0;let u;if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n||!n.lastMessage)return!0;u=n.lastMessage.id}else{const r=Y(e,t,n);if(!r||!r.lastMessageId)return;u=r.lastMessageId}return u>=o.J&&!re(e,t,u)||r[r.length-1]>=u}function re(e,t,n){const r=F(e,t);return r?r[n]:void 0}function ue(e,t,n){const r=B(e,t);return r?r[n]:void 0}function de(e,t,n,r){if("scheduled"===r){const n=V(e,t);return n?ue(e,t,n):void 0}{const r=z(e,t,n);return r?re(e,t,r):void 0}}function oe(e,t){let n;for(const r of Object.values(e.messages.byChatId)){const{byId:e}=r;if(n=Object.values(e).find(e=>e.content.poll&&e.content.poll.id===t),n)break}return n}function ce(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function ae(e,t){const n=ce(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function ie(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=f(e,t.chatId)||{};return Object(c.sb)(t)||!n||n0?a(e,n):f(e,n)}function fe(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?f(e,n.fromChatId):n.senderUserId?a(e,n.senderUserId):void 0}function le(e,t,n){const r=f(e,t.chatId);if(!r||r.isRestricted)return{};const u=Object(c.lb)(r.id),d=b(e,t.chatId),o=Object(c.ib)(r),a=Object(c.nb)(r),i=Object(c.jb)(r),s=Object(c.vb)(t),l=Object(c.tb)(t),h=Object(c.db)(t),{content:m}=t,p=(d||Date.now()-1e3*t.date<1728e5)&&!(m.sticker||m.contact||m.poll||m.action||m.audio||m.video&&m.video.isRound)&&!Object(c.qb)(t)&&!t.viaBotId,g=Object(c.e)(r,n)&&!s,y=u||r.isCreator||!i&&!Object(c.yb)(r,"pinMessages")||Object(c.q)(r,"pinMessages");let v=!h&&y,w=!1;const O=$(e,r.id);v&&(w=Boolean(O&&O.includes(t.id)),v=!w);const I=u||l||o||r.isCreator||Object(c.q)(r,"deleteMessages"),j=I&&!s&&(u&&!d||o&&(l||Object(c.q)(r,"deleteMessages"))),C=!h&&p&&(l||i&&(r.isCreator||Object(c.q)(r,"editMessages"))),E=!h&&!s,S=Boolean(t.content.sticker),M=S&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some(({id:e})=>e===t.id)}(e,t.content.sticker),A=!h&&S&&!M,k=!h&&M,T=!h,N=!h&&(i||a),P=!h;return{noOptions:[g,C,v,w,I,j,E,A,k,T,N,P].every(e=>!e),canReply:g,canEdit:C,canPin:v,canUnpin:w,canDelete:I,canDeleteForAll:j,canForward:E,canFaveSticker:A,canUnfaveSticker:k,canCopy:T,canCopyLink:N,canSelect:P}}function be(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=D(e)||{},u=n&&F(e,n);if(!u||!t||!r)return{};const d=t.map(t=>u[t]&&le(e,u[t],r)).filter(Boolean);return{canDelete:d.every(e=>e.canDelete),canDeleteForAll:d.every(e=>e.canDeleteForAll)}}function he(e,t){const n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id];return n?n.progress:void 0}function me(e,t,n){if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?Object(c.sb)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=Y(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function pe(e,t,n){const r=f(e,t);if(n===d.MAIN_THREAD_ID){if(!r)return}else{const r=Y(e,t,n);if(!r||r.lastMessageId===r.lastReadInboxMessageId)return}const u=U(e,t,n),o=R(e,t,n),c=F(e,t);if(!c||!u&&!o)return;const a=me(e,t,n);if(a||!r||!r.isNotJoined){if(u){const e=a?u.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):u[0];if(e)return e}if(o){const e=a?o.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):o[0];if(e)return e}}}function ge(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ye(e,t){const n=Object.values(e.chats.byId).find(e=>Object(c.ob)(e)&&e.lastMessage&&e.lastMessage.id===t);if(n)return n.id;const{byChatId:r}=e.messages;return Number(Object.keys(r).find(n=>{const u=f(e,Number(n));return u&&Object(c.ob)(u)&&r[u.id].byId[t]}))}function ve(e){const{selectedMessages:t}=e;return Boolean(t)}function we(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function Oe(e,t,n){const r=F(e,t);if(r)return Object.values(r).filter(e=>e.groupedId===n&&e.forwardInfo).map(({forwardInfo:e})=>e.fromMessageId)}function Ie(e,t,n){const r=F(e,t);if(r)return Object.keys(r).map(Number).filter(e=>r[e].groupedId===n)}function je(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const u=Ie(e,t,n);return u&&u.every(e=>r.includes(e))}function Ce(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Ee(e,t){const n=f(e,t);if(!n)return;if(!h(e,n))return;const r=F(e,t),u=G(e,t,d.MAIN_THREAD_ID);if(!r||!u)return;const o=Object(S.g)(u,e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons)),c=Object(S.g)(u,e=>Boolean(r[e].shouldHideKeyboardButtons));return o&&c&&c>o?void 0:o?r[o]:void 0}function Se(e,t,n,r){const{shouldAutoDownloadMediaFromContacts:u,shouldAutoDownloadMediaInPrivateChats:d,shouldAutoDownloadMediaInGroups:o,shouldAutoDownloadMediaInChannels:a}=e.settings.byKey;return Boolean(d&&Object(c.lb)(n.id)||o&&Object(c.kb)(n)||a&&Object(c.jb)(n)||u&&r&&(r.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,r)))}function Me(e,t){const n=Object(c.P)(t);if(!n)return;const{shouldAutoPlayVideos:r,shouldAutoPlayGifs:u}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||u&&d}function Ae(e){return e.settings.byKey.shouldLoopStickers}function ke(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=Object(c.a)(t,n),u=e.localTextSearch.byChatThreadKey[r];return u&&u.isActive?u:void 0}function Te(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=D(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ne(e){const t=Te(e);if(t)return e.localMediaSearch.byChatId[t]}function Pe(e,t){return e.management.byChatId[t]}function De(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;if(Object(c.lb)(t))return"user";const r=f(e,t);return r?Object(c.kb)(r)?"group":"channel":void 0}function Le(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Fe(e){const{users:t,isChatInfoShown:n}=e,d=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),o=Boolean(!u.g&&ke(e)),c=function(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),a=void 0!==M(e).query,i=void 0!==A(e).query,{chatId:s}=D(e)||{},f=t.selectedId,l=v(e),b=Boolean(f&&l),h=Boolean(s&&l)&&n;return d?r.l.PollResults:o?r.l.Search:c?r.l.Management:a?r.l.StickerSearch:i?r.l.GifSearch:b?r.l.UserInfo:h?r.l.ChatInfo:void 0}function Be(e){return void 0!==Fe(e)}function xe(e){return e.globalSearch.query}function Re(e){return e.payment.messageId}function Ue(e){return e.payment.formId}function _e(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function Ge(e){return e.payment.stripeCredentials}},function(e,t,n){"use strict";n.d(t,"o",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"e",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"j",(function(){return a})),n.d(t,"l",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"m",(function(){return f})),n.d(t,"d",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"h",(function(){return m})),n.d(t,"c",(function(){return p})),n.d(t,"a",(function(){return g})),n.d(t,"n",(function(){return y})),n.d(t,"p",(function(){return w}));var r=n(1);const u=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="Mac OS":-1!==["iPhone","iPad","iPod"].indexOf(t)?n="iOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(t)?n="Windows":/Android/.test(e)?n="Android":/Linux/.test(t)&&(n="Linux"),n}(),d="Mac OS"===u,o="iOS"===u,c="Android"===u,a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=window.matchMedia("(pointer: coarse)").matches,s=window.innerWidth<=r.db||window.innerWidth<=r.cb&&window.innerHeight<=r.bb,f=navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext),l=(document.documentElement.style,u&&(d||o)),b="serviceWorker"in navigator,h=b,m=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),p=!r.E&&"filter"in(document.createElement("canvas").getContext("2d")||{}),g=window.devicePixelRatio||1,y=!0;let v;function w(){return Boolean(v)}new Promise(e=>{const t=new Image;t.src="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";const n=()=>{e(2===t.height)};t.onload=n,t.onerror=n}).then(e=>{v=e})},function(e,t,n){"use strict";t.a=(...e)=>e.filter(Boolean).join(" ")},function(e,t,n){"use strict";function r(e,t,n=!0,r=!0){let u;return(...d)=>{u?(clearTimeout(u),u=void 0):n&&e(...d),u=self.setTimeout(()=>{r&&e(...d),u=void 0},t)}}function u(e,t,n=!0){let r,u,d;return(...o)=>{u=!0,d=o,r||(n&&(u=!1,e(...d)),r=self.setInterval(()=>{if(!u)return self.clearInterval(r),void(r=void 0);u=!1,e(...d)},t))}}function d(e){return c(h,e)}function o(e){return c(m,e)}function c(e,t){let n,r=!1;return(...u)=>{n=u,r||(r=!0,e(()=>{r=!1,t(...n)}))}}function a(e){Promise.resolve().then(e)}function i(e){self.requestIdleCallback?self.requestIdleCallback(e):a(e)}n.d(t,"a",(function(){return r})),n.d(t,"g",(function(){return u})),n.d(t,"i",(function(){return d})),n.d(t,"h",(function(){return o})),n.d(t,"d",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return s})),n.d(t,"f",(function(){return f})),n.d(t,"b",(function(){return h}));const s=e=>new Promise(t=>{setTimeout(()=>t(),e)});function f(){return new Promise(e=>{h(e)})}let l,b;function h(e,t=!1){l?t?b.push(e):l.push(e):(l=t?[]:[e],b=t?[e]:[],requestAnimationFrame(()=>{const e=l,t=b;l=void 0,b=void 0,t.forEach(e=>e()),e.forEach(e=>e())}))}function m(e){h(e,!0)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));var r=n(81),u=n.n(r),d=n(1),o=n(28);let c;const a=new Map,i=new Map;function s(e,t){return c||(d.p&&console.log(">>> START LOAD WORKER"),c=new u.a,function(e){c.addEventListener("message",({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){const e=a.get(t.messageId);e&&e.callback&&e.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}(e)),b({type:"initApi",args:[t]})}function f(e,...t){if(c)return b({type:"callMethod",name:e,args:t});d.p&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&c.postMessage({type:"cancelProgress",messageId:t})}function b(e){const t=Object(o.a)(a),n={messageId:t,...e},r={messageId:t},u=new Promise((e,t)=>{Object.assign(r,{resolve:e,reject:t})});if("function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,i.set(e,r)}return a.set(t,r),u.catch(()=>{}).finally(()=>{a.delete(t),r.callback&&i.delete(r.callback)}),c.postMessage(n),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(1);let u;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(u||(u={}));const d={},o={};async function c(e,t){if(!d[e]){switch(e){case u.Auth:d[u.Auth]=n.e(5).then(n.bind(null,106));break;case u.Main:r.p&&console.log(">>> START LOAD MAIN BUNDLE"),d[u.Main]=Promise.all([n.e(0),n.e(4)]).then(n.bind(null,105));break;case u.Extra:d[u.Extra]=Promise.all([n.e(0),n.e(3)]).then(n.bind(null,104))}d[e].then(f)}const c=await d[e];return o[e]||(o[e]=c),a(e,t)}function a(e,t){const n=o[e];if(n)return n[t]}const i=[];function s(e){i.includes(e)||i.push(e)}function f(){i.forEach(e=>{e()})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"c",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"b",(function(){return c}));const r=self.caches;let u;async function d(e,t,n){if(r)try{const d=new Request(t),o=await r.open(e),c=await o.match(d);if(!c)return;switch(n){case u.Text:return await c.text();case u.Blob:{const e=await c.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=c.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case u.Json:return await c.json();default:return}}catch(e){return void console.warn(e)}}async function o(e,t,n){if(r)try{const u="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t),o=new Response(u),c=await r.open(e);return await c.put(d,o)}catch(e){return void console.warn(e)}}async function c(e){try{if(!r)return;return await r.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(u||(u={}))},function(e,t,n){"use strict";n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l}));var r=n(9);function u(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...r}=n;super(e,{type:t}),u(this,"name",void 0),Object.assign(this,r)}else super(e),u(this,"name",void 0);this.name=t}});function d(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let u=r.length;const d=new Uint8Array(u);for(;u--;)d[u]=r.charCodeAt(u);return new Blob([d],{type:n})}function o(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=e=>{const{result:r}=e.target||{};"string"==typeof r&&t(r),n(new Error("Failed to read blob"))},r.onerror=n,r.readAsDataURL(e)})}function c(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function a(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e})}function i(e){return new Promise((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e})}async function s(e){const t=await i(e);return Promise.race([Object(r.e)(2e3),new Promise((e,n)=>{t.onseeked=()=>{const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;n.getContext("2d").drawImage(t,0,0),e(n.toDataURL("image/jpeg"))},t.onerror=n,t.currentTime=Math.min(t.duration,1)})])}async function f(e){return(await fetch(e)).blob()}function l(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return v})),n.d(t,"b",(function(){return j})),n.d(t,"c",(function(){return C}));var r=n(1),u=n(12),d=n(10);var o=n(3),c=n.p+"en-extra.e73049da90714ecdae3233e8ffa74d39.json",a=n.p+"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json",i=n.p+"it-extra.78e5568451a888818c7e2209e05a9602.json",s=n.p+"pl-extra.38fd67a6c26e58f5c912568332c7c074.json",f=n.p+"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json",l=n(51),b=n(2);const h={en:c,es:a,it:i,pl:s,ru:f},m=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],p={en:e=>1!==e?6:2,ar:e=>0===e?1:1===e?2:2===e?3:e%100>=3&&e%100<=10?4:e%100>=11?5:6,ca:e=>1!==e?6:2,de:e=>1!==e?6:2,es:e=>1!==e?6:2,fa:e=>e>1?6:2,fr:e=>e>1?6:2,id:()=>0,it:e=>1!==e?6:2,ko:()=>0,ms:()=>0,nl:e=>1!==e?6:2,pl:e=>1===e?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,pt_BR:e=>e>1?6:2,ru:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,tr:e=>e>1?6:2,uk:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,uz:e=>e>1?6:2},g=new Map;let y;const{addCallback:v,removeCallback:w,runCallbacks:O}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach(e=>{e(...t)})},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let I;const j=(e,t,n)=>{if(void 0!==t){const r=g.get(`${e}_${t}_${n}`);if(r)return r}if(!y)return e;const r=y[e];if(!r)return e;const u=r["number"==typeof t?function(e){const t=I&&p[I]?p[I](e):0;return m[t]}(t):"value"];if(!u||!u.trim()){const t=e.split(".");return t[t.length-1]}if(void 0!==t){const r=function(e,t){return e.replace(/%\d?\$?[sdf@]/,String(t))}(u,"i"===n?Object(l.a)(t):t);return g.set(`${e}_${t}_${n}`,r),r}return u};async function C(e,t){if(y&&e===I)return void(t&&t());const n=await async function(e){const t=await u.c(r.F,e,u.a.Json);if(t)return t;const n=await Object(d.a)("fetchLangPack",{sourceLangPacks:r.G,langCode:e});if(n)return await u.d(r.F,e,n.langPack),n.langPack;return}(e);if(!n)return;if(h[e])try{const t=await fetch(h[e]),r=await t.json(),u=Object(o.i)(r,(e,t)=>({key:t,value:e}));Object.assign(n,u)}catch(e){r.p&&console.error(e)}g.clear(),I=e,y=n,document.documentElement.lang=e;const{languages:c}=Object(b.e)().settings.byKey,a=c?c.find(t=>t.langCode===e):void 0;j.isRtl=Boolean(a&&a.rtl),t&&t(),O(y)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d}));const r=/\uFE0F/g,u=String.fromCharCode(8205);function d(e){return e.indexOf(u)<0?e.replace(r,""):e}t.a=/(?:\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d\udc8f\ud83c[\udffb-\udfff]|\ud83d\udc91\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d\udc8f\udc91])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd4\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83d\ude36\u200d\ud83c\udf2b\ufe0f|\u2764\ufe0f\u200d\ud83d\udd25|\u2764\ufe0f\u200d\ud83e\ude79|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83d\ude2e\u200d\ud83d\udca8|\ud83d\ude35\u200d\ud83d\udcab|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udc8e\udc90\udc92-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g},function(e,t,n){"use strict";var r=n(0),u=n(20);n(95);t.a=Object(r.h)(({color:e="blue"})=>r.a.createElement("div",{className:"Loading"},r.a.createElement(u.a,{color:e,withBackground:"white"===e})))},function(e,t,n){"use strict";var r=n(0),u=n(11),d=n(26);t.a=(e,t,n=!1,o=!1)=>{const c=Object(u.c)(e,t),a=Object(d.a)();return o&&Object(u.b)(a),Object(r.n)(()=>{n||c||Object(u.d)(e,t).then(a)},[e,a,c,t,n]),c}},function(e,t,n){"use strict";n.d(t,"d",(function(){return o})),n.d(t,"e",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return d}));const r={},u=/(\d{1,3})(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,3})?/;var d="AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234".split("\n").map(e=>({id:e.substr(0,2),flag:e.substr(2,4),code:"+"+e.match(/\d+/)[0],name:e.split(/\d+/)[1],phoneFormat:function(e){if(!e)return u;const t=e[0];let n;if(!r[t]){const e=t.split("").map(Number);n=e.reduce((e,t,n)=>`${e}(\\d{1,${t}})${n>0?"?":""}`,""),r[t]=new RegExp(`${n}${"()?".repeat(5-e.length)}`)}return r[t]}(e.match(/\d+$/))}));function o(e){return d.find(t=>t.id===e)}function c(e){let t=e.replace(/[^\d+]+/g,"");t.startsWith("+")||(t="+"+t);const n=d.filter(e=>t.startsWith(e.code)).sort((e,t)=>e.code.length-t.code.length);return n[n.length-1]}function a(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.code.length-1);else if(e.startsWith("+"))return e;return n=n.replace(function(e){return e?e.phoneFormat:u}(t),(e,n,r,u,d,o)=>{const c=t&&"GB"===t.id?" ":"-";let a="";return n&&(a=""+n),r&&(a+=" "+r),u&&(a+=`${c}${u}`),d&&(a+=`${c}${d}`),o&&(a+=`${c}${o}`),a}),n}function i(e){const t=e.startsWith("+")?e:"+"+e,n=c(t);return n?`${n.code} ${a(t,n)}`:t}},function(e,t,n){"use strict";let r,u,d,o,c,a,i,s,f,l,b,h;n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"m",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"a",(function(){return s})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"g",(function(){return p})),function(e){e[e.Backwards=0]="Backwards",e[e.Forwards=1]="Forwards",e[e.Around=2]="Around"}(r||(r={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Static=2]="Static"}(u||(u={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.Language=3]="Language",e[e.General=4]="General",e[e.GeneralChatBackground=5]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=6]="GeneralChatBackgroundColor",e[e.Privacy=7]="Privacy",e[e.PrivacyPhoneNumber=8]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=9]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=10]="PrivacyProfilePhoto",e[e.PrivacyForwarding=11]="PrivacyForwarding",e[e.PrivacyGroupChats=12]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=13]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=14]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=15]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=16]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=17]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=18]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=19]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=20]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=21]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=22]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=23]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=24]="PrivacyBlockedUsers",e[e.Folders=25]="Folders",e[e.FoldersCreateFolder=26]="FoldersCreateFolder",e[e.FoldersEditFolder=27]="FoldersEditFolder",e[e.FoldersIncludedChats=28]="FoldersIncludedChats",e[e.FoldersExcludedChats=29]="FoldersExcludedChats",e[e.TwoFaDisabled=30]="TwoFaDisabled",e[e.TwoFaNewPassword=31]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=32]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=33]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=34]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=35]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=36]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=37]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=38]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=39]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=40]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=41]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=42]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=43]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=44]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=45]="TwoFaCongratulations"}(d||(d={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(o||(o={})),function(e){e[e.ChatList=0]="ChatList",e[e.Media=1]="Media",e[e.Links=2]="Links",e[e.Files=3]="Files",e[e.Music=4]="Music",e[e.Voice=5]="Voice"}(c||(c={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults"}(a||(a={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.MiddleHeaderAvatar=4]="MiddleHeaderAvatar",e[e.Album=5]="Album",e[e.ScheduledAlbum=6]="ScheduledAlbum",e[e.SearchResult=7]="SearchResult"}(i||(i={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(s||(s={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(f||(f={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(l||(l={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(b||(b={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(h||(h={}));const m="UPLOADING_WALLPAPER_SLUG";let p;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(p||(p={}))},function(e,t,n){"use strict";var r=n(0),u=n(8);n(91);t.a=({color:e="blue",withBackground:t})=>r.a.createElement("div",{className:Object(u.a)("Spinner",e,t&&"with-background")},r.a.createElement("div",null))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(1),u=n(9);window.addEventListener("error",c),window.addEventListener("unhandledrejection",c);const d=Date.now();let o=!1;function c(e){e.preventDefault(),a(e instanceof ErrorEvent?e.error:e.reason)}Object(u.g)(window.alert,1e3);function a(e){if(console.error(e),!o)return Date.now()-d<=5e3&&localStorage.getItem(r.B)?(localStorage.removeItem(r.B),o=!0,void window.location.reload()):void 0}},function(e,t,n){"use strict";(function(e){n.d(t,"f",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"e",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"d",(function(){return l}));var r=n(43),u=n(1),d=n(12);const o=[1,2,3,4,5];function c(e,t){const{mainDcId:n,keys:r,hashes:d}=e;localStorage.setItem(u.nb,JSON.stringify({dcID:n,id:t})),localStorage.setItem("dc",String(n)),Object.keys(r).map(Number).forEach(e=>{localStorage.setItem(`dc${e}_auth_key`,JSON.stringify(r[e]))}),Object.keys(d).map(Number).forEach(e=>{localStorage.setItem(`dc${e}_hash`,JSON.stringify(d[e]))})}function a(){[u.nb,"dc",...o.map(e=>`dc${e}_auth_key`),...o.map(e=>`dc${e}_hash`)].forEach(e=>{localStorage.removeItem(e)})}function i(){const e=localStorage.getItem(u.nb);if(!e)return;const{dcID:t}=JSON.parse(e),n={},r={};return o.forEach(e=>{try{const t=localStorage.getItem(`dc${e}_auth_key`);t&&(n[e]=JSON.parse(t));const u=localStorage.getItem(`dc${e}_hash`);u&&(r[e]=JSON.parse(u))}catch(e){u.p&&console.warn("Failed to load stored session",e)}}),Object.keys(n).length?{mainDcId:t,keys:n,hashes:r}:void 0}async function s(){const e=localStorage.getItem(u.H);if(!e)return;const t=await r.b("GramJs:"+e);try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load legacy session",e)}}async function f(){localStorage.removeItem(u.H);const e=await r.c();await Promise.all([d.b("GramJs"),...e.filter(e=>"string"==typeof e&&e.startsWith("GramJs:GramJs-session-")).map(e=>r.a(e))])}function l(){const t=e.env.TEST_SESSION;try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load test session",e)}}}).call(this,n(87))},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(0),u=n(15),d=n(1),o=n(7),c=n(66),a=n(8),i=n(77),s=n(58);const f=/^[\d\wа-яё]$/i,l=/(\*\*|__).+?\1/g;function b(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML]),[])}(e);case"hq_emoji":return u.a.lastIndex=0,h(e,"big","jsx");case"emoji":return u.a.lastIndex=0,h(e,"small","jsx");case"emoji_html":return u.a.lastIndex=0,h(e,"small","html");case"br":return m(e,"jsx");case"br_html":return m(e,"html");case"highlight":return d=e,o=n.highlight,d.reduce((e,t)=>{if("string"!=typeof t||!o)return[...e,t];const n=t.toLowerCase(),u=n.indexOf(o.toLowerCase()),d=n[u+o.length];if(u<0||d&&d.match(f))return[...e,t];const c=[];return c.push(t.substring(0,u)),c.push(r.a.createElement("span",{className:"matching-text-highlight"},t.substring(u,u+o.length))),c.push(t.substring(u+o.length)),[...e,...c]},[]);case"links":return function(e){return e.reduce((e,t)=>{if("string"!=typeof t)return[...e,t];const n=[...t.match(p)||[],...t.match(g)||[]];if(!n.length)return[...e,t];const u=[];let d=n.shift(),o=0;for(;d;){const e=t.indexOf(d,o);u.push(t.substring(o,e)),d.startsWith("@")?u.push(r.a.createElement(i.a,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),u.push(r.a.createElement(s.a,{text:d,url:d}))),o=e+d.length,d=n.shift()}return u.push(t.substring(o)),[...e,...u]},[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var d,o;return e},[e])}function h(e,t,n){return e.reduce((e,d)=>{if("string"!=typeof d)return[...e,d];const i=d.split(u.a),s=d.match(u.a)||[];return e.push(i[0]),s.reduce((e,d,s)=>{const f=Object(c.a)(Object(u.b)(d)),l=Object(a.a)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(o.d?r.a.createElement("span",{className:"font-emoji"},d):r.a.createElement("img",{className:l,src:`./img-apple-${"big"===t?"160":"64"}/${f}.png`,alt:d})),"html"===n&&e.push(o.d?d:`${d}`);const b=2*s+2;return i[b]&&e.push(i[b]),e},e)},[])}function m(e,t){return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce((e,n,u,d)=>{const o=n.trimLeft(),c=n.length-o.length;return e.push(String.fromCharCode(160).repeat(c)+o),u!==d.length-1&&e.push("jsx"===t?r.a.createElement("br",null):"
"),e},[])],[])}const p=new RegExp(d.gb,"ig"),g=/@[\w\d_-]+/gi;function y(e,t){return e.reduce((e,n)=>{if("string"!=typeof n)return[...e,n];const u=n.split(l),d=n.match(l)||[];return e.push(u[0]),d.reduce((e,n,d)=>{"jsx"===t?e.push(n.startsWith("**")?r.a.createElement("b",null,n.replace(/\*\*/g,"")):r.a.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const o=2*d+2;return u[o]&&e.push(u[o]),e},e)},[])}},function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;const n=Object.keys(e),r=n.length;if(r!==Object.keys(t).length)return!1;if(0===r)return!0;for(let u=0;ue[n]!==t[n])}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u}))},function(e,t,n){"use strict";var r=n(14),u=n(26),d=n(40);t.a=()=>{const e=Object(u.a)();return Object(d.a)(()=>r.a(e),[e]),r.b}},function(e,t,n){"use strict";var r=n(0);t.a=()=>{const[,e]=Object(r.r)(!1);return Object(r.m)(()=>{e(e=>!e)},[])}},function(e,t,n){"use strict";var r=n(0),u=n(8);n(89);t.a=({children:e,className:t,isRtl:n,onClick:d})=>{const o=Object(r.m)(e=>{e.preventDefault(),d(e)},[d]);return r.a.createElement("a",{href:"#",className:Object(u.a)("Link",t),dir:n?"rtl":"auto",onClick:d?o:void 0},e)}},function(e,t,n){"use strict";t.a=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},function(e,t,n){"use strict";n.d(t,"d",(function(){return p})),n.d(t,"c",(function(){return g})),n.d(t,"b",(function(){return y})),n.d(t,"a",(function(){return v}));var r=n(10),u=n(68),d=n(1),o=n(2),c=n(4),a=n(14),i=n(37),s=n(6),f=n(7);function l(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function b(){return!!f.k&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(d.p&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(d.p&&console.warn("[PUSH] Push messaging isn't supported."),!1):(d.p&&console.warn("[PUSH] Push notifications aren't supported."),!1))}async function h(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function m(e){const t=Object(o.e)(),n=Object(o.d)();if(e)try{const t=l(e);return await Object(r.a)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){d.p&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await Object(r.a)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function p(){if(!b())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await m(t)}async function g(){if(async function(){const[e]=await Promise.all([Object(r.a)("fetchNotificationSettings"),Object(r.a)("fetchNotificationExceptions")]);e&&Object(o.g)(Object(i.v)(Object(o.e)(),e))}(),!b())return void await h();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=Object(o.e)();return!t.push||!e||(l(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5)}(t)){await m(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=l(t);d.p&&console.log("[PUSH] Received push subscription: ",n),await Object(r.a)("registerDevice",n),Object(o.d)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?d.p&&console.warn("[PUSH] The user has blocked push notifications."):d.p&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await h())}}}function y({chat:e,message:t,isActiveChat:n}){if(!("Notification"in window?"denied"!==Notification.permission||(d.p&&console.warn("[PUSH] The user has blocked push notifications."),0):(d.p&&console.warn("[PUSH] This browser does not support desktop notification"),0)))return;if(!t.id)return;if(!function(e,t){const n=Object(o.e)();if(Object(c.Cb)(e,Object(s.eb)(n),Object(s.db)(n))||e.isNotJoined)return!1;if(t&&document.hasFocus())return!1;switch(e.type){case"chatTypePrivate":case"chatTypeSecret":return Boolean(n.settings.byKey.hasPrivateChatsNotifications);case"chatTypeBasicGroup":case"chatTypeSuperGroup":return Boolean(n.settings.byKey.hasGroupNotifications);case"chatTypeChannel":return Boolean(n.settings.byKey.hasBroadcastNotifications)}return!1}(e,n))return;const{title:r,body:i}=function(e,t){const n=Object(o.e)(),{senderId:r,replyToMessageId:d}=t,i=r?Object(s.Gb)(n,r):void 0,f=Object(c.t)(t),l=f&&d?Object(s.k)(n,e.id,d):void 0,{targetUserId:b,targetChatId:h}=f||{},m=b?Object(s.Gb)(n,b):void 0,p=Object(c.U)(e),g=p?Object(s.Gb)(n,p):void 0;let y;if(Object(c.db)(t)){const n=e&&(Object(c.jb)(e)||t.senderId===t.chatId)?e:i;y=Object(u.a)(a.b,t,n,m,l,h,{asPlain:!0})}else{const n=Object(c.J)(a.b,e.id,i),r=Object(c.N)(a.b,t);y=n?`${n}: ${r}`:r}return{title:Object(c.l)(a.b,e,g),body:y}}(e,t);if(b())navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"newMessageNotification",payload:{title:r,body:i,chatId:e.id,messageId:t.id}});else{const n=Object(o.d)(),u={body:i,icon:"icon-192x192.png",badge:"icon-192x192.png",tag:t.id.toString()};"vibrate"in navigator&&(u.vibrate=[200,100,200]);const d=new Notification(r,u);d.onclick=()=>{d.close(),n.focusMessage({chatId:e.id,messageId:t.id}),window.focus&&window.focus()}}}function v(){navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"h",(function(){return b})),n.d(t,"a",(function(){return h}));var r=n(1),u=n(36),d=n(3);const o=[1,8,5,2,7,4,6];function c(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function a(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function i(e,t){if(t.id===r.mb)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!t.status)return"";switch(t.status.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:n}=t.status;if(!n)return e("LastSeen.Offline");const r=new Date,d=new Date(1e3*n);if(d>=r)return e("LastSeen.JustNow");const o=new Date(r.getTime()-d.getTime());if(o.getTime()/1e3<60)return e("LastSeen.JustNow");if(o.getTime()/1e3<3600){return e("LastSeen.MinutesAgo",Math.floor(o.getTime()/1e3/60))}const c=new Date;if(c.setHours(0,0,0,0),d>c){if(o.getTime()/1e3<21600){return e("LastSeen.HoursAgo",Math.floor(o.getTime()/1e3/60/60))}return e("LastSeen.TodayAt",Object(u.h)(d))}const a=new Date;return a.setDate(r.getDate()-1),c.setHours(0,0,0,0),d>a?e("LastSeen.YesterdayAt",Object(u.h)(d)):e("LastSeen.AtDate",Object(u.b)(e,d))}case"userStatusOnline":return e("Online");case"userStatusRecently":return e("Lately");default:return}}function s(e){const{id:t,status:n,type:u}=e;return!!n&&(t!==r.mb&&("userStatusOnline"===n.type&&"userTypeBot"!==u))}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.mb)&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function l(e){return"userTypeBot"===e.type}function b(e,t,n){return Object(d.k)(e,e=>{const r=Date.now()/1e3;if(n&&n.includes(e))return r+172800-(n.length-n.indexOf(e));const u=t[e];if(!u||!u.status)return 0;if("userStatusOnline"===u.status.type)return u.status.expires;if("userStatusOffline"===u.status.type&&u.status.wasOnline)return u.status.wasOnline;switch(u.status.type){case"userStatusRecently":return r-86400;case"userStatusLastWeek":return r-604800;case"userStatusLastMonth":return r-18144e3;default:return 0}},"desc")}function h(e){const t=e?Math.abs(e.id)%7:0;return o[t]}},function(e,t,n){"use strict";n.d(t,"w",(function(){return c})),n.d(t,"v",(function(){return a})),n.d(t,"t",(function(){return i})),n.d(t,"y",(function(){return s})),n.d(t,"u",(function(){return f})),n.d(t,"z",(function(){return l})),n.d(t,"j",(function(){return b})),n.d(t,"p",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"e",(function(){return p})),n.d(t,"f",(function(){return g})),n.d(t,"d",(function(){return y})),n.d(t,"x",(function(){return v})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"A",(function(){return I})),n.d(t,"c",(function(){return j})),n.d(t,"a",(function(){return C})),n.d(t,"o",(function(){return E})),n.d(t,"h",(function(){return S})),n.d(t,"g",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"D",(function(){return k})),n.d(t,"b",(function(){return T})),n.d(t,"C",(function(){return N})),n.d(t,"B",(function(){return P})),n.d(t,"l",(function(){return D})),n.d(t,"k",(function(){return L})),n.d(t,"q",(function(){return F})),n.d(t,"n",(function(){return B})),n.d(t,"E",(function(){return x}));var r=n(5),u=n(1),d=n(3),o=n(30);function c(e){return e>0}function a(e){return i(e)||s(e)}function i(e){return"chatTypeBasicGroup"===e.type}function s(e){return"chatTypeSuperGroup"===e.type}function f(e){return"chatTypeChannel"===e.type}function l(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function b(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function h(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function m(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function p(e){if(e.fullInfo)return e.fullInfo.about}function g(e){const{username:t}=e,{inviteLink:n}=e.fullInfo||{};return n&&n.length?n:t?"t.me/"+t:""}function y(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function v(e){return!e.lastMessage}function w(e){return Boolean(e.adminRights)}function O(e,t){return!!e.adminRights&&e.adminRights[t]}function I(e,t){return Boolean(e.currentUserBannedRights&&e.currentUserBannedRights[t]||e.defaultBannedRights&&e.defaultBannedRights[t])}function j(e,t){return t!==r.MAIN_THREAD_ID||!(e.isRestricted||e.migratedTo||e.isNotJoined)&&(!!e.isCreator||(!!c(e.id)||(f(e)?O(e,"postMessages"):w(e)||!I(e,"sendMessages"))))}function C(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=w(e);return{canAttachMedia:n||!I(e,"sendMedia"),canAttachPolls:(n||!I(e,"sendPolls"))&&(!c(e.id)||t),canSendStickers:n||!I(e,"sendStickers"),canSendGifs:n||!I(e,"sendGifs"),canAttachEmbedLinks:n||!I(e,"embedLinks")}}function E(e){return e.currentUserBannedRights&&e.currentUserBannedRights.sendMessages?"You are not allowed to send messages in this chat.":e.defaultBannedRights&&e.defaultBannedRights.sendMessages?"Sending messages is not allowed in this chat.":void 0}function S(e){if(e&&e.fullInfo)return e.fullInfo.slowMode}function M(e){return Math.max(e.joinDate||0,e.lastMessage?e.lastMessage.date:0)}function A(e){return e.folderId===u.h}function k(e,t,n){return!(n&&n[e.id]&&!n[e.id].isMuted)&&(e.isMuted||c(e.id)&&!t.hasPrivateChatsNotifications||f(e)&&!t.hasBroadcastNotifications||a(e)&&!t.hasGroupNotifications)}function T(e){return i(e)||(s(e)||f(e))&&e.isCreator}function N(e,t,n,r,u,d){const o=n.excludedChatIds?new Set(n.excludedChatIds):void 0,i=n.excludedChatIds?new Set(n.includedChatIds):void 0,s=n.excludedChatIds?new Set(n.pinnedChatIds):void 0;return[(d||Object.keys(e).map(Number)).filter(d=>function(e,t,n,r,u,d,o,i){if(d&&d.has(e.id))return!1;if(o&&o.has(e.id))return!0;if(i&&i.has(e.id))return!0;if(A(e)&&t.excludeArchived)return!1;if(t.excludeMuted&&k(e,r,u))return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(c(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(a(e))return!!t.groups;if(f(e))return!!t.channels}return!1}(e[d],n,t,r,u,o,i,s)),n.pinnedChatIds]}function P(e,t,n,r="all"){function u(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(A(e))return!1;break;case"archived":if(!A(e))return!1}return!e.isRestricted&&!e.isNotJoined}const o=t.map(t=>e[t]).filter(u),c=new Set(t);return{pinnedChats:n?n.map(t=>e[t]).filter(u).filter(e=>c.has(e.id)):[],otherChats:Object(d.k)(n?o.filter(e=>!n.includes(e.id)):o,M,"desc")}}function D(e,t,n,r,u,d){const[o]=N(e,t,n,u,d,r),c=o.map(t=>e[t]).filter(e=>e&&e.lastMessage&&!e.isRestricted&&!e.isNotJoined);return{unreadDialogsCount:c.reduce((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e,0),hasActiveDialogs:c.some(e=>e.unreadMentionsCount||!k(e,u,d)&&(e.unreadCount||e.hasUnreadMark))}}function L(e,t,n,r,u,d,o){const{id:c,title:a,emoticon:i,description:s,pinnedChatIds:f,excludedChatIds:l,includedChatIds:b,excludeArchived:h,excludeMuted:m,excludeRead:p,...g}=r;if(Object.values(g).filter(Boolean).length>1||l&&l.length||b&&b.length){return e("Chats",function(e,t,n,r,u,d){const[o,c]=N(e,t,n,u,d,r),{pinnedChats:a,otherChats:i}=P(e,o,c,"folder");return a.length+i.length}(t,n,r,u,d,o))}return g.bots?e("FilterBots"):g.groups?e("FilterGroups"):g.channels?e("FilterChannels"):g.contacts?e("FilterContacts"):g.nonContacts?e("FilterNonContacts"):void 0}function F(e){return!!e&&e.id<0}function B(e,t,n){if(n&&!c(t))return n.isSelf?e("FromYou"):Object(o.b)(n)}function x(e,t,n=!1,r){return Object(d.k)(e,e=>{const u=t[e];if(!u)return 0;let d=0;return u.lastMessage&&(d+=u.lastMessage.date),n&&u.isVerified&&(d+=3e9),r&&r.includes(e)&&(d+=Date.now()+(r.length-r.indexOf(e))),d},"desc")}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(20),o=n(45);n(93);t.a=({ref:e,type:t="button",onClick:n,onContextMenu:c,onMouseDown:a,onMouseEnter:i,onMouseLeave:s,onFocus:f,children:l,size:b="default",color:h="primary",className:m,round:p,pill:g,fluid:y,isText:v,isLoading:w,ariaLabel:O,href:I,download:j,disabled:C,ripple:E,faded:S,tabIndex:M,isRtl:A})=>{let k=Object(r.q)(null);e&&(k=e);const[T,N]=Object(r.r)(!1),P=Object(u.a)("Button",m,b,h,p&&"round",g&&"pill",y&&"fluid",C&&"disabled",v&&"text",w&&"loading",E&&"has-ripple",S&&"faded",T&&"clicked"),D=Object(r.m)(e=>{!C&&n&&n(e),N(!0),setTimeout(()=>{N(!1)},400)},[C,n]),L=Object(r.m)(e=>{e.preventDefault(),!C&&a&&a(e)},[a,C]);return I?r.a.createElement("a",{ref:k,className:P,href:I,title:O,download:j,tabIndex:M,dir:A?"rtl":void 0},l,!C&&E&&r.a.createElement(o.a,null)):r.a.createElement("button",{ref:k,type:t,className:P,onClick:D,onContextMenu:c,onMouseDown:L,onMouseEnter:i&&!C?i:void 0,onMouseLeave:s&&!C?s:void 0,onFocus:f&&!C?f:void 0,"aria-label":O,title:O,tabIndex:M,dir:A?"rtl":void 0},w?r.a.createElement("div",null,r.a.createElement("span",{dir:A?"auto":void 0},"Please wait.."),r.a.createElement(d.a,{color:v?"blue":"white"})):l,!C&&E&&r.a.createElement(o.a,null))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return b}));var r=n(1);const u=new Set(["scroll","mouseenter","mouseleave"]),d={},o=new Map,c={};function a(e,t,n){const r=s(t,e);f(r,e)?function(e,t,n){c[e]||(c[e]=0,document.addEventListener(e,h));(function(e){d[e]||(d[e]=new Map);return d[e]})(e).set(t,n),function(e){const t=o.get(e);if(t)return t;const n=new Set;return o.set(e,n),n}(t).add(e),c[e]++}(r,e,n):e.addEventListener(r,n)}function i(e,t,n){const r=s(t,e);f(r,e)?l(r,e):e.removeEventListener(r,n)}function s(e,t){const n=e.replace(/^on/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function f(e,t){return!u.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function l(e,t){c[e]--,c[e]||document.removeEventListener(e,h),d[e].delete(t),o.get(t).delete(e)}function b(e){const t=o.get(e);t&&(t.forEach(t=>l(t,e)),o.delete(e))}function h(e){const t=d[e.type];if(t){let n=!1,r=e.target;const u=()=>{n=!0},d=()=>{e.preventDefault()},o=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?u:"preventDefault"===t?d:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(o),n))return;r=r.parentNode}}}r.p&&document.addEventListener("dblclick",()=>{console.log("DELEGATED EVENTS",{delegationRegistry:d,delegatedEventsByElement:o,documentEventCounters:c})})},function(e,t,n){"use strict";var r=n(0);t.a=(e=!1)=>{const[t,n]=Object(r.r)(e);return[t,Object(r.m)(()=>{n(!0)},[]),Object(r.m)(()=>{n(!1)},[])]}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=(e=!1,t,n=!1,d="fast",o=!1)=>{const[c,a]=Object(r.r)(!e),i=Object(r.q)(),[s,f]=Object(r.r)(e&&n);e?(a(!1),f(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(f(!1),c||i.current||(i.current=window.setTimeout(()=>{a(!0),t&&t(),i.current=void 0},o?0:350)));const l=Boolean(i.current),b=e||l;return{shouldRender:b,transitionClassNames:Object(u.a)(d&&"opacity-transition",d,(s&&!o||o&&e)&&"open",b&&"shown",l&&"closing")}}},function(e,t,n){"use strict";n.d(t,"j",(function(){return o})),n.d(t,"k",(function(){return c})),n.d(t,"n",(function(){return a})),n.d(t,"h",(function(){return s})),n.d(t,"g",(function(){return f})),n.d(t,"b",(function(){return l})),n.d(t,"f",(function(){return b})),n.d(t,"c",(function(){return h})),n.d(t,"d",(function(){return p})),n.d(t,"e",(function(){return g})),n.d(t,"i",(function(){return y})),n.d(t,"a",(function(){return v})),n.d(t,"l",(function(){return O})),n.d(t,"m",(function(){return I}));const r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"],d=u.map(e=>e.toLowerCase());function o(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function c(e){return o(e).getTime()}function a(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function i(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function s(e){const t="number"==typeof e?new Date(e):e;return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function f(e,t){const n="number"==typeof t?new Date(t):t,u=o(new Date);if(n>=u)return s(n);const d=new Date(u);if(d.setDate(u.getDate()-7),n>=d)return e("Weekday.Short"+r[n.getDay()]);const c=n.getFullYear()!==u.getFullYear(),a=e(c?"formatDateScheduleYear":"formatDateSchedule")||(c?"d MMM yyyy":"d MMM");return m(e,n,a)}function l(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return m(e,n,r)}function b(e,t,n=!1){const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return m(e,t,r)}function h(e,t,n=!1,u=!1){const d="number"==typeof t?new Date(t):t,c=o(new Date);if(!u){if(i(d)===i(c))return(n?j:C)(e("Weekday.Today"));const t=new Date(c);if(t.setDate(c.getDate()-1),i(d)===i(t))return(n?j:C)(e("Weekday.Yesterday"));const u=new Date(c),o=new Date(c);if(u.setDate(c.getDate()-7),o.setDate(c.getDate()+7),d>=u&&d<=o){const t=r[d.getDay()];return n?j(e("Weekday.Short"+t)):C(e("Weekday."+t))}}const a=d.getFullYear()!==c.getFullYear(),s=e(n?a?"formatDateScheduleYear":"formatDateSchedule":a?"chatFullDate":"chatDate")||"d MMMM yyyy";return(n?j:C)(m(e,d,s))}function m(e,t,n){const r=t.getDate(),d=t.getMonth();return n.replace("LLLL",e(u[d])).replace("MMMM",e("Month.Gen"+u[d])).replace("MMM",e("Month.Short"+u[d])).replace("MM",String(d+1).padStart(2,"0")).replace("dd",String(r).padStart(2,"0")).replace("d",String(r)).replace("yyyy",String(t.getFullYear()))}function p(e,t){const n="number"==typeof t?new Date(t):t;return`${h(e,n,!0)}, ${s(n)}`}function g(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%3600%60);let u="";return t>0?(u+=String(t).padStart(2,"0")+":",u+=String(n).padStart(2,"0")+":"):u+=String(n)+":",u+=String(r).padStart(2,"0"),u}function y(e){const t=[];let n=e%1e3;e-=n,n=Math.floor(n/10);const r=(e=Math.floor(e/1e3))%60;e-=r;const u=(e=Math.floor(e/60))%60;e-=u;const d=(e=Math.floor(e/60))%60;return d>0&&t.push(String(d).padStart(2,"0")),t.push(String(u).padStart(d>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function v(e){return e.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function O(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?r+"-":""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const u=e.split(" "),o=t?u[0]:u[1],c=(t?u[1]:u[0]).toLowerCase(),a=d.findIndex(e=>e.startsWith(c));return-1!==a&&w(Number(o),a)?`${String(a+1).padStart(2,"0")}-${String(o).padStart(2,"0")}`:void 0}function I(e){return e+86400}function j(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function C(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},function(e,t,n){"use strict";n.d(t,"r",(function(){return d})),n.d(t,"I",(function(){return o})),n.d(t,"s",(function(){return c})),n.d(t,"H",(function(){return a})),n.d(t,"M",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"K",(function(){return f})),n.d(t,"J",(function(){return l})),n.d(t,"N",(function(){return m})),n.d(t,"x",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"b",(function(){return w})),n.d(t,"L",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"j",(function(){return j})),n.d(t,"k",(function(){return C})),n.d(t,"V",(function(){return E})),n.d(t,"db",(function(){return S})),n.d(t,"g",(function(){return A})),n.d(t,"z",(function(){return k})),n.d(t,"kb",(function(){return T})),n.d(t,"lb",(function(){return N})),n.d(t,"u",(function(){return P})),n.d(t,"P",(function(){return D})),n.d(t,"O",(function(){return L})),n.d(t,"m",(function(){return F})),n.d(t,"G",(function(){return B})),n.d(t,"n",(function(){return x})),n.d(t,"ib",(function(){return R})),n.d(t,"hb",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"q",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"o",(function(){return W})),n.d(t,"y",(function(){return K})),n.d(t,"nb",(function(){return z})),n.d(t,"ob",(function(){return V})),n.d(t,"f",(function(){return q})),n.d(t,"fb",(function(){return J})),n.d(t,"l",(function(){return Y})),n.d(t,"R",(function(){return Z})),n.d(t,"S",(function(){return X})),n.d(t,"U",(function(){return ee})),n.d(t,"T",(function(){return te})),n.d(t,"Y",(function(){return ue})),n.d(t,"t",(function(){return de})),n.d(t,"Z",(function(){return oe})),n.d(t,"X",(function(){return ae})),n.d(t,"W",(function(){return ie})),n.d(t,"bb",(function(){return fe})),n.d(t,"ab",(function(){return le})),n.d(t,"v",(function(){return be})),n.d(t,"w",(function(){return he})),n.d(t,"e",(function(){return me})),n.d(t,"cb",(function(){return pe})),n.d(t,"a",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"gb",(function(){return we})),n.d(t,"E",(function(){return Oe})),n.d(t,"C",(function(){return Ie})),n.d(t,"A",(function(){return je})),n.d(t,"F",(function(){return Ce})),n.d(t,"B",(function(){return Ee})),n.d(t,"D",(function(){return Se})),n.d(t,"h",(function(){return Me})),n.d(t,"i",(function(){return Ae}));var r=n(1),u=n(3);function d(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function o(e,t,n){const{[t]:r}=e.chats.listIds,u=r&&r.length?n.filter(e=>!r.includes(e)):n;return r&&!u.length?e:d(e,t,[...r||[],...u])}function c(e,t){return{...e,chats:{...e.chats,byId:t}}}function a(e,t,n,r){const{byId:d}=e.chats,o=d[t],a=n.isMin&&o&&!o.isMin,i={...o,...a?Object(u.j)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...o.photos||[]]}};return i.id&&i.type?c(e,{...d,[t]:i}):e}function i(e,t){return Object.keys(t).forEach(n=>{e=a(e,Number(n),t[Number(n)])}),e}function s(e,t){const{byId:n}=e.chats;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=a(e,r,t[r]))}),e}function f(e,t,n){const u=n===r.h?"archived":"active";let d=e.chats.listIds;return Object.keys(d).forEach(e=>{const n=d[e]||[];e!==u||n.includes(t)?e!==u&&n.includes(t)&&(d={...d,[e]:n.filter(e=>e!==t)}):d={...d,[e]:[...n,t]}}),e=a(e={...e,chats:{...e.chats,listIds:d}},t,{folderId:n||void 0})}function l(e,t,n){const r="active"===t?"all":"archived";return{...e,chats:{...e.chats,...n.orderedPinnedIds&&{orderedPinnedIds:{...e.chats.orderedPinnedIds,[t]:n.orderedPinnedIds}},totalCount:{...e.chats.totalCount,[r]:n.totalChatCount},isFullyLoaded:{...e.chats.isFullyLoaded,[t]:!1}}}}var b=n(5),h=n(6);function m(e,t,n=b.MAIN_THREAD_ID,r="thread"){return{...e,messages:{...e.messages,messageLists:t?[{chatId:t,threadId:n,type:r}]:void 0}}}function p(e,t,n){return g(e,t,{byId:n})}function g(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function y(e,t,n,r,u){return function(e,t,n,r){const u=e.messages.byChatId[t];return g(e,t,{threadsById:{...u&&u.threadsById,[n]:{...u&&u.threadsById[n],...r}}})}(e,t,n,{[r]:u})}function v(e,t){const n=t.reduce((e,t)=>(e[t.chatId]||(e[t.chatId]={}),e[t.chatId][t.id]=t,e),{});return Object.keys(n).map(Number).forEach(t=>{e=w(e,t,n[t])}),e}function w(e,t,n){const r=Object(h.m)(e,t);return r&&Object.keys(n).every(e=>Boolean(r[Number(e)]))?e:p(e,t,{...n,...r})}function O(e,t,n,r){const u=Object(h.m)(e,t)||{},d={...u[n],...r};return d.id?p(e,t,{...u,[n]:d}):e}function I(e,t,n,r){const u=Object(h.qb)(e,t)||{},d={...u[n],...r};return d.id?P(e,t,{...u,[n]:d},void 0):e}function j(e,t,n){const r=Object(h.m)(e,t);if(!r)return e;const d=Object(u.j)(r,n),o=Object.values(Object(u.m)(r,n)).filter(({forwardInfo:e})=>e&&e.isLinkedChannelPost);if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach(r=>{let u=Object(h.Y)(e,t,r),d=Object(h.gb)(e,t,r),o=Object(h.Hb)(e,t,r),c=Object(h.jb)(e,t);n.forEach(e=>{u&&u.includes(e)&&(u=u.filter(t=>t!==e)),d&&d.includes(e)&&(d=d.filter(t=>t!==e)),o&&o.includes(e)&&(o=o.filter(t=>t!==e)),c&&c.includes(e)&&(c=c.filter(t=>t!==e))}),e=y(e,t,r,"listedIds",u),e=y(e,t,r,"outlyingIds",d),e=y(e,t,r,"viewportIds",o),e=y(e,t,r,"pinnedIds",c)}),o.length){const n=Object(h.y)(e),r=n&&n.chatId===t&&"thread"===n.type,u=n&&n.threadId;o.forEach(n=>{const{fromChatId:d,fromMessageId:o}=n.forwardInfo,c=Object(h.k)(e,d,o);r&&u===o&&(e=m(e,t)),c&&(e=O(e,d,o,{threadInfo:void 0}))})}return e=p(e,t,d)}function C(e,t,n){const r=Object(h.qb)(e,t);if(!r)return e;const d=Object(u.j)(r,n);let o=Object(h.ob)(e,t);return o&&(n.forEach(e=>{o.includes(e)&&(o=o.filter(t=>t!==e))}),e=y(e,t,b.MAIN_THREAD_ID,"scheduledIds",o)),e=P(e,t,d,void 0)}function E(e,t,n,r){const u=Object(h.Y)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"listedIds",M([...u||[],...d]))}function S(e,t,n,r){const u=Object(h.gb)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"outlyingIds",M([...u||[],...d]))}function M(e){return e.sort((e,t)=>e-t)}function A(e,t,n,u){const d=Object(h.Hb)(e,t,n)||[];if(d.includes(u))return e;return y(e,t,n,"viewportIds",M([...d.length{e=T(e,t.chatId,t.threadId,t)}),e}function P(e,t,n,r){return function(e,t,n){const r=e.scheduledMessages.byChatId[t]||{byId:{},hash:0};return{...e,scheduledMessages:{byChatId:{...e.scheduledMessages.byChatId,[t]:{...r,...n}}}}}(e,t,{byId:n,hash:r})}function D(e,t,n,r=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r}}}function L(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function F(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function B(e,t,n,r,d,o,c,a=!1){const{selectedMessages:i}=e;o&&(c=Object(h.ab)(e,t,o));const s=c||[d];if(!i)return F(e,t,s);const{messageIds:f}=i;let l;const b=s.filter(e=>!f.includes(e));if(b&&!b.length)l=f.filter(e=>!s.includes(e));else if(a&&f.length){const o=Object(h.x)(e,t,n,r),c=o.indexOf(f[f.length-1]),a=o.indexOf(d),i=Math.min(c,a),s=Math.max(c,a),b=o.slice(i,s+1);l=Object(u.o)([...f,...b])}else l=[...f,...b];return l.length?{...e,selectedMessages:{...i,messageIds:l}}:x(e)}function x(e){return{...e,selectedMessages:void 0}}function R(e,t,n,r,d){const o=r.map(t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t});return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...Object(u.c)(o,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:d}:{setIds:r.map(({id:e})=>e)}}}}}function U(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function _(e,t,n,r){const{results:u}=e.gifs.search;let d;if(t||!u)d=n;else{const e=new Set(u.map(e=>e.id));d=[...u,...n.filter(t=>!e.has(t.id))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:d}}}}function G(e,t){return{...e,animatedEmojis:t}}function $(e,t,n,r){const d=[...Object(h.yb)(e,t),...n||[]],o=Object(u.o)(d.map(({id:e})=>e)),c=Object(u.c)(d,"id"),a=o.map(e=>c[e]);return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:a,hash:r}}}}function W(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?$(e,t,n,r):e}var H=n(52);function K(e,t){return{...e,users:{...e.users,byId:t}}}function z(e,t,n){const{byId:r}=e.users,{hash:d,userIds:o}=e.contactList||{},c=r[t],a=n.isMin&&c&&!c.isMin,i={...c,...a?Object(u.j)(n,["isMin","accessHash"]):n};return i.id&&i.type?(i.isContact&&o&&!o.includes(t)&&(e={...e,contactList:{hash:d||0,userIds:[t,...o]}}),K(e,{...r,[t]:i})):e}function V(e,t){return Object.keys(t).map(Number).forEach(n=>{e=z(e,n,t[n])}),e}function q(e,t){const{byId:n}=e.users;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=z(e,r,t[r]))}),e}function J(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function Y(e,t){const{byId:n}=e.users,{hash:r,userIds:u}=e.contactList||{};return delete n[t],K(e={...e,contactList:{hash:r||0,userIds:u?u.filter(e=>e!==t):H.a}},n)}const Q=e=>`${e.chatId}_${e.id}`;function Z(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function X(e,t){return Z(e,{currentContent:t})}function ee(e,t,n,r,d){const{resultsByType:o}=e.globalSearch||{},c=t.reduce((e,t)=>(e[Q(t)]=t,e),{}),a=o&&o[r]?o[r].foundIds:void 0;if(void 0!==a&&Object.keys(c).every(e=>a.includes(Q(c[e]))))return te(e,{messages:!1});const i=a||[],s=t.map(e=>Q(e)),f=Array.prototype.concat(i,s),l=Object(u.a)(i,f)?i:f;return Z(e=te(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:d,foundIds:l}}})}function te(e,t){return Z(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ne=n(4);function re(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,u){const d=Object(ne.a)(t,n);return re(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:u})}function de(e,t,n,r,u,d){const o=Object(ne.a)(t,n);return re(e,o,{...e.localTextSearch.byChatThreadKey[o],results:{foundIds:r,totalCount:u,nextOffsetId:d}})}function oe(e,t,n,r,d,o){const c=Object(ne.a)(t,n),{results:a}=e.localTextSearch.byChatThreadKey[c]||{},i=a&&a.foundIds||[],s=se(Object(u.o)(Array.prototype.concat(i,r)));return de(e,t,n,Object(u.a)(i,s)?i:s,d,o)}function ce(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ae(e,t,n){return ce(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ie(e,t,n,r,d,o){const{resultsByType:c}=e.localMediaSearch.byChatId[t]||{},a=c&&c[n]?c[n].foundIds:[],i=se(Object(u.o)(Array.prototype.concat(a,r)));return function(e,t,n,r,u,d){return ce(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:u,nextOffsetId:d}}})}(e,t,n,Object(u.a)(a,i)?a:i,d,o)}function se(e){return e.sort((e,t)=>e-t)}function fe(e,t){return{...e,management:{...e.management,progress:t}}}function le(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function be(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function he(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function me(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function pe(e,t,n,r){switch(t){case"contact":return be(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return be(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return be(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function ge(e,t){return{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function ye(e,t){return{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter(e=>e!==t),totalCount:e.blocked.totalCount-1}}}function ve(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function we(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Oe(e,t){return{...e,payment:{...e.payment,formId:t}}}function Ie(e,t){return{...e,payment:{...e.payment,step:t}}}function je(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,description:u,photoUrl:d}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,description:u,photoUrl:d}}}}function Ce(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function Ee(e,t){return{...e,payment:{...e.payment,...t}}}function Se(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:u,text:d,title:o}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:u,text:d,title:o}}}}function Me(e){return{...e,payment:{}}}function Ae(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},function(e,t,n){"use strict";var r=n(0);t.a=function(e,t){const n=Object(r.q)(),{current:u}=n;return t&&void 0===e||(n.current=e),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r={states:[],isHistoryChangedByUser:!0,pushState(e){this.states.push(e),window.history.pushState(e,"")},back(){this.isHistoryChangedByUser=!1,window.history.back(),this.states.pop()}}},function(e,t,n){"use strict";var r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));function r(e,t=30){return!e||e.length<=t?e:e.substr(0,t)+"..."}},function(e){e.exports=JSON.parse('{"--color-primary":["#50A2E9","#8378DB"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#121212"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFEDF","#8378DB"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d4fcae","#7b71c6"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#4C90E6","#8378DB"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-borders":["#DADCE0","#100F10"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-links":["#52A1EF","#868DF6"],"--color-links-hover":["#2d8dec","#6b5fcc"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#1010109c"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#4DCD5E","#8378DB"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#DBF4CE","#6458bc"],"--color-reply-own-active":["#C8EBBC","#4F4A9F"],"--color-accent-own":["#4FAE4E","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#52A1EF","#FFFFFF"],"--color-code-own":["#3C7940","#FFFFFF"]}')},function(e,t,n){"use strict";function r(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}let u;function d(){return u||(u=function(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const u=r(n);return(e,n)=>u.then(r=>n(r.transaction(t,e).objectStore(t)))}("keyval-store","keyval")),u}function o(e,t=d()){return t("readonly",t=>r(t.get(e)))}function c(e,t=d()){return t("readwrite",t=>(t.delete(e),r(t.transaction)))}function a(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction)))}function i(e=d()){const t=[];return a(e,e=>t.push(e.key)).then(()=>t)}n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return i}))},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);n(98);t.a=e=>{const{icon:t,className:n,children:o,onClick:c,href:a,download:i,disabled:s,destructive:f,ariaLabel:l}=e,b=Object(d.a)(),h=Object(r.m)(e=>{if(s||!c)return e.stopPropagation(),void e.preventDefault();c(e)},[s,c]),m=Object(r.m)(e=>{if(13===e.keyCode||32===e.keyCode)return s||!c?(e.stopPropagation(),void e.preventDefault()):void c(e)},[s,c]),p=Object(u.a)("MenuItem",n,s&&"disabled",f&&"destructive"),g=r.a.createElement(r.a.Fragment,null,t&&r.a.createElement("i",{className:"icon-"+t,"data-char":t.startsWith("char-")?t.replace("char-",""):void 0}),o);return a?r.a.createElement("a",{tabIndex:0,className:p,href:a,download:i,"aria-label":l,title:l,target:a.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:b.isRtl?"rtl":void 0},g):r.a.createElement("div",{role:"button",tabIndex:0,className:p,onClick:h,onKeyDown:m,"aria-label":l,title:l,dir:b.isRtl?"rtl":void 0},g)}},function(e,t,n){"use strict";var r=n(0),u=n(9);n(92);t.a=Object(r.h)(()=>{const[e,t]=Object(r.r)([]),n=Object(r.p)(()=>Object(u.a)(()=>{t([])},700,!1),[]),d=Object(r.m)(r=>{if(0!==r.button)return;const u=r.currentTarget,d=u.getBoundingClientRect(),o=u.offsetWidth/2;t([...e,{x:r.clientX-d.x-o/2,y:r.clientY-d.y-o/2,size:o}]),requestAnimationFrame(()=>{n()})},[e,n]);return r.a.createElement("div",{className:"ripple-container",onMouseDown:d},e.map(({x:e,y:t,size:n})=>r.a.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"c",(function(){return l}));var r=n(84),u=n.n(r),d=n(7),o=n(13),c=n(9);let a,i;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function f(e,t){for(b();!i.wasmReady;)await Object(c.e)(2e3);const{result:n,width:r,height:u}=await function(e,t){return new Promise(n=>{i.requests=i.requests||new Map,i.requests.set(e,n),i.postMessage({id:e,blob:t})})}(e,t);if(r&&u)return function({result:e,width:t,height:n}){a||(a=document.createElement("canvas"));return new Promise(r=>{const u=new ImageData(e,t,n);a.width=t,a.height=n;a.getContext("2d").putImageData(u,0,0),a.toBlob(e=>{r(null!=e?e:void 0)},"image/png",1)})}({result:n,width:r,height:u})}async function l(e,t){if(Object(d.p)()||"data:image/webp"!==t.substr(0,15))return t;b();const n=await f(e,Object(o.d)(t));if(!n)throw new Error("Can't convert webp to png. Url: "+t);return Object(o.a)(n)}function b(){i||(i=new u.a,i.wasmReady=!1,i.onmessage=h)}function h(e){const{id:t}=e.data;switch(e.data.type){case"initialized":i.wasmReady=!0;break;case"result":if(i.requests.has(t)){const n=i.requests.get(t);i.requests.delete(t),n(e.data)}}}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);t.a=Object(r.h)(({ref:e,id:t,className:n,value:o,label:c,error:a,success:i,disabled:s,readOnly:f,placeholder:l,autoComplete:b,inputMode:h,maxLength:m,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w})=>{const O=Object(d.a)(),I=a||i||c,j=Object(u.a)("input-group",o&&"touched",a?"error":i&&"success",s&&"disabled",f&&"disabled",I&&"with-label",n);return r.a.createElement("div",{className:j,dir:O.isRtl?"rtl":void 0},r.a.createElement("input",{ref:e,className:"form-control",type:"text",id:t,dir:"auto",value:o||"",placeholder:l,maxLength:m,autoComplete:b,inputMode:h,disabled:s,readOnly:f,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w}),I&&r.a.createElement("label",{htmlFor:t},I))})},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25),o=n(20);n(94);t.a=Object(r.h)(({id:e,name:t,value:n,label:c,subLabel:a,checked:i,disabled:s,round:f,blocking:l,isLoading:b,onChange:h,onCheck:m})=>{const p=Object(d.a)(),g=Object(r.m)(e=>{h&&h(e),m&&m(e.currentTarget.checked)},[h,m]),y=Object(u.a)("Checkbox",s&&"disabled",f&&"round",b&&"loading",l&&"blocking");return r.a.createElement("label",{className:y,dir:p.isRtl?"rtl":void 0},r.a.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:i,disabled:s,onChange:g}),r.a.createElement("div",{className:"Checkbox-main"},r.a.createElement("span",{className:"label",dir:"auto"},c),a&&r.a.createElement("span",{className:"subLabel",dir:"auto"},a)),b&&r.a.createElement(o.a,null))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(56);function u(e){return Object(r.a)({onEsc:e})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));var r=n(0);let u,d=!1;const o=e=>{document.dispatchEvent(new Event("tt-event-heavy-animation-start")),d=!0,u&&(clearTimeout(u),u=void 0),u=window.setTimeout(()=>{d=!1,document.dispatchEvent(new Event("tt-event-heavy-animation-end")),u=void 0},e)};t.a=(e,t)=>{Object(r.n)(()=>(d&&e(),document.addEventListener("tt-event-heavy-animation-start",e),document.addEventListener("tt-event-heavy-animation-end",t),()=>{document.removeEventListener("tt-event-heavy-animation-end",t),document.removeEventListener("tt-event-heavy-animation-start",e)}),[t,e])}},function(e,t,n){"use strict";function r(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function d(e){return e<1e3?e:e<1e6?u(e/1e3)+"K":u(e/1e6)+"M"}function o(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map(e=>e.length&&e.match(/./u)[0].toUpperCase()).join("")}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return o}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r=[]},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));const r=/[^\wа-яё]+/;function u(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every(e=>n.some(t=>t.startsWith(e)))}},function(e,t,n){"use strict";var r=n(0),u=n(35),d=n(64),o=n(80),c=n(59),a=n(49),i=n(8),s=n(50);n(96);t.a=({ref:e,containerRef:t,isOpen:n,className:f,style:l,children:b,positionX:h="left",positionY:m="top",autoClose:p=!1,footer:g,noCloseOnBackdrop:y=!1,onCloseAnimationEnd:v,onClose:w,onMouseEnter:O,onMouseLeave:I,shouldSkipTransition:j})=>{let C=Object(r.q)(null);e&&(C=e);const E=t||C,{transitionClassNames:S}=Object(u.a)(n,v,j,void 0,j);Object(r.n)(()=>n&&w?Object(a.a)(w):void 0,[n,w]),Object(c.a)(([e])=>{void 0!==e&&Object(s.b)(200)},[n]);const M=Object(d.a)(C,n,p?w:void 0,void 0,!0);Object(o.a)(n,E,y?void 0:w);const A=Object(i.a)("bubble menu-container custom-scroll",m,h,g&&"with-footer",S);return r.a.createElement("div",{className:Object(i.a)("Menu no-selection",f),onKeyDown:n?M:void 0,onMouseEnter:O,onMouseLeave:n?I:void 0,style:l},n&&r.a.createElement("div",{className:"backdrop"}),r.a.createElement("div",{ref:C,className:A,style:`transform-origin: ${m} ${h}`,onClick:p?w:void 0},b,g&&r.a.createElement("div",{className:"footer"},g)))}},function(e,t,n){"use strict";n.d(t,"b",(function(){return y})),n.d(t,"c",(function(){return v})),n.d(t,"a",(function(){return w}));var r=n(5),u=n(1),d=n(10),o=n(12),c=n(13),a=n(7),i=n(82),s=n.n(i),f=n(83),l=n.n(f);async function b(e){const t=await new Response(e).arrayBuffer();return new Promise(e=>{const n=new Uint8Array(t);let r=new s.a,u=new l.a;r.onmessage=e=>{null===e.data?u.postMessage({command:"done"}):u.postMessage({command:"encode",buffers:e.data},e.data.map(({buffer:e})=>e))},u.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),r.terminate(),r=void 0,u.terminate(),u=void 0)},u.postMessage({command:"init",wavBitDepth:16,wavSampleRate:48e3}),r.postMessage({command:"init",decoderSampleRate:48e3,outputBufferSampleRate:48e3}),r.postMessage({command:"decode",pages:n},[n.buffer])})}var h=n(46);const m={[r.ApiMediaFormat.DataUri]:o.a.Text,[r.ApiMediaFormat.BlobUrl]:o.a.Blob,[r.ApiMediaFormat.Lottie]:o.a.Json,[r.ApiMediaFormat.Progressive]:void 0,[r.ApiMediaFormat.Stream]:void 0},p=new Map,g=new Map;function y(e,t,n){if(t===r.ApiMediaFormat.Progressive)return a.i?function(e){const t="./progressive/"+e;return p.set(e,t),Promise.resolve(t)}(e):y(e,r.ApiMediaFormat.BlobUrl,n);if(!g.has(e)){const i=async function(e,t,n){if(!u.M){const n=e.startsWith("avatar")?u.O:u.N,r=await o.c(n,e,m[t]);if(r){let t=r;if("audio/ogg"!==r.type||a.h||(t=await b(t)),"image/webp"===r.type&&!Object(a.p)()&&t){const n=await Object(h.b)(e,t);n&&(t=n)}const n=O(t);return p.set(e,n),n}}if(t===r.ApiMediaFormat.Stream){const r=new MediaSource,u=URL.createObjectURL(r);let o=!1;return r.addEventListener("sourceopen",()=>{if(o)return;o=!0;const u=r.addSourceBuffer("audio/mpeg");Object(d.a)("downloadMedia",{url:e,mediaFormat:t},(e,t)=>{n&&n(e),1===e&&r.endOfStream(),t&&u.appendBuffer(t)})}),p.set(e,u),u}const i=await Object(d.a)("downloadMedia",{url:e,mediaFormat:t},n);if(!i)throw new Error("Failed to fetch media");let{prepared:s,mimeType:f}=i;if("audio/ogg"===f&&!a.h){const e=await Object(c.e)(s);URL.revokeObjectURL(s);const t=await b(e);s=O(t),f=e.type}if("image/webp"===f&&!Object(a.p)()){const t=await Object(c.e)(s);URL.revokeObjectURL(s);const n=await Object(h.b)(e,t);n&&(s=O(n))}return p.set(e,s),s}(e,t,n).catch(e=>{u.p&&console.warn(e)}).finally(()=>{g.delete(e)});g.set(e,i)}return g.get(e)}function v(e){return p.get(e)}function w(e){Object(d.b)(e)}function O(e){return e instanceof Blob?URL.createObjectURL(e):e}a.i&&navigator.serviceWorker.addEventListener("message",async e=>{const{type:t,messageId:n,params:u}=e.data;if("requestPart"!==t)return;const o=await Object(d.a)("downloadMedia",{mediaFormat:r.ApiMediaFormat.Progressive,...u});if(!o)return;const{arrayBuffer:c,mimeType:a,fullSize:i}=o;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:c,mimeType:a,fullSize:i}},[c])})},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",ArrowLeft:"onLeft",ArrowRight:"onRight",Tab:"onTab"},u={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onLeft:[],onRight:[],onTab:[]};function d(e){return o()||document.addEventListener("keydown",c,!0),Object.keys(e).forEach(t=>{const n=e[t];if(!n)return;const r=u[t];r&&r.push(n)}),()=>{!function(e){Object.keys(e).forEach(t=>{const n=e[t],r=u[t];if(r){const e=r.findIndex(e=>e===n);-1!==e&&r.splice(e,1)}}),o()||document.removeEventListener("keydown",c,!1)}(e)}}function o(){return Object.values(u).some(e=>Boolean(e.length))}function c(e){const t=r[e.key];if(!t)return;const{length:n}=u[t];if(!n)return;e.stopPropagation();(0,u[t][n-1])(e)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i}));var r=n(9),u=n(1),d=n(7);const o=d.g&&s();let c=i();const a=Object(r.g)(()=>{c=i(),((c.width<=u.db||c.width<=u.cb&&c.height<=u.bb)!==d.g||d.g&&o!==s())&&window.location.reload()},250,!0);function i(){const e=.01*window.innerHeight;return document.documentElement.style.setProperty("--vh",e+"px"),{width:window.innerWidth,height:window.innerHeight}}function s(){return d.e?window.matchMedia("(orientation: landscape)").matches:window.matchMedia("screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)").matches}window.addEventListener("resize",a),window.addEventListener("orientationchange",a),t.a={get:()=>c}},function(e,t,n){"use strict";var r=n(0),u=n(2);const d=e=>{const t=[];let n=0;const r=e.length;let u;for(;n65535&&(u-=65536,t.push(String.fromCharCode(u>>>10&1023|55296)),u=56320|1023&u),t.push(String.fromCharCode(u))}return t.join("")};function o(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=36)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function c(e,t){const n=[],r=[],u=e.length;let c,a,i,s,f,l,b,h,m,p,g,y,v;for(c=128,i=0,s=72,f=e.lastIndexOf("-"),f<0&&(f=0),l=0;l=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(l))}for(b=f>0?f+1:0;b=u)throw RangeError("punycode_bad_input(1)");if(g=(w=e.charCodeAt(b++))-48<10?w-22:w-65<26?w-65:w-97<26?w-97:36,g>=36)throw RangeError("punycode_bad_input(2)");if(g>Math.floor((2147483647-i)/m))throw RangeError("punycode_overflow(1)");if(i+=g*m,y=p<=s?1:p>=s+26?26:p-s,gMath.floor(2147483647/(36-y)))throw RangeError("punycode_overflow(2)");m*=36-y}if(a=n.length+1,s=o(i-h,a,0===h),Math.floor(i/a)>2147483647-c)throw RangeError("punycode_overflow(3)");c+=Math.floor(i/a),i%=a,t&&r.splice(i,0,e.charCodeAt(b-1)-65<26),n.splice(i,0,c),i++}var w;if(t)for(i=0,v=n.length;iObject(s.l)(t,["toggleSafeLinkModal","openTelegramLink"]))(({url:e,text:t,className:n,children:u,isRtl:d,toggleSafeLinkModal:o,openTelegramLink:c})=>{const a=u||t,s=e!==a,h=Object(r.m)(t=>t.ctrlKey||t.altKey||t.shiftKey||t.metaKey||!e||!e.match(i.ib)&&!e.match(i.hb)?!s||(o({url:e}),t.preventDefault(),!1):(t.preventDefault(),c({url:e}),!1),[s,c,o,e]);if(!e)return;const m=Object(f.a)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.a.createElement("a",{href:l(e),title:b(e),target:"_blank",rel:"noopener noreferrer",className:m,onClick:h,dir:d?"rtl":"auto"},a)}))},function(e,t,n){"use strict";var r=n(0),u=n(38);t.a=(e,t)=>{const n=Object(u.a)(t);return Object(r.n)(()=>e(n||[]),t)}},function(e,t,n){"use strict";n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c}));function r(e){return e>536870912?(e/1073741824).toFixed(1)+" GB":e>524288?(e/1048576).toFixed(1)+" MB":(e/1024).toFixed(1)+" KB"}function u(e){const{fileName:t,mimeType:n}=e;return d(t,n)}function d(e,t){return e&&-1!==e.indexOf(".")?e.split(".").pop():t.split("/").pop()}function o(e){switch(e){case"apk":case"xls":case"xlsx":return"green";case"zip":case"rar":case"7z":case"tar":case"gz":case"ppt":case"pptx":return"orange";case"pdf":case"xps":return"red";default:return"default"}}function c(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return o}));const r={missing_payment_information:{field:"cardNumber",fieldError:"Incorrect card number"},invalid_number:{field:"cardNumber",fieldError:"Incorrect card number"},number:{field:"cardNumber",fieldError:"Incorrect card number"},exp_year:{field:"expiry",fieldError:"Incorrect year"},exp_month:{field:"expiry",fieldError:"Incorrect month"},invalid_expiry_year:{field:"expiry",fieldError:"Incorrect year"},invalid_expiry_month:{field:"expiry",fieldError:"Incorrect month"},cvc:{field:"cvv",fieldError:"Incorrect CVV"},invalid_cvc:{field:"cvv",fieldError:"Incorrect CVV"}};function u(e){const{message:t,code:n,param:u}=e,{field:d,fieldError:o,description:c}=u?r[u]:r[n];return{field:d,fieldError:o,description:c||t}}const d={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",fieldError:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",fieldError:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",fieldError:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",fieldError:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",fieldError:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",fieldError:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",fieldError:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",fieldError:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",fieldError:"Incorrect email"}};function o(e){return Object.values(e).reduce((e,t)=>{const n=d[t.message];return n&&(e={...e,[n.field]:n.fieldError}),e},{})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"a",(function(){return o}));var r=n(9);let u;function d(e,t){t||(u&&!u.isCancelled&&(u.isCancelled=!0),u=t={isCancelled:!1}),Object(r.b)(()=>{!t.isCancelled&&e()&&d(e,t)})}function o(e){Object(r.b)(()=>{e()&&o(e)})}},function(e,t,n){"use strict";var r=n(0),u=n(54);n(97);t.a=({trigger:e,className:t,children:n,positionX:d="left",positionY:o="top",footer:c,forceOpen:a,onOpen:i,onClose:s})=>{const f=Object(r.q)(null),l=Object(r.q)(null),[b,h]=Object(r.r)(!1);return r.a.createElement("div",{ref:l,className:"DropdownMenu "+(t||""),onKeyDown:e=>{const t=f.current;if(!b||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{h(!b),b?s&&s():i&&i()},isOpen:b}),r.a.createElement(u.a,{ref:f,containerRef:l,isOpen:b||!!a,className:t||"",positionX:d,positionY:o,footer:c,autoClose:!0,onClose:()=>{h(!1),s&&s()},shouldSkipTransition:a},n))}},function(e,t,n){"use strict";var r=n(0);t.a=(e,t,n,u,d)=>{const[o,c]=Object(r.r)(-1);Object(r.n)(()=>{c(-1);const n=e.current;t&&n&&!d&&(n.tabIndex=-1,n.focus())},[e,t,d]);return Object(r.m)(t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n(o);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,a=Array.from(u?r.querySelectorAll(u):r.children);let i=d&&a.indexOf(d)||o;if(38===t.keyCode&&i>0)i--;else if(40===t.keyCode&&i{if(e.length>24)return!1;if(!Boolean(e.match(u)))return!1;let t=0;for(;r.a.exec(e);)if(t++,t>3)return r.a.lastIndex=0,!1;return t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return o}));const r=["female_sign","male_sign","medical_symbol"];function u(e){const t=e.split("-").map(e=>parseInt(e,16));return String.fromCodePoint(...t)}function d(e){let t;if(1===e.length)t=e.charCodeAt(0).toString(16).padStart(4,"0");else{const n=[];for(let t=0;t=55296&&e.charCodeAt(t)<=56319?e.charCodeAt(t+1)>=56320&&e.charCodeAt(t+1)<=57343&&n.push(1024*(e.charCodeAt(t)-55296)+(e.charCodeAt(t+1)-56320)+65536):(e.charCodeAt(t)<55296||e.charCodeAt(t)>57343)&&n.push(e.charCodeAt(t));t=n.map(e=>e.toString(16).padStart(4,"0")).join("-")}return t}function o(e){const t={categories:[],emojis:{}};for(let n=0;n{void 0!==e.props[r]&&void 0===t.props[r]&&g(n,r,e.props[r])}),u.forEach(r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?p(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(g(e,t,n),p(e,t,r))}(n,r,e.props[r],t.props[r]))})}(t,n,Object(r.b)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const u=new Set(t.children.map(e=>{const t="props"in e&&e.props.key;return d.p&&Object(r.f)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t}));let o=0;const c=e.children.reduce((e,r,d)=>{let c="props"in r?r.props.key:void 0;if(c&&!u.has(c))return f(n,r,void 0,t,-1),e;if(!c){const u=t.children[d],o=u&&"props"in u?u.props.key:void 0;if(!u||o)return f(n,r,void 0,t,-1),e;c="__indexKey#"+d}return e[c]={$element:r,index:o++,order:"props"in r?r.props.teactOrderKey:void 0},e},{});let a,i,s=[],l=0;t.children.forEach((e,r)=>{const u="props"in e?e.props.key:"__indexKey#"+r,d=c[u];if(!d)return a||(a=[],i=r),void a.push(e);a&&(s=s.concat(m(a,i,n,t)),i=void 0,a=void 0);const o="props"in e?e.props.teactOrderKey:void 0,b=d.index!==l&&d.order!==o,h=b&&l>d.index;b&&!h||l++,s.push(f(n,d.$element,e,t,r,{forceIndex:!0,...b&&{moveDirection:h?"down":"up"}}))}),a&&(s=s.concat(m(a,i,n,t)));return s}(e,t,n);const u=Math.max(e.children.length,t.children.length),o=[],c=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:c}:void 0);u&&o.push(u)}c&&n.appendChild(c);return o}(t,n,u?e:Object(r.b)(t))}}return n}function l(e,t,n,u){if(!Object(r.d)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){b(e=Object(r.i)(d),t,n,u);const o=e.children[0];Object(r.d)(o)&&(e.children=[l(o,e,0,u)]),d.isMounted=!0}return e}function b(e,t,n,r){const{componentInstance:u}=e;u.onUpdate=()=>{t.children[n]=f(r,t.children[n],u.$element,t,n,{skipComponentUpdate:!0})}}function h(e){if(Object(r.e)(e))return document.createTextNode("");if(Object(r.g)(e))return document.createTextNode(e.value);if(Object(r.d)(e))return h(e.children[0]);const{tag:t,props:n,children:u=[]}=e,d=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=d),Object.keys(n).forEach(e=>{p(d,e,n[e])}),e.children=u.map((t,n)=>f(d,void 0,t,e,n)),d}function m(e,t,n,r){if(1===e.length)return[f(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const u=document.createDocumentFragment(),d=e.map(e=>f(n,void 0,e,r,t,{fragment:u}));return n.childNodes[t]?n.insertBefore(u,n.childNodes[t]):n.appendChild(u),d}throw new Error("Unexpected input")}function p(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?Object(o.a)(e,t,n):t.startsWith("data-")||a.has(t)?e.setAttribute(t,n):c.has(t)||(e[i[t]||t]=n))}function g(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?Object(o.c)(e,t,n):t.startsWith("data-")||a.has(t)?e.removeAttribute(t):c.has(t)||delete e[i[t]||t]}t.a={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=Object(u.a)(s),s[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=s[n];r.children=[f(t,r.children[0],e,r,0)]}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(0),u=n(4),d=n(41),o=n(23),c=n(2),a=n(3),i=n(8),s=n(27);var f=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openUserInfo"]))(({className:e,sender:t,openUserInfo:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t.id})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("UserLink",e),onClick:d},u):u});var l=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["focusMessage"]))(({className:e,message:t,children:n,focusMessage:u})=>{const d=Object(r.m)(()=>{t&&u({chatId:t.chatId,messageId:t.id})},[u,t]);return t?r.a.createElement(s.a,{className:Object(i.a)("MessageLink",e),onClick:d},n):n});var b=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openChat"]))(({className:e,chatId:t,openChat:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("ChatLink",e),onClick:d},u):u});function h(e,t,n,c,a,i,s={}){if(!t.content.action)return[];const{text:f}=t.content.action,h=[],g={...s,maxTextLength:16};let y,v=p(f,"%action_origin%",n?!s.isEmbedded&&function(e,t,n){return Object(u.fb)(t)?function(e,t,n){const c=Object(d.a)(Object(u.l)(e,t));if(n)return c;return r.a.createElement(b,{className:"action-link",chatId:t.id},t&&Object(o.a)(c))}(e,t,n):m(t,n)}(e,n,s.asPlain)||" ":"User");return y=v.pop(),h.push(...v),v=p(y,"%target_user%",c?m(c,s.asPlain):"User"),y=v.pop(),h.push(...v),v=p(y,"%message%",a?function(e,t,n={}){const c=Object(u.N)(e,t),{photo:a,video:i,document:s,sticker:f}=Object(u.v)(t),b=c&&!a&&!i&&!s&&!f;let h=Object(d.a)(c,n.maxTextLength);a?h="a photo":i?h=i.isGif?"a GIF":"a video":s?h="a document":f&&(h=`«${c}»`);if(n.asPlain)return b?`«${h}»`:h;if(b)return r.a.createElement("span",null,"«",r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h)),"»");return r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h))}(e,a,g):"a message"),y=v.pop(),h.push(...v),v=p(y,"%product%",a?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(a):"a product"),y=v.pop(),h.push(...v),v=p(y,"%target_chat%",i?function(e,t){if(t)return"another chat";return r.a.createElement(b,{className:"action-link",chatId:e},"another chat")}(i,s.asPlain):"another chat"),h.push(...v),s.asPlain?h.join("").trim():h}function m(e,t){const n=Object(d.a)(Object(u.Z)(e));return t?n:r.a.createElement(f,{className:"action-link",sender:e},e&&Object(o.a)(n))}function p(e,t,n){const r=e.indexOf(t);if(r<0||!n)return[e];const u=[];return u.push(e.substring(0,r)),u.push(n),u.push(e.substring(r+t.length)),u}},function(e,t){},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return d})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const u=-1,d="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var r=n(0),u=n(2),d=n(3),o=n(6);t.a=Object(u.h)((e,{userId:t})=>({userOrChat:t?Object(o.Gb)(e,t):void 0}),(e,t)=>Object(d.l)(t,["openChat","openChatByUsername"]))(({username:e,userOrChat:t,children:n,openChat:u,openChatByUsername:d})=>r.a.createElement("a",{onClick:()=>{t?u({id:t.id}):e&&d({username:e.substring(1)})},className:"text-entity-link",dir:"auto"},n))},function(e,t,n){"use strict";var r=n(62),u=n(42);let d=!1;const o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,c=(e,t,n)=>(1-n)*e+n*t,a=Object.keys(u).map(e=>({property:e,colors:[i(u[e][0]),i(u[e][1])]}));function i(e){const t=o.exec(e);return{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16),a:void 0!==t[4]?parseInt(t[4],16):void 0}}function s(e,t,n=1){a.forEach(({property:r,colors:u})=>{const d=Math.round(c(u[e].r,u[t].r,n)),o=Math.round(c(u[e].g,u[t].g,n)),a=Math.round(c(u[e].b,u[t].b,n)),i=void 0!==u[e].a?Math.round(c(u[e].a,u[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==i?`rgba(${d},${o},${a},${i/255})`:`rgb(${d},${o},${a})`)})}t.a=(e,t)=>{const n="dark"===e,u=d&&t,o=n?0:1,c=n?1:0,a=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),d&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add("theme-"+e),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout(()=>{document.documentElement.classList.remove("no-animations")},500),d=!0,u?Object(r.b)(()=>{const e=Math.min((Date.now()-a)/200,1);return s(o,c,function(e){return 1-(1-e)**3.5}(e)),e<1}):s(o,c)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(1);function u(e){"function"==typeof window.navigator.setAppBadge&&window.navigator.setAppBadge(e).catch(e=>{r.p&&console.error(e)})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(0);function u(e,t,n){Object(r.n)(()=>{const r=e=>{const r=t.current,u=e.target;r&&u&&(r.contains(e.target)&&!u.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}},[e,t,n])}},function(e,t,n){e.exports=function(){return new Worker(n.p+"6b9e1c477ee38548ce72.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"01705582fc3eca0e007b.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0dbbe0a906f6c2adf071.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"a66075669d8d0ac2d740.worker.js")}},function(e,t,n){"use strict";var r=n(2),u=n(7),d=n(14),o=n(78),c=n(39);Object(r.b)("init",e=>{const{theme:t,animationLevel:n,messageTextSize:r,language:c}=e.settings.byKey;Object(d.c)(c),document.documentElement.style.setProperty("--message-text-size",r+"px"),document.body.classList.add("initial"),document.body.classList.add("animation-level-"+n),document.body.classList.add(u.l?"is-touch-env":"is-pointer-env"),Object(o.a)(t,n>0),u.j&&document.body.classList.add("is-safari"),u.e?document.body.classList.add("is-ios"):u.b&&document.body.classList.add("is-android")}),Object(r.b)("setIsUiReady",(e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return c.a.pushState({type:"login",contentKey:"authCode"}),{...e,authPhoneNumber:r}}),Object(r.b)("setAuthRememberMe",(e,t,n)=>({...e,authRememberMe:Boolean(n)})),Object(r.b)("clearAuthError",e=>({...e,authError:void 0})),Object(r.b)("setShouldSkipUiLoaderTransition",(e,t,n)=>{const{shouldSkipUiLoaderTransition:r}=n;return{...e,shouldSkipUiLoaderTransition:r}})},function(e,t,n){"use strict";var r=n(2),u=n(1),d=n(10),o=n(29),c=n(12),a=n(39),i=n(79),s=n(22);Object(r.b)("initApi",(e,t)=>{(async()=>{u.E?Object(s.d)():(await Object(s.c)(),Object(s.a)()),Object(d.c)(t.apiUpdate,Object(s.e)())})()}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return Object(d.a)("provideAuthPhoneNumber",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthCode",(e,t,n)=>{const{code:r}=n;return Object(d.a)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthPassword",(e,t,n)=>{const{password:r}=n;return Object(d.a)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("uploadProfilePhoto",(e,t,n)=>{const{file:r}=n;Object(d.a)("uploadProfilePhoto",r)}),Object(r.b)("signUp",(e,t,n)=>{const{firstName:r,lastName:u}=n;return Object(d.a)("provideAuthRegistration",{firstName:r,lastName:u}),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("returnToAuthPhoneNumber",e=>(Object(d.a)("restartAuth"),{...e,authError:void 0})),Object(r.b)("gotToAuthQrCode",e=>(Object(d.a)("restartAuthWithQr"),a.a.pushState({type:"login",contentKey:"authQr"}),{...e,authIsLoadingQrCode:!0,authError:void 0})),Object(r.b)("saveSession",(e,t,n)=>{Object(s.f)(n.sessionData,e.currentUserId)}),Object(r.b)("signOut",()=>{(async()=>{await Object(o.d)(),await Object(d.a)("destroy"),Object(r.d)().reset()})()}),Object(r.b)("reset",()=>{Object(s.b)(),c.b(u.N),c.b(u.O),c.b(u.P),c.b(u.m);const e=u.F.replace(/\d+$/,""),t=(u.F.match(/\d+$/)||[0])[0];for(let n=0;n{(async()=>{await Object(d.a)("disconnect")})()}),Object(r.b)("loadNearestCountry",e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await Object(d.a)("fetchNearestCountry");Object(r.g)({...Object(r.e)(),authNearestCountry:e})})()}),Object(r.b)("setDeviceToken",(e,t,n)=>{Object(r.g)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})}),Object(r.b)("deleteDeviceToken",e=>{const t={...e};delete t.push,Object(r.g)(t)})},function(e,t){var n,r,u=e.exports={};function d(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function c(e){if(n===setTimeout)return setTimeout(e,0);if((n===d||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:d}catch(e){n=d}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,i=[],s=!1,f=-1;function l(){s&&a&&(s=!1,a.length?i=a.concat(i):f=-1,i.length&&b())}function b(){if(!s){var e=c(l);s=!0;for(var t=i.length;t;){for(a=i,i=[];++f1)for(var n=1;n{switch(u.p&&"updateUserStatus"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){Object(d.c)(),Object(c.c)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=Object(r.e)();const n="authorizationStateReady"===t.authState,u=e.authorizationState;switch(Object(r.g)({...t,authState:u,authIsLoading:!1}),t=Object(r.e)(),u){case"authorizationStateLoggingOut":Object(r.g)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":Object(r.g)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":Object(r.g)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":Object(r.g)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":if(n)break;Object(r.g)({...t,isLoggingOut:!1,lastSyncTime:Date.now()})}}(n);break;case"updateAuthorizationError":!function(e){Object(r.g)({...Object(r.e)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=Object(r.e)();Object(r.g)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?Object(r.d)().sync():"connectionStateBroken"===t&&Object(r.d)().signOut()}(n);break;case"updateSession":!function(e){if(!Object(r.e)().authRememberMe)return;const{sessionData:t}=e;Object(r.d)().saveSession({sessionData:t})}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;Object(r.g)({...Object(o.nb)(Object(r.e)(),t.id,t),currentUserId:t.id}),function(e){const t=localStorage.getItem(u.nb);if(!t)return;const n=JSON.parse(t);n.id=e,localStorage.setItem(u.nb,JSON.stringify(n))}(t.id)}(n);break;case"error":"SESSION_REVOKED"===n.error.message&&t.signOut(),t.showError({error:n.error})}})},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(21),function(){function e(){var t=Error.call(this,"ServiceWorker is not supported.");return Object.setPrototypeOf(t,e.prototype),t}e.prototype=Object.create(Error.prototype)}();var r=n.p+"serviceWorker.js";var u=n(1),d=n(2),o=n(7),c=n(29);function a(e){const t=e.data;if(!t.type)return;const n=Object(d.d)();switch(t.type){case"focusMessage":n.focusMessage(t.payload)}}function i(){navigator.serviceWorker.removeEventListener("message",a),navigator.serviceWorker.addEventListener("message",a),Object(c.a)()}o.k&&(window.addEventListener("load",async()=>{try{await navigator.serviceWorker.register(r),u.p&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(u.p&&console.log("[SW] ServiceWorker ready"),i()):(u.p&&console.error("[SW] ServiceWorker not available"),Object(d.d)().showError({error:{message:"SERVICE_WORKER_DISABLED"}}))}catch(e){u.p&&console.error("[SW] ServiceWorker registration failed: ",e)}}),window.addEventListener("focus",async()=>{await navigator.serviceWorker.ready,i()}));var s=n(67);const f={isLeftColumnShown:!0,isChatInfoShown:!1,uiReadyState:0,authRememberMe:!0,blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{}},scheduledMessages:{byChatId:{}},chatFolders:{byId:{},activeChatFolder:0},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},emojiKeywords:{},gifs:{saved:{},search:{}},globalSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},mediaViewer:{},audioPlayer:{},forwardMessages:{},pollResults:{},payment:{},notifications:[],errors:[],activeSessions:[],settings:{byKey:{messageTextSize:u.s,animationLevel:u.d,messageSendKeyCombo:"enter",theme:"light",shouldAutoDownloadMediaFromContacts:!0,shouldAutoDownloadMediaInPrivateChats:!0,shouldAutoDownloadMediaInGroups:!0,shouldAutoDownloadMediaInChannels:!0,shouldAutoPlayGifs:!0,shouldAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en"},themes:{light:{isBlurred:!0,patternColor:u.t},dark:{isBlurred:!0,patternColor:u.o}},privacy:{},notifyExceptions:{}},twoFaSettings:{}};var l=n(5),b=n(9),h=n(3),m=n(6);const p=Object(b.g)((function(){Object(b.c)(()=>{if(!g)return;const e=Object(d.e)();if(e.isLoggingOut)return;const t={...f,...Object(h.l)(e,["authState","authPhoneNumber","authRememberMe","authNearestCountry","currentUserId","contactList","chatFolders","topPeers","recentEmojis","emojiKeywords","push"]),isChatInfoShown:v(e),users:w(e),chats:O(e),messages:I(e),globalSearch:{recentlyFoundChatIds:e.globalSearch.recentlyFoundChatIds},settings:j(e)},n=JSON.stringify(t);localStorage.setItem(u.B,n)})}),1e3,!1);let g=!1;function y(e){if(!u.A){if(localStorage.getItem(u.nb)||localStorage.getItem(u.H))return g=!0,Object(d.a)(p),function(e){u.p&&console.time("global-state-cache-read");const t=localStorage.getItem(u.B),n=t?JSON.parse(t):void 0;u.p&&console.timeEnd("global-state-cache-read");n&&(n.settings.byKey={...e.settings.byKey,...n.settings.byKey},n.settings.themes={...e.settings.themes,...n.settings.themes},n.chatFolders={...e.chatFolders,...n.chatFolders});return{...e,...n}}(e);g=!1}}function v(e){return window.innerWidth>u.ab&&e.isChatInfoShown}function w(e){const{users:{byId:t,selectedId:n}}=e,r=[...(e.chats.listIds.active||[]).slice(0,u.z).filter(e=>e>0),...Object.keys(t)].slice(0,u.C);return{byId:Object(h.l)(t,r),selectedId:window.innerWidth>u.ab?n:void 0}}function O(e){const t=[...(e.chats.listIds.active||[]).slice(0,u.z)],{chatId:n}=Object(m.y)(e)||{};return{...e.chats,byId:Object(h.l)(e.chats.byId,n?[...t,n]:t),listIds:{active:t},isFullyLoaded:{},orderedPinnedIds:{active:e.chats.orderedPinnedIds.active}}}function I(e){const t={},{chatId:n}=Object(m.y)(e)||{};[...(e.chats.listIds.active||[]).slice(0,u.z),...n?[n]:[]].forEach(n=>{const r=e.messages.byChatId[n];if(!r)return;const u=r.threadsById[l.MAIN_THREAD_ID];u&&u.viewportIds&&(t[n]={byId:Object(h.l)(r.byId,u.viewportIds),threadsById:{[l.MAIN_THREAD_ID]:u}})});const r=Object(m.y)(e);return{byChatId:t,messageLists:!r||o.g?void 0:[{...r,threadId:l.MAIN_THREAD_ID,type:"thread"}]}}function j(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}u.A||(Object(d.b)("saveSession",()=>{g=!0,Object(d.a)(p)}),Object(d.b)("reset",()=>{g=!1,Object(d.f)(p),localStorage.removeItem(u.B)})),Object(d.b)("init",()=>{const e=Object(h.d)(f),t=y(e)||e,n=Object(m.y)(t)||{};return window.history.replaceState(n,""),t});var C=n(0),E=n(57);const S=String(Date.now()+Math.random());let M;localStorage.setItem("tt-active-tab",S);const A=window.setInterval(()=>{M&&localStorage.getItem("tt-active-tab")!==S&&(M(),clearInterval(A))},2e3);var k=n(34),T=(n(85),n(86),n(88),n(31)),N=n(35),P=n(40),D=n(13);const L=["400 1em Roboto","500 1em Roboto"];function F(){if("fonts"in document)return Promise.all(L.map(e=>document.fonts.load(e)))}var B=n(55),x=n(11),R=n(8),U=(n(90),n.p+"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg"),_=n.p+"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg";function G(){const{listIds:e,byId:t}=Object(d.e)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map(e=>{const n=t[e];if(!n)return;const r=Object(T.d)(n);return r?B.b(r,l.ApiMediaFormat.DataUri):void 0}))}const $={main:()=>Promise.all([Object(x.d)(x.a.Main,"Main").then(F),G()]),authPhoneNumber:()=>Promise.all([F(),Object(D.g)(U)]),authCode:()=>Object(D.g)(_),authPassword:()=>Object(D.g)(_),authQrCode:F};var W=Object(d.h)(e=>{const{theme:t}=e.settings.byKey,{background:n,backgroundColor:r}=e.settings.themes[t]||{};return{shouldSkipUiLoaderTransition:e.shouldSkipUiLoaderTransition,uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(n),hasCustomBackgroundColor:Boolean(r),isRightColumnShown:Object(m.W)(e)}},(e,t)=>Object(h.l)(t,["setIsUiReady","setShouldSkipUiLoaderTransition"]))(({page:e,children:t,hasCustomBackground:n,hasCustomBackgroundColor:r,isRightColumnShown:u,shouldSkipUiLoaderTransition:d,setIsUiReady:o,setShouldSkipUiLoaderTransition:c})=>{const[a,i]=Object(k.a)(),{shouldRender:s,transitionClassNames:f}=Object(N.a)(!a,void 0,!0);return Object(C.n)(()=>{let t;return Promise.race([Object(b.e)(700),(async()=>{try{await $[e]()}catch(e){}})()]).then(()=>{i(),o({uiReadyState:1}),t=window.setTimeout(()=>{o({uiReadyState:2})},1e3)}),()=>{t&&(clearTimeout(t),t=void 0),o({uiReadyState:0})}},[]),Object(P.a)(()=>{d&&setTimeout(()=>{c({shouldSkipUiLoaderTransition:!1})},400)},[d]),C.a.createElement("div",{id:"UiLoader"},t,s&&!d&&C.a.createElement("div",{className:Object(R.a)("mask",f)},"main"===e?C.a.createElement(C.a.Fragment,null,C.a.createElement("div",{className:"left"}),C.a.createElement("div",{className:Object(R.a)("middle",n&&"custom-bg-image",r&&"custom-bg-color",u&&"with-right-column")}),u&&C.a.createElement("div",{className:"right"})):C.a.createElement("div",{className:"blank"})))}),H=n(18),K=n(32),z=n(48),V=n(47),q=n(16),J=n(53),Y=n(23),Q=n(63),Z=n(44),X=n(20);n(99);const ee=200+u.c;var te=Object(C.h)(({id:e,value:t,isLoading:n,onChange:r})=>{const u=Object(C.q)(null),[d,o]=Object(C.r)(),[c,a]=Object(C.r)(H.a);function i(e){o(e),a(function(e=""){return e.length?H.a.filter(t=>Object(J.a)(t.name,e)):H.a}(e))}const s=Object(C.m)(e=>{const{countryId:t}=e.currentTarget.firstElementChild.dataset,n=H.a.find(e=>e.id===t);n&&r(n),setTimeout(()=>i(void 0),ee)},[r]),f=Object(C.m)(e=>{i(e.currentTarget.value)},[]),l=Object(C.m)(e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===d&&(n.value=""),i(n.value)},[d,t]);return C.a.createElement(Q.a,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:o})=>{const c=()=>{if(o)return;setTimeout(()=>{u.current.select()},50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},a=void 0!==d?d:t&&t.name||"";return C.a.createElement("div",{className:Object(R.a)("input-group",t&&"touched")},C.a.createElement("input",{ref:u,className:Object(R.a)("form-control",o&&"focus"),type:"text",id:e,value:a,autoComplete:"off",onClick:c,onFocus:c,onInput:f,onKeyDown:l}),C.a.createElement("label",null,"Country"),n?C.a.createElement(X.a,{color:"black"}):C.a.createElement("i",{onClick:c,className:Object(R.a)("css-icon-down",o&&"open")}))}},c.map(e=>C.a.createElement(Z.a,{key:e.id,className:t&&e.id===t.id?"selected":"",onClick:s},C.a.createElement("span",{"data-country-id":e.id}),C.a.createElement("span",{className:"country-flag"},Object(Y.a)(e.flag,["hq_emoji"])),C.a.createElement("span",{className:"country-name"},e.name),C.a.createElement("span",{className:"country-code"},e.code))),!c.length&&C.a.createElement(Z.a,{key:"no-results",className:"no-results",disabled:!0},C.a.createElement("span",null,"No countries matched your filter.")))});let ne=!1;var re=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),(e,t)=>Object(h.l)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","gotToAuthQrCode"]))(({connectionState:e,authState:t,authPhoneNumber:n,authIsLoading:r,authIsLoadingQrCode:u,authError:d,authRememberMe:c,authNearestCountry:a,setAuthPhoneNumber:i,setAuthRememberMe:s,loadNearestCountry:f,clearAuthError:l,gotToAuthQrCode:b})=>{const h=Object(C.q)(null),[m,p]=Object(C.r)(),[g,y]=Object(C.r)(),[v,w]=Object(C.r)(!1),[O,I]=Object(C.r)(),j=m?`${m.code} ${g||""}`:g,E=j&&j.replace(/[^\d]+/g,"").length>=7;Object(C.n)(()=>{o.l||h.current.focus()},[m]),Object(C.n)(()=>{"connectionStateReady"!==e||a||f()},[e,a,f]),Object(C.n)(()=>{!a||m||v||p(Object(H.d)(a))},[m,a,v]);const S=Object(C.m)(e=>{const t=Object(H.e)(e),n=!m||t&&t.id!==m.id?t:m;e.length?(!m||n&&n.code!==m.code)&&p(n):p(void 0),y(Object(H.b)(e,n))},[m]);Object(C.n)(()=>{void 0===g&&n&&S(n)},[n,g,S]),Object(C.o)(()=>{h.current&&O&&h.current.setSelectionRange(...O)},[O]);const M=Object(C.m)(e=>{d&&l(),ne||(ne=!0,F(),Object(D.g)(_));const{value:t,selectionStart:n,selectionEnd:r}=e.target;I(n&&r&&r{s(e.target.checked)},[s]);const k="authorizationStateWaitPhoneNumber"===t;return C.a.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},C.a.createElement("div",{className:"auth-form"},C.a.createElement("div",{id:"logo"}),C.a.createElement("h2",null,"Sign in to Telegram"),C.a.createElement("p",{className:"note"},"Please confirm your country and",C.a.createElement("br",null),"enter your phone number."),C.a.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),r||E&&i({phoneNumber:j})}},C.a.createElement(te,{id:"sign-in-phone-code",value:m,isLoading:!a&&!m,onChange:p}),C.a.createElement(V.a,{ref:h,id:"sign-in-phone-number",label:"Phone Number",value:j,error:d,inputMode:"tel",onChange:M}),C.a.createElement(z.a,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(c),onChange:A}),E&&(k?C.a.createElement(K.a,{type:"submit",ripple:!0,isLoading:r},"Next"):C.a.createElement(q.a,null)),k&&C.a.createElement(K.a,{isText:!0,ripple:!0,isLoading:u,onClick:b},"Log in by QR code"))))})),ue=n(17);var de=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthCode");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});var oe=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthPassword");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});var ce=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthRegister");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});var ae=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthQrCode");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});n(100);var ie=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["reset","initApi"]))(({authState:e,reset:t,initApi:n})=>{switch(Object(C.n)(()=>{t(),n()},[t,n]),Object(C.n)(()=>{},[]),e){case"authorizationStateWaitCode":return C.a.createElement(W,{page:"authCode",key:"authCode"},C.a.createElement(de,null));case"authorizationStateWaitPassword":return C.a.createElement(W,{page:"authPassword",key:"authPassword"},C.a.createElement(oe,null));case"authorizationStateWaitRegistration":return C.a.createElement(ce,null);case"authorizationStateWaitQrCode":return C.a.createElement(W,{page:"authQrCode",key:"authQrCode"},C.a.createElement(ae,null));case"authorizationStateWaitPhoneNumber":default:return C.a.createElement(W,{page:"authPhoneNumber",key:"authPhoneNumber"},C.a.createElement(re,null))}}));var se=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Main,"Main");return e?C.a.createElement(e,null):void 0}),fe=n.p+"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png";n(101);var le=()=>C.a.createElement("div",{id:"AppInactive"},C.a.createElement("div",{className:"content"},C.a.createElement("img",{src:fe,alt:""}),C.a.createElement("h3",{className:"title"},"Such error, many tabs"),C.a.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",C.a.createElement("br",null),"Please reload this page to continue using this tab or close it."),C.a.createElement("div",{className:"actions"},C.a.createElement(K.a,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function be(){return d.c.createElement(W,{page:"main",key:"main"},d.c.createElement(se,null))}var he=Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["disconnect"]))(({authState:e,disconnect:t})=>{const[n,r]=Object(k.a)(!1);if(Object(C.n)(()=>{Object(E.b)(),M=()=>{t(),document.title=`${u.eb}${u.D}`,r()}},[t,r]),n)return d.c.createElement(le,null);if(e)switch(e){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return d.c.createElement(ie,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return be()}return localStorage.getItem(u.nb)||localStorage.getItem(u.H)?be():d.c.createElement(ie,null)});n(102);u.p&&console.log(">>> INIT"),Object(d.d)().init(),u.p&&console.log(">>> START INITIAL RENDER"),s.a.render(d.c.createElement(he,null),document.getElementById("root")),u.p&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",()=>{console.log("GLOBAL STATE",Object(d.e)())})}]); -//# sourceMappingURL=main.a578e966316fd5919f1a.js.map \ No newline at end of file +!function(e){function t(t){for(var n,r,d=t[0],o=t[1],c=0,a=[];c=0&&w(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),I[n].renderTimes.push(t),I[n].renderCount++}}catch(t){Object(c.a)(t),u=e.renderedValue}if(e.isMounted&&u===e.renderedValue)return e.$element;e.renderedValue=u;const d=O(u);return e.$element=y(e,[d]),e.$element}function C(e,t){return typeof e!=typeof t||(e.type!==t.type||(b(e)&&b(t)?e.value!==t.value:h(e)&&h(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!m(e)||!m(t))&&(e.componentInstance.Component!==t.componentInstance.Component||e.props.key!==t.props.key)))}function E(e){p(e)&&(m(e)?function(e){if(!e.isMounted)return;e.hooks.memos.byCursor.forEach(e=>{e.current=null}),e.hooks.effects.byCursor.forEach(({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}}),e.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach(e=>{e.cleanup=null,e.effect=null,e.dependencies=null}),e.hooks.state.byCursor.forEach(e=>{e.value=null,e.nextValue=null,e.setter=null}),e.hooks.memos.byCursor.forEach(e=>{e.dependencies=null}),e.hooks=null,e.$element=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(e)}(e.componentInstance):e.target&&(Object(a.b)(e.target),e.target=null),e.children.forEach(E))}function S(e){return j(e),e.isMounted=!0,e.$element}function M(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;j(e),e.$element!==t&&e.onUpdate()}function A(e){return m(e)?A(e.children[0]):e.target}function k(e,t){m(e)?k(e.children[0],t):e.target=t}function T(e){const{cursor:t,byCursor:n}=f.hooks.state;var d;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(d=f,e=>{n[t].nextValue!==e&&(n[t].nextValue="function"==typeof e?e(n[t].value):e,d.prepareForFrame&&d.forceUpdate||(d.prepareForFrame=Object(u.h)(()=>function e(t){t.isMounted&&(t.hooks.state.byCursor.forEach(e=>{e.value=e.nextValue}),t.prepareForFrame=Object(u.h)(()=>e(t)),t.forceUpdate=Object(u.i)(()=>M(t)))}(d)),d.forceUpdate=Object(u.i)(()=>M(d))),d.prepareForFrame(),d.forceUpdate(),r.r&&console.log("[Teact.useState]",d.name,d.Component&&d.Component.DEBUG_contentComponentName?"> "+d.Component.DEBUG_contentComponentName:"",`Forced update at cursor #${t}, next value: `,n[t].nextValue))})}),f.hooks.state.cursor++,[n[t].value,n[t].setter]}function N(e,t,n){const{cursor:r,byCursor:u}=f.hooks.effects,d=f,o=()=>{if(!d.isMounted)return;const{cleanup:e}=u[r];if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}u[r].cleanup=t()};void 0!==u[r]&&n&&u[r].dependencies?n.some((e,t)=>e!==u[r].dependencies[t])&&e(o):e(o),u[r]={effect:t,dependencies:n,cleanup:u[r]?u[r].cleanup:void 0},f.hooks.effects.cursor++}function P(e,t){return N(u.b,e,t)}function D(e,t){return N(u.d,e,t)}function L(e,t){const{cursor:n,byCursor:r}=f.hooks.memos;let{current:u}=r[n]||{};return(void 0===r[n]||t.some((e,t)=>e!==r[n].dependencies[t]))&&(u=e()),r[n]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function F(e,t){return L(()=>e,t)}function B(e){return L(()=>({current:e}),[])}function x(e,t=o.a,n=!1){return function(u){const d=B(u),c=B();return(!c.current||d.current&&!t(d.current,u))&&(r.p&&n&&console.log(`[Teact.memo] ${e.name}: Update is caused by:`,Object(o.b)(d.current,u).join(", ")),d.current=u,c.current=g(e,u)),c.current}}document.addEventListener("dblclick",()=>{console.log("COMPONENTS",Object(d.k)(Object.values(I),"renderCount","desc"))}),t.a={createElement:g,Fragment:s}},function(e,t,n){"use strict";n.d(t,"eb",(function(){return r})),n.d(t,"D",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"g",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"r",(function(){return a})),n.d(t,"E",(function(){return i})),n.d(t,"q",(function(){return s})),n.d(t,"nb",(function(){return f})),n.d(t,"H",(function(){return l})),n.d(t,"A",(function(){return b})),n.d(t,"B",(function(){return h})),n.d(t,"z",(function(){return m})),n.d(t,"C",(function(){return p})),n.d(t,"M",(function(){return g})),n.d(t,"N",(function(){return y})),n.d(t,"O",(function(){return v})),n.d(t,"P",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"F",(function(){return I})),n.d(t,"Y",(function(){return C})),n.d(t,"U",(function(){return E})),n.d(t,"V",(function(){return S})),n.d(t,"W",(function(){return M})),n.d(t,"i",(function(){return A})),n.d(t,"k",(function(){return k})),n.d(t,"j",(function(){return T})),n.d(t,"ob",(function(){return N})),n.d(t,"X",(function(){return P})),n.d(t,"y",(function(){return D})),n.d(t,"R",(function(){return L})),n.d(t,"Q",(function(){return F})),n.d(t,"fb",(function(){return B})),n.d(t,"Db",(function(){return x})),n.d(t,"a",(function(){return R})),n.d(t,"e",(function(){return U})),n.d(t,"d",(function(){return _})),n.d(t,"s",(function(){return G})),n.d(t,"u",(function(){return $})),n.d(t,"v",(function(){return W})),n.d(t,"w",(function(){return H})),n.d(t,"kb",(function(){return K})),n.d(t,"jb",(function(){return z})),n.d(t,"ab",(function(){return V})),n.d(t,"Z",(function(){return q})),n.d(t,"db",(function(){return J})),n.d(t,"cb",(function(){return Y})),n.d(t,"bb",(function(){return Q})),n.d(t,"J",(function(){return Z})),n.d(t,"c",(function(){return X})),n.d(t,"vb",(function(){return ee})),n.d(t,"wb",(function(){return te})),n.d(t,"qb",(function(){return ne})),n.d(t,"rb",(function(){return re})),n.d(t,"yb",(function(){return ue})),n.d(t,"ub",(function(){return de})),n.d(t,"zb",(function(){return oe})),n.d(t,"Ab",(function(){return ce})),n.d(t,"xb",(function(){return ae})),n.d(t,"Bb",(function(){return ie})),n.d(t,"sb",(function(){return se})),n.d(t,"tb",(function(){return fe})),n.d(t,"S",(function(){return le})),n.d(t,"T",(function(){return be})),n.d(t,"pb",(function(){return he})),n.d(t,"l",(function(){return me})),n.d(t,"gb",(function(){return pe})),n.d(t,"ib",(function(){return ge})),n.d(t,"hb",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"b",(function(){return we})),n.d(t,"h",(function(){return Oe})),n.d(t,"L",(function(){return Ie})),n.d(t,"K",(function(){return je})),n.d(t,"lb",(function(){return Ce})),n.d(t,"G",(function(){return Ee})),n.d(t,"Cb",(function(){return Se})),n.d(t,"x",(function(){return Me})),n.d(t,"I",(function(){return Ae})),n.d(t,"n",(function(){return ke})),n.d(t,"o",(function(){return Te})),n.d(t,"t",(function(){return Ne}));const r="Telegram",u=" [Inactive]",d="Telegram WebZ",o="8b04a98",c=!1,a=!1,i=!1,s="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",f="user_auth",l="GramJs:sessionId",b=!1,h="tt-global-state",m=30,p=5e3,g=!1,y="tt-media",v="tt-media-avatars",w="tt-media-progressive",O="tt-custom-bg",I="tt-lang-packs-v4",j=(new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight>=900),C=1,E=750,S=j?60:40,M=2*S,A=72,k=j?30:25,T=100,N=42,P=42,D=20,L=30,F=200,B=500,x=20,R=!1,U=2,_=U,G=16,$=1e4,W="editable-message-text",H="editable-message-text-modal",K=1440,z=1150,V=1275,q=925,J=600,Y=950,Q=450,Z=1e9,X=100,ee=13,te=11,ne=160,re=120,ue=64,de=48,oe=32,ce=64,ae=64,ie=160,se=140,fe=80,le="MEMOJI_STICKER",be=200,he=450,me="image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime",pe="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",ge=/^(?:https?:\/\/)?(?:t\.me\/)([\d\w_]+)(?:\/([\d]+))?$/gm,ye=/^(?:https?:\/\/)?(?:t\.me\/joinchat\/)([\d\w_]+)?$/gm,ve=777e3,we=0,Oe=1,Ie=10,je=5,Ce=2147483646,Ee=["android","ios","tdesktop","macos"],Se="TelegramTips",Me="https://bugs.telegram.org/?tag_ids=41&sort=time",Ae="#A2AF8E",ke="#0F0F0F",Te="#0a0a0a8c",Ne="rgba(90, 110, 70, 0.6)"},function(e,t,n){"use strict";n.d(t,"g",(function(){return v})),n.d(t,"e",(function(){return w})),n.d(t,"d",(function(){return O})),n.d(t,"b",(function(){return I})),n.d(t,"a",(function(){return j})),n.d(t,"f",(function(){return C})),n.d(t,"h",(function(){return E}));var r=n(0),u=n(1),d=n(26),o=n(28),c=n(9),a=n(24),i=n(3),s=n(21);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],m={},p=new Map;function g(){h.forEach(e=>e(l))}const y=Object(c.i)(g);function v(e,t=!1){"object"==typeof e&&e!==l&&(l=e,t?g():y())}function w(){return l}function O(){return m}function I(e,t){b[e]||(b[e]=[],m[e]=(t,n=!1)=>{!function(e,t,n){b[e]&&b[e].forEach(e=>{const r=e(l,m,t);r&&v(r,n)})}(e,t,n)}),b[e].push(t)}function j(e){h.push(e)}function C(e){const t=h.indexOf(e);-1!==t&&h.splice(t,1)}function E(e=(()=>({})),t=(()=>({}))){return n=>function u(c){u.DEBUG_contentComponentName=n.name;const[i]=Object(r.r)(Object(o.a)(p)),b=Object(d.a)();Object(r.n)(()=>()=>{p.delete(i)},[i]);let h=p.get(i);if(h||(h={mapStateToProps:e,mapReducersToProps:t,ownProps:c,areMappedPropsChanged:!1,forceUpdate:b,DEBUG_updates:0,DEBUG_componentName:n.name},p.set(i,h)),h.areMappedPropsChanged&&(h.areMappedPropsChanged=!1),!h.mappedProps||!Object(a.a)(h.ownProps,c)){h.ownProps=c;try{h.mappedProps={...e(l,c),...t(v,m)}}catch(e){Object(s.a)(e)}}return r.a.createElement(n,f({},h.mappedProps,c))}}u.p&&(window.getGlobal=w,document.addEventListener("dblclick",()=>{console.log("GLOBAL CONTAINERS",Object(i.k)(Object.values(p),"DEBUG_updates","desc"))}))},function(e,t,n){"use strict";function r(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function u(e,t){return Object.keys(e).reduce((n,r,u)=>(n[r]=t(e[r],r,u,e),n),{})}function d(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function o(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}function c(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter(e=>!n.has(e)))}function a(e,t,n="asc"){return e.sort((e,r)=>{if(Array.isArray(t)){const[u,d]=Array.isArray(n)?n:[n,n],[o,c]=t;let a,i;if("function"==typeof o?(a=o(e)||0,i=o(r)||0):"string"==typeof o&&(a=e[o]||0,i=r[o]||0),a!==i)return"asc"===u?a-i:i-a;{let t,n;return"function"==typeof c?(t=c(e)||0,n=c(r)||0):"string"==typeof c&&(t=e[c]||0,n=r[c]||0),"asc"===d?t-n:n-t}}let u,d;return"function"==typeof t?(u=t(e)||0,d=t(r)||0):"string"==typeof t&&(u=e[t]||0,d=r[t]||0),"asc"===n?u-d:d-u})}function i(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e),[])}function s(e){return Array.from(new Set(e))}function f(e){return e.filter(Boolean)}function l(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function b(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function h(e,t){return e.filter(e=>t.has(e))}function m(e,t){const n=[];for(let r=0;r(t[n]=p(e[n]),t),{})}function g(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,"c",(function(){return r})),n.d(t,"i",(function(){return u})),n.d(t,"l",(function(){return d})),n.d(t,"m",(function(){return o})),n.d(t,"j",(function(){return c})),n.d(t,"k",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"d",(function(){return p})),n.d(t,"g",(function(){return g}))},function(e,t,n){"use strict";n.d(t,"Y",(function(){return r.b})),n.d(t,"Z",(function(){return r.c})),n.d(t,"ab",(function(){return r.d})),n.d(t,"xb",(function(){return r.g})),n.d(t,"pb",(function(){return r.e})),n.d(t,"wb",(function(){return r.f})),n.d(t,"Eb",(function(){return r.h})),n.d(t,"X",(function(){return r.a})),n.d(t,"lb",(function(){return u.w})),n.d(t,"kb",(function(){return u.v})),n.d(t,"ib",(function(){return u.t})),n.d(t,"nb",(function(){return u.y})),n.d(t,"jb",(function(){return u.u})),n.d(t,"ob",(function(){return u.z})),n.d(t,"m",(function(){return u.j})),n.d(t,"U",(function(){return u.p})),n.d(t,"l",(function(){return u.i})),n.d(t,"g",(function(){return u.e})),n.d(t,"h",(function(){return u.f})),n.d(t,"f",(function(){return u.d})),n.d(t,"mb",(function(){return u.x})),n.d(t,"gb",(function(){return u.r})),n.d(t,"q",(function(){return u.m})),n.d(t,"yb",(function(){return u.A})),n.d(t,"e",(function(){return u.c})),n.d(t,"c",(function(){return u.a})),n.d(t,"K",(function(){return u.o})),n.d(t,"k",(function(){return u.h})),n.d(t,"j",(function(){return u.g})),n.d(t,"hb",(function(){return u.s})),n.d(t,"Cb",(function(){return u.D})),n.d(t,"d",(function(){return u.b})),n.d(t,"Bb",(function(){return u.C})),n.d(t,"Ab",(function(){return u.B})),n.d(t,"p",(function(){return u.l})),n.d(t,"o",(function(){return u.k})),n.d(t,"fb",(function(){return u.q})),n.d(t,"J",(function(){return u.n})),n.d(t,"Db",(function(){return u.E})),n.d(t,"A",(function(){return i})),n.d(t,"zb",(function(){return s})),n.d(t,"F",(function(){return f})),n.d(t,"N",(function(){return l})),n.d(t,"O",(function(){return b})),n.d(t,"x",(function(){return h})),n.d(t,"L",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"tb",(function(){return g})),n.d(t,"ub",(function(){return y})),n.d(t,"qb",(function(){return v})),n.d(t,"db",(function(){return w})),n.d(t,"vb",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"V",(function(){return j})),n.d(t,"W",(function(){return C})),n.d(t,"sb",(function(){return E})),n.d(t,"rb",(function(){return S})),n.d(t,"v",(function(){return k})),n.d(t,"cb",(function(){return T})),n.d(t,"G",(function(){return N})),n.d(t,"P",(function(){return P})),n.d(t,"I",(function(){return D})),n.d(t,"t",(function(){return L})),n.d(t,"u",(function(){return F})),n.d(t,"M",(function(){return B})),n.d(t,"y",(function(){return x})),n.d(t,"H",(function(){return R})),n.d(t,"z",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"R",(function(){return G})),n.d(t,"E",(function(){return $})),n.d(t,"D",(function(){return W})),n.d(t,"C",(function(){return K})),n.d(t,"B",(function(){return z})),n.d(t,"b",(function(){return q})),n.d(t,"i",(function(){return J})),n.d(t,"S",(function(){return Y})),n.d(t,"T",(function(){return Q})),n.d(t,"bb",(function(){return Z})),n.d(t,"s",(function(){return X})),n.d(t,"w",(function(){return ee})),n.d(t,"r",(function(){return te})),n.d(t,"a",(function(){return ne}));var r=n(30),u=n(31),d=n(5),o=n(1),c=n(65);const a=new RegExp(o.gb,"i");function i(e){const{chatId:t,id:n}=e;return`msg${t}-${n}`}function s(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:Number(t[1]),messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function l(e,t,n=!1){const{text:r,photo:u,video:d,audio:o,voice:c,document:a,sticker:i,contact:s,poll:f,invoice:l}=t.content;if(t.groupedId)return`${n?"":"🖼 "}${r?r.text:e("lng_in_dlg_album")}`;if(u)return`${n?"":"🖼 "}${r?r.text:e("AttachPhoto")}`;if(d)return`${n?"":"📹 "}${r?r.text:e(d.isGif?"AttachGif":"AttachVideo")}`;if(i)return`${i.emoji} ${e("AttachSticker")} `;if(o){return`${n?"":"🎧 "}${[o.title,o.performer].filter(Boolean).join(" — ")||r&&r.text||e("AttachMusic")}`}return c?`${n?"":"🎤 "}${r?r.text:e("AttachAudio")}`:a?`${n?"":"📎 "}${r?r.text:a.fileName}`:s?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:l?"Invoice":r?r.text:"The message is not supported on this version of Telegram"}function b(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:c,poll:a,webPage:i,contact:s,invoice:f}=e.content;return t?t.text:n||r||u||d||o||c||s||a||i||f?void 0:"The message is not supported on this version of Telegram"}function h(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:a,poll:i,webPage:s,contact:f}=e.content;return!!(n||u&&u.isRound)||!(!t||r||u||d||o||a||i||s||f)&&(Object(c.a)(t.text)||!1)}function m(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===h(e))return t.text}function p(e){const{text:t}=e.content;let n;if(t&&t.entities){let e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.TextUrl);if(e&&(n=e.url.match(a)),!n&&(e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.Url),e)){const{offset:r,length:u}=e;n=t.text.substring(r,r+u).match(a)}}if(!n&&t&&(n=t.text.match(a)),n)return{url:n[0],domain:n[3]}}function g(e){return e.isOutgoing}function y(e){return Boolean(e.replyToMessageId)}function v(e){return Boolean(e.forwardInfo)}function w(e){return!!e.content.action}function O(e){return e.chatId===o.mb&&E(e)}function I(e){return Boolean(e.senderId)&&e.senderId<0&&g(e)}function j(e,t){return t.id>0?Object(r.c)(t):Object(u.i)(e,t)}function C(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function E(e){return e.id>=o.J}function S(e){return e.content.action&&"historyClear"===e.content.action.type}var M=n(7),A=n(60);function k(e){return e.content}function T(e){return Boolean(N(e)||P(e)||x(e)||B(e)||function(e){return e.content.contact}(e)||R(e)||L(e)||F(e)||function(e){return e.content.voice}(e))}function N(e){return e.content.photo}function P(e){return e.content.video}function D(e){const{video:t}=e.content;return t&&t.isRound?t:void 0}function L(e){return e.content.action}function F(e){return e.content.audio}function B(e){return e.content.sticker}function x(e){return e.content.document}function R(e){return e.content.poll}function U(e){return e.content.invoice}function _(e){return e.content.webPage}function G(e){const t=_(e);return t?t.photo:void 0}function $(e){const t=function(e){const t=N(e)||P(e)||x(e)||B(e)||G(e);if(t)return t.thumbnail}(e);return t?t.dataUri:void 0}function W(e,t){const{photo:n,video:r,sticker:u,audio:d,voice:o,document:c}=e.content,a=G(e);if(!(n||r||u||a||d||o||c))return;const s=i(e);if(n||a)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return s+"?size=x";case"viewerPreview":return s+"?size=x";case"viewerFull":return s+"?size=z"}if(r)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return q(r)?H(r,s):s+"?size=z";case"viewerPreview":return s+"?size=m";case"viewerFull":return H(r,s);case"download":return s+"?download"}if(c)switch(t){case"micro":case"pictogram":case"inline":if(!Object(A.c)(c)||V(e))return;return s+"?size=m";default:return s}if(u)switch(t){case"micro":return;case"pictogram":return s+"?size=m";default:return s}if(d)switch(t){case"micro":case"pictogram":return;default:return H(d,s)}if(o)switch(t){case"micro":case"pictogram":return;default:return s}}function H(e,t){return M.i&&M.j?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function K(e,t){const{sticker:n,video:r,audio:u,voice:o}=e.content;return n&&"inline"===t&&n.isAnimated?d.ApiMediaFormat.Lottie:r&&M.i&&("viewerFull"===t||"inline"===t&&q(r))?d.ApiMediaFormat.Progressive:u||o?o&&!M.h?d.ApiMediaFormat.BlobUrl:d.ApiMediaFormat.Progressive:d.ApiMediaFormat.BlobUrl}function z(e){const{photo:t,video:n,webPage:r}=e.content;return t||r&&r.photo?`photo${e.date}.jpeg`:n?n.fileName:void 0}function V(e){const{photo:t,video:n,document:r}=e.content;return t&&t.blobUrl||n&&n.blobUrl||r&&r.previewBlobUrl}function q(e){return e.isGif||e.isRound||e.size<=10485760}function J(e,t,n=!1){const r=ee(e,t,"media");return n?r.reverse():r}function Y(e){return e.sizes.find(e=>"z"===e.type)||e.sizes.find(e=>"y"===e.type)||Q(e)}function Q(e){return e.sizes.find(e=>"x"===e.type)||e.sizes.find(e=>"m"===e.type)||e.sizes.find(e=>"s"===e.type)||e.thumbnail}function Z(e){if(e.width&&e.height)return e}function X(e,t,n=!1){const r=E(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ee(e,t,n){let r;switch(n){case"media":r=e=>{const t=P(e);return N(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=x;break;case"links":r=e=>_(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(a);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=F;break;default:return[]}return t.reduce((t,n)=>(e[n]&&r(e[n])&&t.push(n),t),[])}function te(e){const{audio:t,voice:n,video:r}=k(e),u=t||n||r;if(u)return u.duration}function ne(e,t){return`${e}_${t}`}n(61)},function(e,t,n){"use strict";var r=n(69);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat})),n.o(r,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return r.ApiMessageEntityTypes})),n.o(r,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return r.MAIN_THREAD_ID})),n.o(r,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return r.MESSAGE_DELETED}));var u=n(70);n.o(u,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return u.ApiMediaFormat})),n.o(u,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return u.ApiMessageEntityTypes})),n.o(u,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return u.MAIN_THREAD_ID})),n.o(u,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return u.MESSAGE_DELETED}));var d=n(71);n.d(t,"ApiMessageEntityTypes",(function(){return d.a})),n.d(t,"MAIN_THREAD_ID",(function(){return d.b})),n.d(t,"MESSAGE_DELETED",(function(){return d.c}));var o=n(72);n.o(o,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return o.ApiMediaFormat}));var c=n(73);n.d(t,"ApiMediaFormat",(function(){return c.a}));n(74),n(75),n(76)},function(e,t,n){"use strict";n.d(t,"T",(function(){return Le})),n.d(t,"nb",(function(){return Fe})),n.d(t,"W",(function(){return Be})),n.d(t,"Gb",(function(){return a})),n.d(t,"f",(function(){return f})),n.d(t,"o",(function(){return l})),n.d(t,"P",(function(){return b})),n.d(t,"O",(function(){return h})),n.d(t,"Ab",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"g",(function(){return g})),n.d(t,"L",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"M",(function(){return w})),n.d(t,"j",(function(){return O})),n.d(t,"i",(function(){return I})),n.d(t,"N",(function(){return j})),n.d(t,"h",(function(){return C})),n.d(t,"q",(function(){return E})),n.d(t,"y",(function(){return D})),n.d(t,"r",(function(){return L})),n.d(t,"m",(function(){return F})),n.d(t,"qb",(function(){return B})),n.d(t,"Y",(function(){return R})),n.d(t,"gb",(function(){return U})),n.d(t,"x",(function(){return _})),n.d(t,"Hb",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"ob",(function(){return W})),n.d(t,"rb",(function(){return H})),n.d(t,"mb",(function(){return K})),n.d(t,"C",(function(){return z})),n.d(t,"E",(function(){return V})),n.d(t,"B",(function(){return q})),n.d(t,"cb",(function(){return J})),n.d(t,"Cb",(function(){return Y})),n.d(t,"G",(function(){return Q})),n.d(t,"Db",(function(){return Z})),n.d(t,"Eb",(function(){return X})),n.d(t,"Bb",(function(){return ee})),n.d(t,"a",(function(){return te})),n.d(t,"X",(function(){return ne})),n.d(t,"k",(function(){return re})),n.d(t,"pb",(function(){return ue})),n.d(t,"D",(function(){return de})),n.d(t,"l",(function(){return oe})),n.d(t,"I",(function(){return ce})),n.d(t,"U",(function(){return ae})),n.d(t,"fb",(function(){return ie})),n.d(t,"tb",(function(){return se})),n.d(t,"K",(function(){return fe})),n.d(t,"b",(function(){return le})),n.d(t,"e",(function(){return be})),n.d(t,"Fb",(function(){return he})),n.d(t,"lb",(function(){return me})),n.d(t,"H",(function(){return pe})),n.d(t,"R",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"S",(function(){return ve})),n.d(t,"V",(function(){return we})),n.d(t,"J",(function(){return Oe})),n.d(t,"ab",(function(){return Ie})),n.d(t,"Q",(function(){return je})),n.d(t,"sb",(function(){return Ce})),n.d(t,"bb",(function(){return Ee})),n.d(t,"ub",(function(){return Se})),n.d(t,"vb",(function(){return Me})),n.d(t,"wb",(function(){return Ae})),n.d(t,"t",(function(){return xe})),n.d(t,"A",(function(){return ke})),n.d(t,"w",(function(){return Te})),n.d(t,"v",(function(){return Ne})),n.d(t,"Z",(function(){return Pe})),n.d(t,"u",(function(){return De})),n.d(t,"z",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"xb",(function(){return k})),n.d(t,"yb",(function(){return T})),n.d(t,"c",(function(){return N})),n.d(t,"F",(function(){return P})),n.d(t,"hb",(function(){return Re})),n.d(t,"ib",(function(){return Ue})),n.d(t,"kb",(function(){return _e})),n.d(t,"zb",(function(){return Ge})),n.d(t,"eb",(function(){return i})),n.d(t,"db",(function(){return s}));var r=n(19),u=n(7),d=n(5),o=n(1),c=n(4);function a(e,t){return e.users.byId[t]}function i(e){return e.settings.byKey}function s(e){return e.settings.notifyExceptions}function f(e,t){return e.chats.byId[t]}function l(e,t){const n=Object(c.U)(t);return!!n&&a(e,n)}function b(e,t){return t===e.currentUserId}function h(e,t){const n=l(e,t);return n&&Object(c.wb)(n)}function m(e){return Object.values(e.chats.byId).find(({isSupport:e})=>e)}function p(e,t){if(!Object(c.lb)(t.id)&&!Object(c.jb)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==o.Q?t.fullInfo.members.reduce((t,{userId:n})=>e.users.byId[n]&&Object(c.xb)(e.users.byId[n])&&n!==e.currentUserId?t+1:t,0):t.fullInfo.onlineCount}function g(e,t){const n=f(e,t),r=n&&Object(c.U)(n),u=r&&a(e,r);if(u&&Object(c.wb)(u))return u}function y(e,t){const n=f(e,t),r=g(e,t);if(!n||!r)return!1;if(n.lastMessage&&Object(c.rb)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:o}=u.threadsById[d.MAIN_THREAD_ID]||{};return o&&!o.length}function v(e){return Boolean(e.chats.listIds.active)}function w(e,t,n){const{listIds:r}=e.chats;if(n){const e=r[n];return Boolean(e&&e.includes(t))}return Object.values(r).some(e=>e&&e.includes(t))}function O(e,t){const n=f(e,t);if(n&&w(e,t))return n.folderId===o.h?"archived":"active"}function I(e,t){return e.chatFolders.byId[t]}function j(e,t,n=o.b){const{active:r,archived:u}=e.chats.orderedPinnedIds;if(n===o.b)return!!r&&r.includes(t);if(n===o.h)return!!u&&u.includes(t);const{byId:d}=e.chatFolders,{pinnedChatIds:c}=d[n]||{};return!!c&&c.includes(t)}function C(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find(e=>e.username&&e.username.toLowerCase()===n)}function E(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId;return t.reduce((t,r)=>{const u=n[r];return u&&u.unreadCount&&!Object(c.Cb)(u,i(e),s(e))?t+u.unreadCount:t},0)}var S=n(3);function M(e){return e.stickers.search}function A(e){return e.gifs.search}function k(e,t){return e.stickers.setsById[t]}function T(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach(({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))}),r}function N(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=t.replace("️","");return n.stickers.find(e=>e.emoji===t||e.emoji===r)}function P(e,t){return e.emojiKeywords[t]&&void 0!==e.emojiKeywords[t]?e.emojiKeywords[t]:void 0}function D(e){const{messageLists:t}=e.messages;if(t&&t.length)return t[t.length-1]}function L(e){const{chatId:t}=D(e)||{};return t?f(e,t):void 0}function F(e,t){const n=e.messages.byChatId[t];return n?n.byId:void 0}function B(e,t){const n=e.scheduledMessages.byChatId[t];return n?n.byId:void 0}function x(e,t,n,r){const u=e.messages.byChatId[t];if(!u)return;const d=u.threadsById[n];return d?d[r]:void 0}function R(e,t,n){return x(e,t,n,"listedIds")}function U(e,t,n){return x(e,t,n,"outlyingIds")}function _(e,t,n,r){switch(r){case"thread":return G(e,t,n);case"pinned":return $(e,t);case"scheduled":return W(e,t)}}function G(e,t,n){return x(e,t,n,"viewportIds")}function $(e,t){return x(e,t,d.MAIN_THREAD_ID,"pinnedIds")}function W(e,t){return x(e,t,d.MAIN_THREAD_ID,"scheduledIds")}function H(e,t,n){return x(e,t,n,"scrollOffset")}function K(e,t,n){return x(e,t,n,"replyingToId")}function z(e,t,n){return x(e,t,n,"editingId")}function V(e,t){return x(e,t,d.MAIN_THREAD_ID,"editingScheduledId")}function q(e,t,n){return x(e,t,n,"draft")}function J(e,t,n){return x(e,t,n,"noWebPage")}function Y(e,t,n){return x(e,t,n,"threadInfo")}function Q(e,t,n){return x(e,t,n,"firstMessageId")}function Z(e,t,n){if(n===d.MAIN_THREAD_ID)return f(e,t);const r=Y(e,t,n);return r?f(e,r.originChannelId||t):void 0}function X(e,t,n){if(n===d.MAIN_THREAD_ID)return;const r=Y(e,t,n);return r?r.topMessageId:void 0}function ee(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:u,replyToTopMessageId:d}=n;return u||d?Object.values(r.threadsById).find(e=>e.threadInfo&&(u&&u===e.threadInfo.topMessageId||d&&d===e.threadInfo.topMessageId)):void 0}function te(e,t,n){const r=D(e);if(!r)return!1;const{threadInfo:u}=ee(e,t,n)||{};return t===r.chatId&&(r.threadId===d.MAIN_THREAD_ID||u&&r.threadId===u.threadId)}function ne(e,t,n){const r=G(e,t,n);if(!r||!r.length)return!0;let u;if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n||!n.lastMessage)return!0;u=n.lastMessage.id}else{const r=Y(e,t,n);if(!r||!r.lastMessageId)return;u=r.lastMessageId}return u>=o.J&&!re(e,t,u)||r[r.length-1]>=u}function re(e,t,n){const r=F(e,t);return r?r[n]:void 0}function ue(e,t,n){const r=B(e,t);return r?r[n]:void 0}function de(e,t,n,r){if("scheduled"===r){const n=V(e,t);return n?ue(e,t,n):void 0}{const r=z(e,t,n);return r?re(e,t,r):void 0}}function oe(e,t){let n;for(const r of Object.values(e.messages.byChatId)){const{byId:e}=r;if(n=Object.values(e).find(e=>e.content.poll&&e.content.poll.id===t),n)break}return n}function ce(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function ae(e,t){const n=ce(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function ie(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=f(e,t.chatId)||{};return Object(c.sb)(t)||!n||n0?a(e,n):f(e,n)}function fe(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?f(e,n.fromChatId):n.senderUserId?a(e,n.senderUserId):void 0}function le(e,t,n){const r=f(e,t.chatId);if(!r||r.isRestricted)return{};const u=Object(c.lb)(r.id),d=b(e,t.chatId),o=Object(c.ib)(r),a=Object(c.nb)(r),i=Object(c.jb)(r),s=Object(c.vb)(t),l=Object(c.tb)(t),h=Object(c.db)(t),{content:m}=t,p=(d||Date.now()-1e3*t.date<1728e5)&&!(m.sticker||m.contact||m.poll||m.action||m.audio||m.video&&m.video.isRound)&&!Object(c.qb)(t)&&!t.viaBotId,g=Object(c.e)(r,n)&&!s,y=u||r.isCreator||!i&&!Object(c.yb)(r,"pinMessages")||Object(c.q)(r,"pinMessages");let v=!h&&y,w=!1;const O=$(e,r.id);v&&(w=Boolean(O&&O.includes(t.id)),v=!w);const I=u||l||o||r.isCreator||Object(c.q)(r,"deleteMessages"),j=I&&!s&&(u&&!d||o&&(l||Object(c.q)(r,"deleteMessages"))),C=!h&&p&&(l||i&&(r.isCreator||Object(c.q)(r,"editMessages"))),E=!h&&!s,S=Boolean(t.content.sticker),M=S&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some(({id:e})=>e===t.id)}(e,t.content.sticker),A=!h&&S&&!M,k=!h&&M,T=!h,N=!h&&(i||a),P=!h;return{noOptions:[g,C,v,w,I,j,E,A,k,T,N,P].every(e=>!e),canReply:g,canEdit:C,canPin:v,canUnpin:w,canDelete:I,canDeleteForAll:j,canForward:E,canFaveSticker:A,canUnfaveSticker:k,canCopy:T,canCopyLink:N,canSelect:P}}function be(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=D(e)||{},u=n&&F(e,n);if(!u||!t||!r)return{};const d=t.map(t=>u[t]&&le(e,u[t],r)).filter(Boolean);return{canDelete:d.every(e=>e.canDelete),canDeleteForAll:d.every(e=>e.canDeleteForAll)}}function he(e,t){const n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id];return n?n.progress:void 0}function me(e,t,n){if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?Object(c.sb)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=Y(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function pe(e,t,n){const r=f(e,t);if(n===d.MAIN_THREAD_ID){if(!r)return}else{const r=Y(e,t,n);if(!r||r.lastMessageId===r.lastReadInboxMessageId)return}const u=U(e,t,n),o=R(e,t,n),c=F(e,t);if(!c||!u&&!o)return;const a=me(e,t,n);if(a||!r||!r.isNotJoined){if(u){const e=a?u.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):u[0];if(e)return e}if(o){const e=a?o.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):o[0];if(e)return e}}}function ge(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ye(e,t){const n=Object.values(e.chats.byId).find(e=>Object(c.ob)(e)&&e.lastMessage&&e.lastMessage.id===t);if(n)return n.id;const{byChatId:r}=e.messages;return Number(Object.keys(r).find(n=>{const u=f(e,Number(n));return u&&Object(c.ob)(u)&&r[u.id].byId[t]}))}function ve(e){const{selectedMessages:t}=e;return Boolean(t)}function we(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function Oe(e,t,n){const r=F(e,t);if(r)return Object.values(r).filter(e=>e.groupedId===n&&e.forwardInfo).map(({forwardInfo:e})=>e.fromMessageId)}function Ie(e,t,n){const r=F(e,t);if(r)return Object.keys(r).map(Number).filter(e=>r[e].groupedId===n)}function je(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const u=Ie(e,t,n);return u&&u.every(e=>r.includes(e))}function Ce(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Ee(e,t){const n=f(e,t);if(!n)return;if(!h(e,n))return;const r=F(e,t),u=G(e,t,d.MAIN_THREAD_ID);if(!r||!u)return;const o=Object(S.g)(u,e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons)),c=Object(S.g)(u,e=>Boolean(r[e].shouldHideKeyboardButtons));return o&&c&&c>o?void 0:o?r[o]:void 0}function Se(e,t,n,r){const{shouldAutoDownloadMediaFromContacts:u,shouldAutoDownloadMediaInPrivateChats:d,shouldAutoDownloadMediaInGroups:o,shouldAutoDownloadMediaInChannels:a}=e.settings.byKey;return Boolean(d&&Object(c.lb)(n.id)||o&&Object(c.kb)(n)||a&&Object(c.jb)(n)||u&&r&&(r.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,r)))}function Me(e,t){const n=Object(c.P)(t);if(!n)return;const{shouldAutoPlayVideos:r,shouldAutoPlayGifs:u}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||u&&d}function Ae(e){return e.settings.byKey.shouldLoopStickers}function ke(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=Object(c.a)(t,n),u=e.localTextSearch.byChatThreadKey[r];return u&&u.isActive?u:void 0}function Te(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=D(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ne(e){const t=Te(e);if(t)return e.localMediaSearch.byChatId[t]}function Pe(e,t){return e.management.byChatId[t]}function De(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;if(Object(c.lb)(t))return"user";const r=f(e,t);return r?Object(c.kb)(r)?"group":"channel":void 0}function Le(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Fe(e){const{users:t,isChatInfoShown:n}=e,d=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),o=Boolean(!u.g&&ke(e)),c=function(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),a=void 0!==M(e).query,i=void 0!==A(e).query,{chatId:s}=D(e)||{},f=t.selectedId,l=v(e),b=Boolean(f&&l),h=Boolean(s&&l)&&n;return d?r.l.PollResults:o?r.l.Search:c?r.l.Management:a?r.l.StickerSearch:i?r.l.GifSearch:b?r.l.UserInfo:h?r.l.ChatInfo:void 0}function Be(e){return void 0!==Fe(e)}function xe(e){return e.globalSearch.query}function Re(e){return e.payment.messageId}function Ue(e){return e.payment.formId}function _e(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function Ge(e){return e.payment.stripeCredentials}},function(e,t,n){"use strict";n.d(t,"o",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"e",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"j",(function(){return a})),n.d(t,"l",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"m",(function(){return f})),n.d(t,"d",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"h",(function(){return m})),n.d(t,"c",(function(){return p})),n.d(t,"a",(function(){return g})),n.d(t,"n",(function(){return y})),n.d(t,"p",(function(){return w}));var r=n(1);const u=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="Mac OS":-1!==["iPhone","iPad","iPod"].indexOf(t)?n="iOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(t)?n="Windows":/Android/.test(e)?n="Android":/Linux/.test(t)&&(n="Linux"),n}(),d="Mac OS"===u,o="iOS"===u,c="Android"===u,a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=window.matchMedia("(pointer: coarse)").matches,s=window.innerWidth<=r.db||window.innerWidth<=r.cb&&window.innerHeight<=r.bb,f=navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext),l=(document.documentElement.style,u&&(d||o)),b="serviceWorker"in navigator,h=b,m=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),p=!r.E&&"filter"in(document.createElement("canvas").getContext("2d")||{}),g=window.devicePixelRatio||1,y=!0;let v;function w(){return Boolean(v)}new Promise(e=>{const t=new Image;t.src="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";const n=()=>{e(2===t.height)};t.onload=n,t.onerror=n}).then(e=>{v=e})},function(e,t,n){"use strict";t.a=(...e)=>e.filter(Boolean).join(" ")},function(e,t,n){"use strict";function r(e,t,n=!0,r=!0){let u;return(...d)=>{u?(clearTimeout(u),u=void 0):n&&e(...d),u=self.setTimeout(()=>{r&&e(...d),u=void 0},t)}}function u(e,t,n=!0){let r,u,d;return(...o)=>{u=!0,d=o,r||(n&&(u=!1,e(...d)),r=self.setInterval(()=>{if(!u)return self.clearInterval(r),void(r=void 0);u=!1,e(...d)},t))}}function d(e){return c(h,e)}function o(e){return c(m,e)}function c(e,t){let n,r=!1;return(...u)=>{n=u,r||(r=!0,e(()=>{r=!1,t(...n)}))}}function a(e){Promise.resolve().then(e)}function i(e){self.requestIdleCallback?self.requestIdleCallback(e):a(e)}n.d(t,"a",(function(){return r})),n.d(t,"g",(function(){return u})),n.d(t,"i",(function(){return d})),n.d(t,"h",(function(){return o})),n.d(t,"d",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return s})),n.d(t,"f",(function(){return f})),n.d(t,"b",(function(){return h}));const s=e=>new Promise(t=>{setTimeout(()=>t(),e)});function f(){return new Promise(e=>{h(e)})}let l,b;function h(e,t=!1){l?t?b.push(e):l.push(e):(l=t?[]:[e],b=t?[e]:[],requestAnimationFrame(()=>{const e=l,t=b;l=void 0,b=void 0,t.forEach(e=>e()),e.forEach(e=>e())}))}function m(e){h(e,!0)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));var r=n(81),u=n.n(r),d=n(1),o=n(28);let c;const a=new Map,i=new Map;function s(e,t){return c||(d.p&&console.log(">>> START LOAD WORKER"),c=new u.a,function(e){c.addEventListener("message",({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){const e=a.get(t.messageId);e&&e.callback&&e.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}(e)),b({type:"initApi",args:[t]})}function f(e,...t){if(c)return b({type:"callMethod",name:e,args:t});d.p&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&c.postMessage({type:"cancelProgress",messageId:t})}function b(e){const t=Object(o.a)(a),n={messageId:t,...e},r={messageId:t},u=new Promise((e,t)=>{Object.assign(r,{resolve:e,reject:t})});if("function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,i.set(e,r)}return a.set(t,r),u.catch(()=>{}).finally(()=>{a.delete(t),r.callback&&i.delete(r.callback)}),c.postMessage(n),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(1);let u;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(u||(u={}));const d={},o={};async function c(e,t){if(!d[e]){switch(e){case u.Auth:d[u.Auth]=n.e(5).then(n.bind(null,106));break;case u.Main:r.p&&console.log(">>> START LOAD MAIN BUNDLE"),d[u.Main]=Promise.all([n.e(0),n.e(4)]).then(n.bind(null,105));break;case u.Extra:d[u.Extra]=Promise.all([n.e(0),n.e(3)]).then(n.bind(null,104))}d[e].then(f)}const c=await d[e];return o[e]||(o[e]=c),a(e,t)}function a(e,t){const n=o[e];if(n)return n[t]}const i=[];function s(e){i.includes(e)||i.push(e)}function f(){i.forEach(e=>{e()})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"c",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"b",(function(){return c}));const r=self.caches;let u;async function d(e,t,n){if(r)try{const d=new Request(t),o=await r.open(e),c=await o.match(d);if(!c)return;switch(n){case u.Text:return await c.text();case u.Blob:{const e=await c.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=c.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case u.Json:return await c.json();default:return}}catch(e){return void console.warn(e)}}async function o(e,t,n){if(r)try{const u="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t),o=new Response(u),c=await r.open(e);return await c.put(d,o)}catch(e){return void console.warn(e)}}async function c(e){try{if(!r)return;return await r.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(u||(u={}))},function(e,t,n){"use strict";n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l}));var r=n(9);function u(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...r}=n;super(e,{type:t}),u(this,"name",void 0),Object.assign(this,r)}else super(e),u(this,"name",void 0);this.name=t}});function d(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let u=r.length;const d=new Uint8Array(u);for(;u--;)d[u]=r.charCodeAt(u);return new Blob([d],{type:n})}function o(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=e=>{const{result:r}=e.target||{};"string"==typeof r&&t(r),n(new Error("Failed to read blob"))},r.onerror=n,r.readAsDataURL(e)})}function c(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function a(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e})}function i(e){return new Promise((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e})}async function s(e){const t=await i(e);return Promise.race([Object(r.e)(2e3),new Promise((e,n)=>{t.onseeked=()=>{const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;n.getContext("2d").drawImage(t,0,0),e(n.toDataURL("image/jpeg"))},t.onerror=n,t.currentTime=Math.min(t.duration,1)})])}async function f(e){return(await fetch(e)).blob()}function l(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return v})),n.d(t,"b",(function(){return j})),n.d(t,"c",(function(){return C}));var r=n(1),u=n(12),d=n(10);var o=n(3),c=n.p+"en-extra.e73049da90714ecdae3233e8ffa74d39.json",a=n.p+"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json",i=n.p+"it-extra.78e5568451a888818c7e2209e05a9602.json",s=n.p+"pl-extra.38fd67a6c26e58f5c912568332c7c074.json",f=n.p+"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json",l=n(51),b=n(2);const h={en:c,es:a,it:i,pl:s,ru:f},m=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],p={en:e=>1!==e?6:2,ar:e=>0===e?1:1===e?2:2===e?3:e%100>=3&&e%100<=10?4:e%100>=11?5:6,ca:e=>1!==e?6:2,de:e=>1!==e?6:2,es:e=>1!==e?6:2,fa:e=>e>1?6:2,fr:e=>e>1?6:2,id:()=>0,it:e=>1!==e?6:2,ko:()=>0,ms:()=>0,nl:e=>1!==e?6:2,pl:e=>1===e?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,pt_BR:e=>e>1?6:2,ru:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,tr:e=>e>1?6:2,uk:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,uz:e=>e>1?6:2},g=new Map;let y;const{addCallback:v,removeCallback:w,runCallbacks:O}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach(e=>{e(...t)})},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let I;const j=(e,t,n)=>{if(void 0!==t){const r=g.get(`${e}_${t}_${n}`);if(r)return r}if(!y)return e;const r=y[e];if(!r)return e;const u=r["number"==typeof t?function(e){const t=I&&p[I]?p[I](e):0;return m[t]}(t):"value"];if(!u||!u.trim()){const t=e.split(".");return t[t.length-1]}if(void 0!==t){const r=function(e,t){return e.replace(/%\d?\$?[sdf@]/,String(t))}(u,"i"===n?Object(l.a)(t):t);return g.set(`${e}_${t}_${n}`,r),r}return u};async function C(e,t){if(y&&e===I)return void(t&&t());const n=await async function(e){const t=await u.c(r.F,e,u.a.Json);if(t)return t;const n=await Object(d.a)("fetchLangPack",{sourceLangPacks:r.G,langCode:e});if(n)return await u.d(r.F,e,n.langPack),n.langPack;return}(e);if(!n)return;if(h[e])try{const t=await fetch(h[e]),r=await t.json(),u=Object(o.i)(r,(e,t)=>({key:t,value:e}));Object.assign(n,u)}catch(e){r.p&&console.error(e)}g.clear(),I=e,y=n,document.documentElement.lang=e;const{languages:c}=Object(b.e)().settings.byKey,a=c?c.find(t=>t.langCode===e):void 0;j.isRtl=Boolean(a&&a.rtl),t&&t(),O(y)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d}));const r=/\uFE0F/g,u=String.fromCharCode(8205);function d(e){return e.indexOf(u)<0?e.replace(r,""):e}t.a=/(?:\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d\udc8f\ud83c[\udffb-\udfff]|\ud83d\udc91\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d\udc8f\udc91])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd4\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83d\ude36\u200d\ud83c\udf2b\ufe0f|\u2764\ufe0f\u200d\ud83d\udd25|\u2764\ufe0f\u200d\ud83e\ude79|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83d\ude2e\u200d\ud83d\udca8|\ud83d\ude35\u200d\ud83d\udcab|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udc8e\udc90\udc92-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g},function(e,t,n){"use strict";var r=n(0),u=n(20);n(95);t.a=Object(r.h)(({color:e="blue"})=>r.a.createElement("div",{className:"Loading"},r.a.createElement(u.a,{color:e,withBackground:"white"===e})))},function(e,t,n){"use strict";var r=n(0),u=n(11),d=n(26);t.a=(e,t,n=!1,o=!1)=>{const c=Object(u.c)(e,t),a=Object(d.a)();return o&&Object(u.b)(a),Object(r.n)(()=>{n||c||Object(u.d)(e,t).then(a)},[e,a,c,t,n]),c}},function(e,t,n){"use strict";n.d(t,"d",(function(){return o})),n.d(t,"e",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return d}));const r={},u=/(\d{1,3})(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,3})?/;var d="AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234".split("\n").map(e=>({id:e.substr(0,2),flag:e.substr(2,4),code:"+"+e.match(/\d+/)[0],name:e.split(/\d+/)[1],phoneFormat:function(e){if(!e)return u;const t=e[0];let n;if(!r[t]){const e=t.split("").map(Number);n=e.reduce((e,t,n)=>`${e}(\\d{1,${t}})${n>0?"?":""}`,""),r[t]=new RegExp(`${n}${"()?".repeat(5-e.length)}`)}return r[t]}(e.match(/\d+$/))}));function o(e){return d.find(t=>t.id===e)}function c(e){let t=e.replace(/[^\d+]+/g,"");t.startsWith("+")||(t="+"+t);const n=d.filter(e=>t.startsWith(e.code)).sort((e,t)=>e.code.length-t.code.length);return n[n.length-1]}function a(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.code.length-1);else if(e.startsWith("+"))return e;return n=n.replace(function(e){return e?e.phoneFormat:u}(t),(e,n,r,u,d,o)=>{const c=t&&"GB"===t.id?" ":"-";let a="";return n&&(a=""+n),r&&(a+=" "+r),u&&(a+=`${c}${u}`),d&&(a+=`${c}${d}`),o&&(a+=`${c}${o}`),a}),n}function i(e){const t=e.startsWith("+")?e:"+"+e,n=c(t);return n?`${n.code} ${a(t,n)}`:t}},function(e,t,n){"use strict";let r,u,d,o,c,a,i,s,f,l,b,h;n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"m",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"a",(function(){return s})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"g",(function(){return p})),function(e){e[e.Backwards=0]="Backwards",e[e.Forwards=1]="Forwards",e[e.Around=2]="Around"}(r||(r={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Static=2]="Static"}(u||(u={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.Language=3]="Language",e[e.General=4]="General",e[e.GeneralChatBackground=5]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=6]="GeneralChatBackgroundColor",e[e.Privacy=7]="Privacy",e[e.PrivacyPhoneNumber=8]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=9]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=10]="PrivacyProfilePhoto",e[e.PrivacyForwarding=11]="PrivacyForwarding",e[e.PrivacyGroupChats=12]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=13]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=14]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=15]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=16]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=17]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=18]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=19]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=20]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=21]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=22]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=23]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=24]="PrivacyBlockedUsers",e[e.Folders=25]="Folders",e[e.FoldersCreateFolder=26]="FoldersCreateFolder",e[e.FoldersEditFolder=27]="FoldersEditFolder",e[e.FoldersIncludedChats=28]="FoldersIncludedChats",e[e.FoldersExcludedChats=29]="FoldersExcludedChats",e[e.TwoFaDisabled=30]="TwoFaDisabled",e[e.TwoFaNewPassword=31]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=32]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=33]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=34]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=35]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=36]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=37]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=38]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=39]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=40]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=41]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=42]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=43]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=44]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=45]="TwoFaCongratulations"}(d||(d={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(o||(o={})),function(e){e[e.ChatList=0]="ChatList",e[e.Media=1]="Media",e[e.Links=2]="Links",e[e.Files=3]="Files",e[e.Music=4]="Music",e[e.Voice=5]="Voice"}(c||(c={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults"}(a||(a={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.MiddleHeaderAvatar=4]="MiddleHeaderAvatar",e[e.Album=5]="Album",e[e.ScheduledAlbum=6]="ScheduledAlbum",e[e.SearchResult=7]="SearchResult"}(i||(i={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(s||(s={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(f||(f={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(l||(l={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(b||(b={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(h||(h={}));const m="UPLOADING_WALLPAPER_SLUG";let p;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(p||(p={}))},function(e,t,n){"use strict";var r=n(0),u=n(8);n(91);t.a=({color:e="blue",withBackground:t})=>r.a.createElement("div",{className:Object(u.a)("Spinner",e,t&&"with-background")},r.a.createElement("div",null))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(1),u=n(9);window.addEventListener("error",c),window.addEventListener("unhandledrejection",c);const d=Date.now();let o=!1;function c(e){e.preventDefault(),a(e instanceof ErrorEvent?e.error:e.reason)}Object(u.g)(window.alert,1e3);function a(e){if(console.error(e),!o)return Date.now()-d<=5e3&&localStorage.getItem(r.B)?(localStorage.removeItem(r.B),o=!0,void window.location.reload()):void 0}},function(e,t,n){"use strict";(function(e){n.d(t,"f",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"e",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"d",(function(){return l}));var r=n(43),u=n(1),d=n(12);const o=[1,2,3,4,5];function c(e,t){const{mainDcId:n,keys:r,hashes:d}=e;localStorage.setItem(u.nb,JSON.stringify({dcID:n,id:t})),localStorage.setItem("dc",String(n)),Object.keys(r).map(Number).forEach(e=>{localStorage.setItem(`dc${e}_auth_key`,JSON.stringify(r[e]))}),Object.keys(d).map(Number).forEach(e=>{localStorage.setItem(`dc${e}_hash`,JSON.stringify(d[e]))})}function a(){[u.nb,"dc",...o.map(e=>`dc${e}_auth_key`),...o.map(e=>`dc${e}_hash`)].forEach(e=>{localStorage.removeItem(e)})}function i(){const e=localStorage.getItem(u.nb);if(!e)return;const{dcID:t}=JSON.parse(e),n={},r={};return o.forEach(e=>{try{const t=localStorage.getItem(`dc${e}_auth_key`);t&&(n[e]=JSON.parse(t));const u=localStorage.getItem(`dc${e}_hash`);u&&(r[e]=JSON.parse(u))}catch(e){u.p&&console.warn("Failed to load stored session",e)}}),Object.keys(n).length?{mainDcId:t,keys:n,hashes:r}:void 0}async function s(){const e=localStorage.getItem(u.H);if(!e)return;const t=await r.b("GramJs:"+e);try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load legacy session",e)}}async function f(){localStorage.removeItem(u.H);const e=await r.c();await Promise.all([d.b("GramJs"),...e.filter(e=>"string"==typeof e&&e.startsWith("GramJs:GramJs-session-")).map(e=>r.a(e))])}function l(){const t=e.env.TEST_SESSION;try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load test session",e)}}}).call(this,n(87))},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(0),u=n(15),d=n(1),o=n(7),c=n(66),a=n(8),i=n(77),s=n(58);const f=/^[\d\wа-яё]$/i,l=/(\*\*|__).+?\1/g;function b(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML]),[])}(e);case"hq_emoji":return u.a.lastIndex=0,h(e,"big","jsx");case"emoji":return u.a.lastIndex=0,h(e,"small","jsx");case"emoji_html":return u.a.lastIndex=0,h(e,"small","html");case"br":return m(e,"jsx");case"br_html":return m(e,"html");case"highlight":return d=e,o=n.highlight,d.reduce((e,t)=>{if("string"!=typeof t||!o)return[...e,t];const n=t.toLowerCase(),u=n.indexOf(o.toLowerCase()),d=n[u+o.length];if(u<0||d&&d.match(f))return[...e,t];const c=[];return c.push(t.substring(0,u)),c.push(r.a.createElement("span",{className:"matching-text-highlight"},t.substring(u,u+o.length))),c.push(t.substring(u+o.length)),[...e,...c]},[]);case"links":return function(e){return e.reduce((e,t)=>{if("string"!=typeof t)return[...e,t];const n=[...t.match(p)||[],...t.match(g)||[]];if(!n.length)return[...e,t];const u=[];let d=n.shift(),o=0;for(;d;){const e=t.indexOf(d,o);u.push(t.substring(o,e)),d.startsWith("@")?u.push(r.a.createElement(i.a,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),u.push(r.a.createElement(s.a,{text:d,url:d}))),o=e+d.length,d=n.shift()}return u.push(t.substring(o)),[...e,...u]},[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var d,o;return e},[e])}function h(e,t,n){return e.reduce((e,d)=>{if("string"!=typeof d)return[...e,d];const i=d.split(u.a),s=d.match(u.a)||[];return e.push(i[0]),s.reduce((e,d,s)=>{const f=Object(c.a)(Object(u.b)(d)),l=Object(a.a)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(o.d?r.a.createElement("span",{className:"font-emoji"},d):r.a.createElement("img",{className:l,src:`./img-apple-${"big"===t?"160":"64"}/${f}.png`,alt:d})),"html"===n&&e.push(o.d?d:`${d}`);const b=2*s+2;return i[b]&&e.push(i[b]),e},e)},[])}function m(e,t){return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce((e,n,u,d)=>{const o=n.trimLeft(),c=n.length-o.length;return e.push(String.fromCharCode(160).repeat(c)+o),u!==d.length-1&&e.push("jsx"===t?r.a.createElement("br",null):"
"),e},[])],[])}const p=new RegExp(d.gb,"ig"),g=/@[\w\d_-]+/gi;function y(e,t){return e.reduce((e,n)=>{if("string"!=typeof n)return[...e,n];const u=n.split(l),d=n.match(l)||[];return e.push(u[0]),d.reduce((e,n,d)=>{"jsx"===t?e.push(n.startsWith("**")?r.a.createElement("b",null,n.replace(/\*\*/g,"")):r.a.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const o=2*d+2;return u[o]&&e.push(u[o]),e},e)},[])}},function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;const n=Object.keys(e),r=n.length;if(r!==Object.keys(t).length)return!1;if(0===r)return!0;for(let u=0;ue[n]!==t[n])}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u}))},function(e,t,n){"use strict";var r=n(14),u=n(26),d=n(40);t.a=()=>{const e=Object(u.a)();return Object(d.a)(()=>r.a(e),[e]),r.b}},function(e,t,n){"use strict";var r=n(0);t.a=()=>{const[,e]=Object(r.r)(!1);return Object(r.m)(()=>{e(e=>!e)},[])}},function(e,t,n){"use strict";var r=n(0),u=n(8);n(89);t.a=({children:e,className:t,isRtl:n,onClick:d})=>{const o=Object(r.m)(e=>{e.preventDefault(),d(e)},[d]);return r.a.createElement("a",{href:"#",className:Object(u.a)("Link",t),dir:n?"rtl":"auto",onClick:d?o:void 0},e)}},function(e,t,n){"use strict";t.a=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},function(e,t,n){"use strict";n.d(t,"d",(function(){return p})),n.d(t,"c",(function(){return g})),n.d(t,"b",(function(){return y})),n.d(t,"a",(function(){return v}));var r=n(10),u=n(68),d=n(1),o=n(2),c=n(4),a=n(14),i=n(37),s=n(6),f=n(7);function l(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function b(){return!!f.k&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(d.p&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(d.p&&console.warn("[PUSH] Push messaging isn't supported."),!1):(d.p&&console.warn("[PUSH] Push notifications aren't supported."),!1))}async function h(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function m(e){const t=Object(o.e)(),n=Object(o.d)();if(e)try{const t=l(e);return await Object(r.a)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){d.p&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await Object(r.a)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function p(){if(!b())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await m(t)}async function g(){if(async function(){const[e]=await Promise.all([Object(r.a)("fetchNotificationSettings"),Object(r.a)("fetchNotificationExceptions")]);e&&Object(o.g)(Object(i.v)(Object(o.e)(),e))}(),!b())return void await h();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=Object(o.e)();return!t.push||!e||(l(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5)}(t)){await m(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=l(t);d.p&&console.log("[PUSH] Received push subscription: ",n),await Object(r.a)("registerDevice",n),Object(o.d)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?d.p&&console.warn("[PUSH] The user has blocked push notifications."):d.p&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await h())}}}function y({chat:e,message:t,isActiveChat:n}){if(!("Notification"in window?"denied"!==Notification.permission||(d.p&&console.warn("[PUSH] The user has blocked push notifications."),0):(d.p&&console.warn("[PUSH] This browser does not support desktop notification"),0)))return;if(!t.id)return;if(!function(e,t){const n=Object(o.e)();if(Object(c.Cb)(e,Object(s.eb)(n),Object(s.db)(n))||e.isNotJoined)return!1;if(t&&document.hasFocus())return!1;switch(e.type){case"chatTypePrivate":case"chatTypeSecret":return Boolean(n.settings.byKey.hasPrivateChatsNotifications);case"chatTypeBasicGroup":case"chatTypeSuperGroup":return Boolean(n.settings.byKey.hasGroupNotifications);case"chatTypeChannel":return Boolean(n.settings.byKey.hasBroadcastNotifications)}return!1}(e,n))return;const{title:r,body:i}=function(e,t){const n=Object(o.e)(),{senderId:r,replyToMessageId:d}=t,i=r?Object(s.Gb)(n,r):void 0,f=Object(c.t)(t),l=f&&d?Object(s.k)(n,e.id,d):void 0,{targetUserId:b,targetChatId:h}=f||{},m=b?Object(s.Gb)(n,b):void 0,p=Object(c.U)(e),g=p?Object(s.Gb)(n,p):void 0;let y;if(Object(c.db)(t)){const n=e&&(Object(c.jb)(e)||t.senderId===t.chatId)?e:i;y=Object(u.a)(a.b,t,n,m,l,h,{asPlain:!0})}else{const n=Object(c.J)(a.b,e.id,i),r=Object(c.N)(a.b,t);y=n?`${n}: ${r}`:r}return{title:Object(c.l)(a.b,e,g),body:y}}(e,t);if(b())navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"newMessageNotification",payload:{title:r,body:i,chatId:e.id,messageId:t.id}});else{const n=Object(o.d)(),u={body:i,icon:"icon-192x192.png",badge:"icon-192x192.png",tag:t.id.toString()};"vibrate"in navigator&&(u.vibrate=[200,100,200]);const d=new Notification(r,u);d.onclick=()=>{d.close(),n.focusMessage({chatId:e.id,messageId:t.id}),window.focus&&window.focus()}}}function v(){navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"h",(function(){return b})),n.d(t,"a",(function(){return h}));var r=n(1),u=n(36),d=n(3);const o=[1,8,5,2,7,4,6];function c(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function a(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function i(e,t){if(t.id===r.mb)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!t.status)return"";switch(t.status.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:n}=t.status;if(!n)return e("LastSeen.Offline");const r=new Date,d=new Date(1e3*n);if(d>=r)return e("LastSeen.JustNow");const o=new Date(r.getTime()-d.getTime());if(o.getTime()/1e3<60)return e("LastSeen.JustNow");if(o.getTime()/1e3<3600){return e("LastSeen.MinutesAgo",Math.floor(o.getTime()/1e3/60))}const c=new Date;if(c.setHours(0,0,0,0),d>c){if(o.getTime()/1e3<21600){return e("LastSeen.HoursAgo",Math.floor(o.getTime()/1e3/60/60))}return e("LastSeen.TodayAt",Object(u.h)(d))}const a=new Date;return a.setDate(r.getDate()-1),c.setHours(0,0,0,0),d>a?e("LastSeen.YesterdayAt",Object(u.h)(d)):e("LastSeen.AtDate",Object(u.b)(e,d))}case"userStatusOnline":return e("Online");case"userStatusRecently":return e("Lately");default:return}}function s(e){const{id:t,status:n,type:u}=e;return!!n&&(t!==r.mb&&("userStatusOnline"===n.type&&"userTypeBot"!==u))}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.mb)&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function l(e){return"userTypeBot"===e.type}function b(e,t,n){return Object(d.k)(e,e=>{const r=Date.now()/1e3;if(n&&n.includes(e))return r+172800-(n.length-n.indexOf(e));const u=t[e];if(!u||!u.status)return 0;if("userStatusOnline"===u.status.type)return u.status.expires;if("userStatusOffline"===u.status.type&&u.status.wasOnline)return u.status.wasOnline;switch(u.status.type){case"userStatusRecently":return r-86400;case"userStatusLastWeek":return r-604800;case"userStatusLastMonth":return r-18144e3;default:return 0}},"desc")}function h(e){const t=e?Math.abs(e.id)%7:0;return o[t]}},function(e,t,n){"use strict";n.d(t,"w",(function(){return c})),n.d(t,"v",(function(){return a})),n.d(t,"t",(function(){return i})),n.d(t,"y",(function(){return s})),n.d(t,"u",(function(){return f})),n.d(t,"z",(function(){return l})),n.d(t,"j",(function(){return b})),n.d(t,"p",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"e",(function(){return p})),n.d(t,"f",(function(){return g})),n.d(t,"d",(function(){return y})),n.d(t,"x",(function(){return v})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"A",(function(){return I})),n.d(t,"c",(function(){return j})),n.d(t,"a",(function(){return C})),n.d(t,"o",(function(){return E})),n.d(t,"h",(function(){return S})),n.d(t,"g",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"D",(function(){return k})),n.d(t,"b",(function(){return T})),n.d(t,"C",(function(){return N})),n.d(t,"B",(function(){return P})),n.d(t,"l",(function(){return D})),n.d(t,"k",(function(){return L})),n.d(t,"q",(function(){return F})),n.d(t,"n",(function(){return B})),n.d(t,"E",(function(){return x}));var r=n(5),u=n(1),d=n(3),o=n(30);function c(e){return e>0}function a(e){return i(e)||s(e)}function i(e){return"chatTypeBasicGroup"===e.type}function s(e){return"chatTypeSuperGroup"===e.type}function f(e){return"chatTypeChannel"===e.type}function l(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function b(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function h(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function m(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function p(e){if(e.fullInfo)return e.fullInfo.about}function g(e){const{username:t}=e,{inviteLink:n}=e.fullInfo||{};return n&&n.length?n:t?"t.me/"+t:""}function y(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function v(e){return!e.lastMessage}function w(e){return Boolean(e.adminRights)}function O(e,t){return!!e.adminRights&&e.adminRights[t]}function I(e,t){return Boolean(e.currentUserBannedRights&&e.currentUserBannedRights[t]||e.defaultBannedRights&&e.defaultBannedRights[t])}function j(e,t){return t!==r.MAIN_THREAD_ID||!(e.isRestricted||e.migratedTo||e.isNotJoined)&&(!!e.isCreator||(!!c(e.id)||(f(e)?O(e,"postMessages"):w(e)||!I(e,"sendMessages"))))}function C(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=w(e);return{canAttachMedia:n||!I(e,"sendMedia"),canAttachPolls:(n||!I(e,"sendPolls"))&&(!c(e.id)||t),canSendStickers:n||!I(e,"sendStickers"),canSendGifs:n||!I(e,"sendGifs"),canAttachEmbedLinks:n||!I(e,"embedLinks")}}function E(e){return e.currentUserBannedRights&&e.currentUserBannedRights.sendMessages?"You are not allowed to send messages in this chat.":e.defaultBannedRights&&e.defaultBannedRights.sendMessages?"Sending messages is not allowed in this chat.":void 0}function S(e){if(e&&e.fullInfo)return e.fullInfo.slowMode}function M(e){return Math.max(e.joinDate||0,e.lastMessage?e.lastMessage.date:0)}function A(e){return e.folderId===u.h}function k(e,t,n){return!(n&&n[e.id]&&!n[e.id].isMuted)&&(e.isMuted||c(e.id)&&!t.hasPrivateChatsNotifications||f(e)&&!t.hasBroadcastNotifications||a(e)&&!t.hasGroupNotifications)}function T(e){return i(e)||(s(e)||f(e))&&e.isCreator}function N(e,t,n,r,u,d){const o=n.excludedChatIds?new Set(n.excludedChatIds):void 0,i=n.excludedChatIds?new Set(n.includedChatIds):void 0,s=n.excludedChatIds?new Set(n.pinnedChatIds):void 0;return[(d||Object.keys(e).map(Number)).filter(d=>function(e,t,n,r,u,d,o,i){if(d&&d.has(e.id))return!1;if(o&&o.has(e.id))return!0;if(i&&i.has(e.id))return!0;if(A(e)&&t.excludeArchived)return!1;if(t.excludeMuted&&k(e,r,u))return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(c(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(a(e))return!!t.groups;if(f(e))return!!t.channels}return!1}(e[d],n,t,r,u,o,i,s)),n.pinnedChatIds]}function P(e,t,n,r="all"){function u(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(A(e))return!1;break;case"archived":if(!A(e))return!1}return!e.isRestricted&&!e.isNotJoined}const o=t.map(t=>e[t]).filter(u),c=new Set(t);return{pinnedChats:n?n.map(t=>e[t]).filter(u).filter(e=>c.has(e.id)):[],otherChats:Object(d.k)(n?o.filter(e=>!n.includes(e.id)):o,M,"desc")}}function D(e,t,n,r,u,d){const[o]=N(e,t,n,u,d,r),c=o.map(t=>e[t]).filter(e=>e&&e.lastMessage&&!e.isRestricted&&!e.isNotJoined);return{unreadDialogsCount:c.reduce((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e,0),hasActiveDialogs:c.some(e=>e.unreadMentionsCount||!k(e,u,d)&&(e.unreadCount||e.hasUnreadMark))}}function L(e,t,n,r,u,d,o){const{id:c,title:a,emoticon:i,description:s,pinnedChatIds:f,excludedChatIds:l,includedChatIds:b,excludeArchived:h,excludeMuted:m,excludeRead:p,...g}=r;if(Object.values(g).filter(Boolean).length>1||l&&l.length||b&&b.length){return e("Chats",function(e,t,n,r,u,d){const[o,c]=N(e,t,n,u,d,r),{pinnedChats:a,otherChats:i}=P(e,o,c,"folder");return a.length+i.length}(t,n,r,u,d,o))}return g.bots?e("FilterBots"):g.groups?e("FilterGroups"):g.channels?e("FilterChannels"):g.contacts?e("FilterContacts"):g.nonContacts?e("FilterNonContacts"):void 0}function F(e){return!!e&&e.id<0}function B(e,t,n){if(n&&!c(t))return n.isSelf?e("FromYou"):Object(o.b)(n)}function x(e,t,n=!1,r){return Object(d.k)(e,e=>{const u=t[e];if(!u)return 0;let d=0;return u.lastMessage&&(d+=u.lastMessage.date),n&&u.isVerified&&(d+=3e9),r&&r.includes(e)&&(d+=Date.now()+(r.length-r.indexOf(e))),d},"desc")}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(20),o=n(45);n(93);t.a=({ref:e,type:t="button",onClick:n,onContextMenu:c,onMouseDown:a,onMouseEnter:i,onMouseLeave:s,onFocus:f,children:l,size:b="default",color:h="primary",className:m,round:p,pill:g,fluid:y,isText:v,isLoading:w,ariaLabel:O,href:I,download:j,disabled:C,ripple:E,faded:S,tabIndex:M,isRtl:A})=>{let k=Object(r.q)(null);e&&(k=e);const[T,N]=Object(r.r)(!1),P=Object(u.a)("Button",m,b,h,p&&"round",g&&"pill",y&&"fluid",C&&"disabled",v&&"text",w&&"loading",E&&"has-ripple",S&&"faded",T&&"clicked"),D=Object(r.m)(e=>{!C&&n&&n(e),N(!0),setTimeout(()=>{N(!1)},400)},[C,n]),L=Object(r.m)(e=>{e.preventDefault(),!C&&a&&a(e)},[a,C]);return I?r.a.createElement("a",{ref:k,className:P,href:I,title:O,download:j,tabIndex:M,dir:A?"rtl":void 0},l,!C&&E&&r.a.createElement(o.a,null)):r.a.createElement("button",{ref:k,type:t,className:P,onClick:D,onContextMenu:c,onMouseDown:L,onMouseEnter:i&&!C?i:void 0,onMouseLeave:s&&!C?s:void 0,onFocus:f&&!C?f:void 0,"aria-label":O,title:O,tabIndex:M,dir:A?"rtl":void 0},w?r.a.createElement("div",null,r.a.createElement("span",{dir:A?"auto":void 0},"Please wait.."),r.a.createElement(d.a,{color:v?"blue":"white"})):l,!C&&E&&r.a.createElement(o.a,null))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return b}));var r=n(1);const u=new Set(["scroll","mouseenter","mouseleave"]),d={},o=new Map,c={};function a(e,t,n){const r=s(t,e);f(r,e)?function(e,t,n){c[e]||(c[e]=0,document.addEventListener(e,h));(function(e){d[e]||(d[e]=new Map);return d[e]})(e).set(t,n),function(e){const t=o.get(e);if(t)return t;const n=new Set;return o.set(e,n),n}(t).add(e),c[e]++}(r,e,n):e.addEventListener(r,n)}function i(e,t,n){const r=s(t,e);f(r,e)?l(r,e):e.removeEventListener(r,n)}function s(e,t){const n=e.replace(/^on/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function f(e,t){return!u.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function l(e,t){c[e]--,c[e]||document.removeEventListener(e,h),d[e].delete(t),o.get(t).delete(e)}function b(e){const t=o.get(e);t&&(t.forEach(t=>l(t,e)),o.delete(e))}function h(e){const t=d[e.type];if(t){let n=!1,r=e.target;const u=()=>{n=!0},d=()=>{e.preventDefault()},o=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?u:"preventDefault"===t?d:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(o),n))return;r=r.parentNode}}}r.p&&document.addEventListener("dblclick",()=>{console.log("DELEGATED EVENTS",{delegationRegistry:d,delegatedEventsByElement:o,documentEventCounters:c})})},function(e,t,n){"use strict";var r=n(0);t.a=(e=!1)=>{const[t,n]=Object(r.r)(e);return[t,Object(r.m)(()=>{n(!0)},[]),Object(r.m)(()=>{n(!1)},[])]}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=(e=!1,t,n=!1,d="fast",o=!1)=>{const[c,a]=Object(r.r)(!e),i=Object(r.q)(),[s,f]=Object(r.r)(e&&n);e?(a(!1),f(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(f(!1),c||i.current||(i.current=window.setTimeout(()=>{a(!0),t&&t(),i.current=void 0},o?0:350)));const l=Boolean(i.current),b=e||l;return{shouldRender:b,transitionClassNames:Object(u.a)(d&&"opacity-transition",d,(s&&!o||o&&e)&&"open",b&&"shown",l&&"closing")}}},function(e,t,n){"use strict";n.d(t,"j",(function(){return o})),n.d(t,"k",(function(){return c})),n.d(t,"n",(function(){return a})),n.d(t,"h",(function(){return s})),n.d(t,"g",(function(){return f})),n.d(t,"b",(function(){return l})),n.d(t,"f",(function(){return b})),n.d(t,"c",(function(){return h})),n.d(t,"d",(function(){return p})),n.d(t,"e",(function(){return g})),n.d(t,"i",(function(){return y})),n.d(t,"a",(function(){return v})),n.d(t,"l",(function(){return O})),n.d(t,"m",(function(){return I}));const r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"],d=u.map(e=>e.toLowerCase());function o(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function c(e){return o(e).getTime()}function a(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function i(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function s(e){const t="number"==typeof e?new Date(e):e;return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function f(e,t){const n="number"==typeof t?new Date(t):t,u=o(new Date);if(n>=u)return s(n);const d=new Date(u);if(d.setDate(u.getDate()-7),n>=d)return e("Weekday.Short"+r[n.getDay()]);const c=n.getFullYear()!==u.getFullYear(),a=e(c?"formatDateScheduleYear":"formatDateSchedule")||(c?"d MMM yyyy":"d MMM");return m(e,n,a)}function l(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return m(e,n,r)}function b(e,t,n=!1){const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return m(e,t,r)}function h(e,t,n=!1,u=!1){const d="number"==typeof t?new Date(t):t,c=o(new Date);if(!u){if(i(d)===i(c))return(n?j:C)(e("Weekday.Today"));const t=new Date(c);if(t.setDate(c.getDate()-1),i(d)===i(t))return(n?j:C)(e("Weekday.Yesterday"));const u=new Date(c),o=new Date(c);if(u.setDate(c.getDate()-7),o.setDate(c.getDate()+7),d>=u&&d<=o){const t=r[d.getDay()];return n?j(e("Weekday.Short"+t)):C(e("Weekday."+t))}}const a=d.getFullYear()!==c.getFullYear(),s=e(n?a?"formatDateScheduleYear":"formatDateSchedule":a?"chatFullDate":"chatDate")||"d MMMM yyyy";return(n?j:C)(m(e,d,s))}function m(e,t,n){const r=t.getDate(),d=t.getMonth();return n.replace("LLLL",e(u[d])).replace("MMMM",e("Month.Gen"+u[d])).replace("MMM",e("Month.Short"+u[d])).replace("MM",String(d+1).padStart(2,"0")).replace("dd",String(r).padStart(2,"0")).replace("d",String(r)).replace("yyyy",String(t.getFullYear()))}function p(e,t){const n="number"==typeof t?new Date(t):t;return`${h(e,n,!0)}, ${s(n)}`}function g(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%3600%60);let u="";return t>0?(u+=String(t).padStart(2,"0")+":",u+=String(n).padStart(2,"0")+":"):u+=String(n)+":",u+=String(r).padStart(2,"0"),u}function y(e){const t=[];let n=e%1e3;e-=n,n=Math.floor(n/10);const r=(e=Math.floor(e/1e3))%60;e-=r;const u=(e=Math.floor(e/60))%60;e-=u;const d=(e=Math.floor(e/60))%60;return d>0&&t.push(String(d).padStart(2,"0")),t.push(String(u).padStart(d>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function v(e){return e.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function O(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?r+"-":""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const u=e.split(" "),o=t?u[0]:u[1],c=(t?u[1]:u[0]).toLowerCase(),a=d.findIndex(e=>e.startsWith(c));return-1!==a&&w(Number(o),a)?`${String(a+1).padStart(2,"0")}-${String(o).padStart(2,"0")}`:void 0}function I(e){return e+86400}function j(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function C(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},function(e,t,n){"use strict";n.d(t,"r",(function(){return d})),n.d(t,"I",(function(){return o})),n.d(t,"s",(function(){return c})),n.d(t,"H",(function(){return a})),n.d(t,"M",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"K",(function(){return f})),n.d(t,"J",(function(){return l})),n.d(t,"N",(function(){return m})),n.d(t,"x",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"b",(function(){return w})),n.d(t,"L",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"j",(function(){return j})),n.d(t,"k",(function(){return C})),n.d(t,"V",(function(){return E})),n.d(t,"db",(function(){return S})),n.d(t,"g",(function(){return A})),n.d(t,"z",(function(){return k})),n.d(t,"kb",(function(){return T})),n.d(t,"lb",(function(){return N})),n.d(t,"u",(function(){return P})),n.d(t,"P",(function(){return D})),n.d(t,"O",(function(){return L})),n.d(t,"m",(function(){return F})),n.d(t,"G",(function(){return B})),n.d(t,"n",(function(){return x})),n.d(t,"ib",(function(){return R})),n.d(t,"hb",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"q",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"o",(function(){return W})),n.d(t,"y",(function(){return K})),n.d(t,"nb",(function(){return z})),n.d(t,"ob",(function(){return V})),n.d(t,"f",(function(){return q})),n.d(t,"fb",(function(){return J})),n.d(t,"l",(function(){return Y})),n.d(t,"R",(function(){return Z})),n.d(t,"S",(function(){return X})),n.d(t,"U",(function(){return ee})),n.d(t,"T",(function(){return te})),n.d(t,"Y",(function(){return ue})),n.d(t,"t",(function(){return de})),n.d(t,"Z",(function(){return oe})),n.d(t,"X",(function(){return ae})),n.d(t,"W",(function(){return ie})),n.d(t,"bb",(function(){return fe})),n.d(t,"ab",(function(){return le})),n.d(t,"v",(function(){return be})),n.d(t,"w",(function(){return he})),n.d(t,"e",(function(){return me})),n.d(t,"cb",(function(){return pe})),n.d(t,"a",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"gb",(function(){return we})),n.d(t,"E",(function(){return Oe})),n.d(t,"C",(function(){return Ie})),n.d(t,"A",(function(){return je})),n.d(t,"F",(function(){return Ce})),n.d(t,"B",(function(){return Ee})),n.d(t,"D",(function(){return Se})),n.d(t,"h",(function(){return Me})),n.d(t,"i",(function(){return Ae}));var r=n(1),u=n(3);function d(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function o(e,t,n){const{[t]:r}=e.chats.listIds,u=r&&r.length?n.filter(e=>!r.includes(e)):n;return r&&!u.length?e:d(e,t,[...r||[],...u])}function c(e,t){return{...e,chats:{...e.chats,byId:t}}}function a(e,t,n,r){const{byId:d}=e.chats,o=d[t],a=n.isMin&&o&&!o.isMin,i={...o,...a?Object(u.j)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...o.photos||[]]}};return i.id&&i.type?c(e,{...d,[t]:i}):e}function i(e,t){return Object.keys(t).forEach(n=>{e=a(e,Number(n),t[Number(n)])}),e}function s(e,t){const{byId:n}=e.chats;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=a(e,r,t[r]))}),e}function f(e,t,n){const u=n===r.h?"archived":"active";let d=e.chats.listIds;return Object.keys(d).forEach(e=>{const n=d[e]||[];e!==u||n.includes(t)?e!==u&&n.includes(t)&&(d={...d,[e]:n.filter(e=>e!==t)}):d={...d,[e]:[...n,t]}}),e=a(e={...e,chats:{...e.chats,listIds:d}},t,{folderId:n||void 0})}function l(e,t,n){const r="active"===t?"all":"archived";return{...e,chats:{...e.chats,...n.orderedPinnedIds&&{orderedPinnedIds:{...e.chats.orderedPinnedIds,[t]:n.orderedPinnedIds}},totalCount:{...e.chats.totalCount,[r]:n.totalChatCount},isFullyLoaded:{...e.chats.isFullyLoaded,[t]:!1}}}}var b=n(5),h=n(6);function m(e,t,n=b.MAIN_THREAD_ID,r="thread"){return{...e,messages:{...e.messages,messageLists:t?[{chatId:t,threadId:n,type:r}]:void 0}}}function p(e,t,n){return g(e,t,{byId:n})}function g(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function y(e,t,n,r,u){return function(e,t,n,r){const u=e.messages.byChatId[t];return g(e,t,{threadsById:{...u&&u.threadsById,[n]:{...u&&u.threadsById[n],...r}}})}(e,t,n,{[r]:u})}function v(e,t){const n=t.reduce((e,t)=>(e[t.chatId]||(e[t.chatId]={}),e[t.chatId][t.id]=t,e),{});return Object.keys(n).map(Number).forEach(t=>{e=w(e,t,n[t])}),e}function w(e,t,n){const r=Object(h.m)(e,t);return r&&Object.keys(n).every(e=>Boolean(r[Number(e)]))?e:p(e,t,{...n,...r})}function O(e,t,n,r){const u=Object(h.m)(e,t)||{},d={...u[n],...r};return d.id?p(e,t,{...u,[n]:d}):e}function I(e,t,n,r){const u=Object(h.qb)(e,t)||{},d={...u[n],...r};return d.id?P(e,t,{...u,[n]:d},void 0):e}function j(e,t,n){const r=Object(h.m)(e,t);if(!r)return e;const d=Object(u.j)(r,n),o=Object.values(Object(u.m)(r,n)).filter(({forwardInfo:e})=>e&&e.isLinkedChannelPost);if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach(r=>{let u=Object(h.Y)(e,t,r),d=Object(h.gb)(e,t,r),o=Object(h.Hb)(e,t,r),c=Object(h.jb)(e,t);n.forEach(e=>{u&&u.includes(e)&&(u=u.filter(t=>t!==e)),d&&d.includes(e)&&(d=d.filter(t=>t!==e)),o&&o.includes(e)&&(o=o.filter(t=>t!==e)),c&&c.includes(e)&&(c=c.filter(t=>t!==e))}),e=y(e,t,r,"listedIds",u),e=y(e,t,r,"outlyingIds",d),e=y(e,t,r,"viewportIds",o),e=y(e,t,r,"pinnedIds",c)}),o.length){const n=Object(h.y)(e),r=n&&n.chatId===t&&"thread"===n.type,u=n&&n.threadId;o.forEach(n=>{const{fromChatId:d,fromMessageId:o}=n.forwardInfo,c=Object(h.k)(e,d,o);r&&u===o&&(e=m(e,t)),c&&(e=O(e,d,o,{threadInfo:void 0}))})}return e=p(e,t,d)}function C(e,t,n){const r=Object(h.qb)(e,t);if(!r)return e;const d=Object(u.j)(r,n);let o=Object(h.ob)(e,t);return o&&(n.forEach(e=>{o.includes(e)&&(o=o.filter(t=>t!==e))}),e=y(e,t,b.MAIN_THREAD_ID,"scheduledIds",o)),e=P(e,t,d,void 0)}function E(e,t,n,r){const u=Object(h.Y)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"listedIds",M([...u||[],...d]))}function S(e,t,n,r){const u=Object(h.gb)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"outlyingIds",M([...u||[],...d]))}function M(e){return e.sort((e,t)=>e-t)}function A(e,t,n,u){const d=Object(h.Hb)(e,t,n)||[];if(d.includes(u))return e;return y(e,t,n,"viewportIds",M([...d.length{e=T(e,t.chatId,t.threadId,t)}),e}function P(e,t,n,r){return function(e,t,n){const r=e.scheduledMessages.byChatId[t]||{byId:{},hash:0};return{...e,scheduledMessages:{byChatId:{...e.scheduledMessages.byChatId,[t]:{...r,...n}}}}}(e,t,{byId:n,hash:r})}function D(e,t,n,r=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r}}}function L(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function F(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function B(e,t,n,r,d,o,c,a=!1){const{selectedMessages:i}=e;o&&(c=Object(h.ab)(e,t,o));const s=c||[d];if(!i)return F(e,t,s);const{messageIds:f}=i;let l;const b=s.filter(e=>!f.includes(e));if(b&&!b.length)l=f.filter(e=>!s.includes(e));else if(a&&f.length){const o=Object(h.x)(e,t,n,r),c=o.indexOf(f[f.length-1]),a=o.indexOf(d),i=Math.min(c,a),s=Math.max(c,a),b=o.slice(i,s+1);l=Object(u.o)([...f,...b])}else l=[...f,...b];return l.length?{...e,selectedMessages:{...i,messageIds:l}}:x(e)}function x(e){return{...e,selectedMessages:void 0}}function R(e,t,n,r,d){const o=r.map(t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t});return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...Object(u.c)(o,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:d}:{setIds:r.map(({id:e})=>e)}}}}}function U(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function _(e,t,n,r){const{results:u}=e.gifs.search;let d;if(t||!u)d=n;else{const e=new Set(u.map(e=>e.id));d=[...u,...n.filter(t=>!e.has(t.id))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:d}}}}function G(e,t){return{...e,animatedEmojis:t}}function $(e,t,n,r){const d=[...Object(h.yb)(e,t),...n||[]],o=Object(u.o)(d.map(({id:e})=>e)),c=Object(u.c)(d,"id"),a=o.map(e=>c[e]);return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:a,hash:r}}}}function W(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?$(e,t,n,r):e}var H=n(52);function K(e,t){return{...e,users:{...e.users,byId:t}}}function z(e,t,n){const{byId:r}=e.users,{hash:d,userIds:o}=e.contactList||{},c=r[t],a=n.isMin&&c&&!c.isMin,i={...c,...a?Object(u.j)(n,["isMin","accessHash"]):n};return i.id&&i.type?(i.isContact&&o&&!o.includes(t)&&(e={...e,contactList:{hash:d||0,userIds:[t,...o]}}),K(e,{...r,[t]:i})):e}function V(e,t){return Object.keys(t).map(Number).forEach(n=>{e=z(e,n,t[n])}),e}function q(e,t){const{byId:n}=e.users;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=z(e,r,t[r]))}),e}function J(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function Y(e,t){const{byId:n}=e.users,{hash:r,userIds:u}=e.contactList||{};return delete n[t],K(e={...e,contactList:{hash:r||0,userIds:u?u.filter(e=>e!==t):H.a}},n)}const Q=e=>`${e.chatId}_${e.id}`;function Z(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function X(e,t){return Z(e,{currentContent:t})}function ee(e,t,n,r,d){const{resultsByType:o}=e.globalSearch||{},c=t.reduce((e,t)=>(e[Q(t)]=t,e),{}),a=o&&o[r]?o[r].foundIds:void 0;if(void 0!==a&&Object.keys(c).every(e=>a.includes(Q(c[e]))))return te(e,{messages:!1});const i=a||[],s=t.map(e=>Q(e)),f=Array.prototype.concat(i,s),l=Object(u.a)(i,f)?i:f;return Z(e=te(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:d,foundIds:l}}})}function te(e,t){return Z(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ne=n(4);function re(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,u){const d=Object(ne.a)(t,n);return re(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:u})}function de(e,t,n,r,u,d){const o=Object(ne.a)(t,n);return re(e,o,{...e.localTextSearch.byChatThreadKey[o],results:{foundIds:r,totalCount:u,nextOffsetId:d}})}function oe(e,t,n,r,d,o){const c=Object(ne.a)(t,n),{results:a}=e.localTextSearch.byChatThreadKey[c]||{},i=a&&a.foundIds||[],s=se(Object(u.o)(Array.prototype.concat(i,r)));return de(e,t,n,Object(u.a)(i,s)?i:s,d,o)}function ce(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ae(e,t,n){return ce(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ie(e,t,n,r,d,o){const{resultsByType:c}=e.localMediaSearch.byChatId[t]||{},a=c&&c[n]?c[n].foundIds:[],i=se(Object(u.o)(Array.prototype.concat(a,r)));return function(e,t,n,r,u,d){return ce(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:u,nextOffsetId:d}}})}(e,t,n,Object(u.a)(a,i)?a:i,d,o)}function se(e){return e.sort((e,t)=>e-t)}function fe(e,t){return{...e,management:{...e.management,progress:t}}}function le(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function be(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function he(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function me(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function pe(e,t,n,r){switch(t){case"contact":return be(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return be(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return be(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function ge(e,t){return{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function ye(e,t){return{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter(e=>e!==t),totalCount:e.blocked.totalCount-1}}}function ve(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function we(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Oe(e,t){return{...e,payment:{...e.payment,formId:t}}}function Ie(e,t){return{...e,payment:{...e.payment,step:t}}}function je(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,description:u,photoUrl:d}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,description:u,photoUrl:d}}}}function Ce(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function Ee(e,t){return{...e,payment:{...e.payment,...t}}}function Se(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:u,text:d,title:o}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:u,text:d,title:o}}}}function Me(e){return{...e,payment:{}}}function Ae(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},function(e,t,n){"use strict";var r=n(0);t.a=function(e,t){const n=Object(r.q)(),{current:u}=n;return t&&void 0===e||(n.current=e),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r={states:[],isHistoryChangedByUser:!0,pushState(e){this.states.push(e),window.history.pushState(e,"")},back(){this.isHistoryChangedByUser=!1,window.history.back(),this.states.pop()}}},function(e,t,n){"use strict";var r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));function r(e,t=30){return!e||e.length<=t?e:e.substr(0,t)+"..."}},function(e){e.exports=JSON.parse('{"--color-primary":["#50A2E9","#8378DB"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#121212"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFEDF","#8378DB"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d4fcae","#7b71c6"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#4C90E6","#8378DB"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-borders":["#DADCE0","#100F10"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-links":["#52A1EF","#868DF6"],"--color-links-hover":["#2d8dec","#6b5fcc"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#1010109c"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#4DCD5E","#8378DB"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#DBF4CE","#6458bc"],"--color-reply-own-active":["#C8EBBC","#4F4A9F"],"--color-accent-own":["#4FAE4E","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#52A1EF","#FFFFFF"],"--color-code-own":["#3C7940","#FFFFFF"]}')},function(e,t,n){"use strict";function r(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}let u;function d(){return u||(u=function(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const u=r(n);return(e,n)=>u.then(r=>n(r.transaction(t,e).objectStore(t)))}("keyval-store","keyval")),u}function o(e,t=d()){return t("readonly",t=>r(t.get(e)))}function c(e,t=d()){return t("readwrite",t=>(t.delete(e),r(t.transaction)))}function a(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction)))}function i(e=d()){const t=[];return a(e,e=>t.push(e.key)).then(()=>t)}n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return i}))},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);n(98);t.a=e=>{const{icon:t,className:n,children:o,onClick:c,href:a,download:i,disabled:s,destructive:f,ariaLabel:l}=e,b=Object(d.a)(),h=Object(r.m)(e=>{if(s||!c)return e.stopPropagation(),void e.preventDefault();c(e)},[s,c]),m=Object(r.m)(e=>{if(13===e.keyCode||32===e.keyCode)return s||!c?(e.stopPropagation(),void e.preventDefault()):void c(e)},[s,c]),p=Object(u.a)("MenuItem",n,s&&"disabled",f&&"destructive"),g=r.a.createElement(r.a.Fragment,null,t&&r.a.createElement("i",{className:"icon-"+t,"data-char":t.startsWith("char-")?t.replace("char-",""):void 0}),o);return a?r.a.createElement("a",{tabIndex:0,className:p,href:a,download:i,"aria-label":l,title:l,target:a.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:b.isRtl?"rtl":void 0},g):r.a.createElement("div",{role:"button",tabIndex:0,className:p,onClick:h,onKeyDown:m,"aria-label":l,title:l,dir:b.isRtl?"rtl":void 0},g)}},function(e,t,n){"use strict";var r=n(0),u=n(9);n(92);t.a=Object(r.h)(()=>{const[e,t]=Object(r.r)([]),n=Object(r.p)(()=>Object(u.a)(()=>{t([])},700,!1),[]),d=Object(r.m)(r=>{if(0!==r.button)return;const u=r.currentTarget,d=u.getBoundingClientRect(),o=u.offsetWidth/2;t([...e,{x:r.clientX-d.x-o/2,y:r.clientY-d.y-o/2,size:o}]),requestAnimationFrame(()=>{n()})},[e,n]);return r.a.createElement("div",{className:"ripple-container",onMouseDown:d},e.map(({x:e,y:t,size:n})=>r.a.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"c",(function(){return l}));var r=n(84),u=n.n(r),d=n(7),o=n(13),c=n(9);let a,i;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function f(e,t){for(b();!i.wasmReady;)await Object(c.e)(2e3);const{result:n,width:r,height:u}=await function(e,t){return new Promise(n=>{i.requests=i.requests||new Map,i.requests.set(e,n),i.postMessage({id:e,blob:t})})}(e,t);if(r&&u)return function({result:e,width:t,height:n}){a||(a=document.createElement("canvas"));return new Promise(r=>{const u=new ImageData(e,t,n);a.width=t,a.height=n;a.getContext("2d").putImageData(u,0,0),a.toBlob(e=>{r(null!=e?e:void 0)},"image/png",1)})}({result:n,width:r,height:u})}async function l(e,t){if(Object(d.p)()||"data:image/webp"!==t.substr(0,15))return t;b();const n=await f(e,Object(o.d)(t));if(!n)throw new Error("Can't convert webp to png. Url: "+t);return Object(o.a)(n)}function b(){i||(i=new u.a,i.wasmReady=!1,i.onmessage=h)}function h(e){const{id:t}=e.data;switch(e.data.type){case"initialized":i.wasmReady=!0;break;case"result":if(i.requests.has(t)){const n=i.requests.get(t);i.requests.delete(t),n(e.data)}}}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);t.a=Object(r.h)(({ref:e,id:t,className:n,value:o,label:c,error:a,success:i,disabled:s,readOnly:f,placeholder:l,autoComplete:b,inputMode:h,maxLength:m,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w})=>{const O=Object(d.a)(),I=a||i||c,j=Object(u.a)("input-group",o&&"touched",a?"error":i&&"success",s&&"disabled",f&&"disabled",I&&"with-label",n);return r.a.createElement("div",{className:j,dir:O.isRtl?"rtl":void 0},r.a.createElement("input",{ref:e,className:"form-control",type:"text",id:t,dir:"auto",value:o||"",placeholder:l,maxLength:m,autoComplete:b,inputMode:h,disabled:s,readOnly:f,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w}),I&&r.a.createElement("label",{htmlFor:t},I))})},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25),o=n(20);n(94);t.a=Object(r.h)(({id:e,name:t,value:n,label:c,subLabel:a,checked:i,disabled:s,round:f,blocking:l,isLoading:b,onChange:h,onCheck:m})=>{const p=Object(d.a)(),g=Object(r.m)(e=>{h&&h(e),m&&m(e.currentTarget.checked)},[h,m]),y=Object(u.a)("Checkbox",s&&"disabled",f&&"round",b&&"loading",l&&"blocking");return r.a.createElement("label",{className:y,dir:p.isRtl?"rtl":void 0},r.a.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:i,disabled:s,onChange:g}),r.a.createElement("div",{className:"Checkbox-main"},r.a.createElement("span",{className:"label",dir:"auto"},c),a&&r.a.createElement("span",{className:"subLabel",dir:"auto"},a)),b&&r.a.createElement(o.a,null))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(56);function u(e){return Object(r.a)({onEsc:e})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));var r=n(0);let u,d=!1;const o=e=>{document.dispatchEvent(new Event("tt-event-heavy-animation-start")),d=!0,u&&(clearTimeout(u),u=void 0),u=window.setTimeout(()=>{d=!1,document.dispatchEvent(new Event("tt-event-heavy-animation-end")),u=void 0},e)};t.a=(e,t)=>{Object(r.n)(()=>(d&&e(),document.addEventListener("tt-event-heavy-animation-start",e),document.addEventListener("tt-event-heavy-animation-end",t),()=>{document.removeEventListener("tt-event-heavy-animation-end",t),document.removeEventListener("tt-event-heavy-animation-start",e)}),[t,e])}},function(e,t,n){"use strict";function r(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function d(e){return e<1e3?e:e<1e6?u(e/1e3)+"K":u(e/1e6)+"M"}function o(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map(e=>e.length&&e.match(/./u)[0].toUpperCase()).join("")}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return o}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r=[]},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));const r=/[^\wа-яё]+/;function u(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every(e=>n.some(t=>t.startsWith(e)))}},function(e,t,n){"use strict";var r=n(0),u=n(35),d=n(64),o=n(80),c=n(59),a=n(49),i=n(8),s=n(50);n(96);t.a=({ref:e,containerRef:t,isOpen:n,className:f,style:l,children:b,positionX:h="left",positionY:m="top",autoClose:p=!1,footer:g,noCloseOnBackdrop:y=!1,onCloseAnimationEnd:v,onClose:w,onMouseEnter:O,onMouseLeave:I,shouldSkipTransition:j})=>{let C=Object(r.q)(null);e&&(C=e);const E=t||C,{transitionClassNames:S}=Object(u.a)(n,v,j,void 0,j);Object(r.n)(()=>n&&w?Object(a.a)(w):void 0,[n,w]),Object(c.a)(([e])=>{void 0!==e&&Object(s.b)(200)},[n]);const M=Object(d.a)(C,n,p?w:void 0,void 0,!0);Object(o.a)(n,E,y?void 0:w);const A=Object(i.a)("bubble menu-container custom-scroll",m,h,g&&"with-footer",S);return r.a.createElement("div",{className:Object(i.a)("Menu no-selection",f),onKeyDown:n?M:void 0,onMouseEnter:O,onMouseLeave:n?I:void 0,style:l},n&&r.a.createElement("div",{className:"backdrop"}),r.a.createElement("div",{ref:C,className:A,style:`transform-origin: ${m} ${h}`,onClick:p?w:void 0},b,g&&r.a.createElement("div",{className:"footer"},g)))}},function(e,t,n){"use strict";n.d(t,"b",(function(){return y})),n.d(t,"c",(function(){return v})),n.d(t,"a",(function(){return w}));var r=n(5),u=n(1),d=n(10),o=n(12),c=n(13),a=n(7),i=n(82),s=n.n(i),f=n(83),l=n.n(f);async function b(e){const t=await new Response(e).arrayBuffer();return new Promise(e=>{const n=new Uint8Array(t);let r=new s.a,u=new l.a;r.onmessage=e=>{null===e.data?u.postMessage({command:"done"}):u.postMessage({command:"encode",buffers:e.data},e.data.map(({buffer:e})=>e))},u.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),r.terminate(),r=void 0,u.terminate(),u=void 0)},u.postMessage({command:"init",wavBitDepth:16,wavSampleRate:48e3}),r.postMessage({command:"init",decoderSampleRate:48e3,outputBufferSampleRate:48e3}),r.postMessage({command:"decode",pages:n},[n.buffer])})}var h=n(46);const m={[r.ApiMediaFormat.DataUri]:o.a.Text,[r.ApiMediaFormat.BlobUrl]:o.a.Blob,[r.ApiMediaFormat.Lottie]:o.a.Json,[r.ApiMediaFormat.Progressive]:void 0,[r.ApiMediaFormat.Stream]:void 0},p=new Map,g=new Map;function y(e,t,n){if(t===r.ApiMediaFormat.Progressive)return a.i?function(e){const t="./progressive/"+e;return p.set(e,t),Promise.resolve(t)}(e):y(e,r.ApiMediaFormat.BlobUrl,n);if(!g.has(e)){const i=async function(e,t,n){if(!u.M){const n=e.startsWith("avatar")?u.O:u.N,r=await o.c(n,e,m[t]);if(r){let t=r;if("audio/ogg"!==r.type||a.h||(t=await b(t)),"image/webp"===r.type&&!Object(a.p)()&&t){const n=await Object(h.b)(e,t);n&&(t=n)}const n=O(t);return p.set(e,n),n}}if(t===r.ApiMediaFormat.Stream){const r=new MediaSource,u=URL.createObjectURL(r);let o=!1;return r.addEventListener("sourceopen",()=>{if(o)return;o=!0;const u=r.addSourceBuffer("audio/mpeg");Object(d.a)("downloadMedia",{url:e,mediaFormat:t},(e,t)=>{n&&n(e),1===e&&r.endOfStream(),t&&u.appendBuffer(t)})}),p.set(e,u),u}const i=await Object(d.a)("downloadMedia",{url:e,mediaFormat:t},n);if(!i)throw new Error("Failed to fetch media");let{prepared:s,mimeType:f}=i;if("audio/ogg"===f&&!a.h){const e=await Object(c.e)(s);URL.revokeObjectURL(s);const t=await b(e);s=O(t),f=e.type}if("image/webp"===f&&!Object(a.p)()){const t=await Object(c.e)(s);URL.revokeObjectURL(s);const n=await Object(h.b)(e,t);n&&(s=O(n))}return p.set(e,s),s}(e,t,n).catch(e=>{u.p&&console.warn(e)}).finally(()=>{g.delete(e)});g.set(e,i)}return g.get(e)}function v(e){return p.get(e)}function w(e){Object(d.b)(e)}function O(e){return e instanceof Blob?URL.createObjectURL(e):e}a.i&&navigator.serviceWorker.addEventListener("message",async e=>{const{type:t,messageId:n,params:u}=e.data;if("requestPart"!==t)return;const o=await Object(d.a)("downloadMedia",{mediaFormat:r.ApiMediaFormat.Progressive,...u});if(!o)return;const{arrayBuffer:c,mimeType:a,fullSize:i}=o;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:c,mimeType:a,fullSize:i}},[c])})},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",ArrowLeft:"onLeft",ArrowRight:"onRight",Tab:"onTab"},u={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onLeft:[],onRight:[],onTab:[]};function d(e){return o()||document.addEventListener("keydown",c,!0),Object.keys(e).forEach(t=>{const n=e[t];if(!n)return;const r=u[t];r&&r.push(n)}),()=>{!function(e){Object.keys(e).forEach(t=>{const n=e[t],r=u[t];if(r){const e=r.findIndex(e=>e===n);-1!==e&&r.splice(e,1)}}),o()||document.removeEventListener("keydown",c,!1)}(e)}}function o(){return Object.values(u).some(e=>Boolean(e.length))}function c(e){const t=r[e.key];if(!t)return;const{length:n}=u[t];if(!n)return;e.stopPropagation();(0,u[t][n-1])(e)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i}));var r=n(9),u=n(1),d=n(7);const o=d.g&&s();let c=i();const a=Object(r.g)(()=>{c=i(),((c.width<=u.db||c.width<=u.cb&&c.height<=u.bb)!==d.g||d.g&&o!==s())&&window.location.reload()},250,!0);function i(){const e=.01*window.innerHeight;return document.documentElement.style.setProperty("--vh",e+"px"),{width:window.innerWidth,height:window.innerHeight}}function s(){return d.e?window.matchMedia("(orientation: landscape)").matches:window.matchMedia("screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)").matches}window.addEventListener("resize",a),window.addEventListener("orientationchange",a),t.a={get:()=>c}},function(e,t,n){"use strict";var r=n(0),u=n(2);const d=e=>{const t=[];let n=0;const r=e.length;let u;for(;n65535&&(u-=65536,t.push(String.fromCharCode(u>>>10&1023|55296)),u=56320|1023&u),t.push(String.fromCharCode(u))}return t.join("")};function o(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=36)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function c(e,t){const n=[],r=[],u=e.length;let c,a,i,s,f,l,b,h,m,p,g,y,v;for(c=128,i=0,s=72,f=e.lastIndexOf("-"),f<0&&(f=0),l=0;l=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(l))}for(b=f>0?f+1:0;b=u)throw RangeError("punycode_bad_input(1)");if(g=(w=e.charCodeAt(b++))-48<10?w-22:w-65<26?w-65:w-97<26?w-97:36,g>=36)throw RangeError("punycode_bad_input(2)");if(g>Math.floor((2147483647-i)/m))throw RangeError("punycode_overflow(1)");if(i+=g*m,y=p<=s?1:p>=s+26?26:p-s,gMath.floor(2147483647/(36-y)))throw RangeError("punycode_overflow(2)");m*=36-y}if(a=n.length+1,s=o(i-h,a,0===h),Math.floor(i/a)>2147483647-c)throw RangeError("punycode_overflow(3)");c+=Math.floor(i/a),i%=a,t&&r.splice(i,0,e.charCodeAt(b-1)-65<26),n.splice(i,0,c),i++}var w;if(t)for(i=0,v=n.length;iObject(s.l)(t,["toggleSafeLinkModal","openTelegramLink"]))(({url:e,text:t,className:n,children:u,isRtl:d,toggleSafeLinkModal:o,openTelegramLink:c})=>{const a=u||t,s=e!==a,h=Object(r.m)(t=>t.ctrlKey||t.altKey||t.shiftKey||t.metaKey||!e||!e.match(i.ib)&&!e.match(i.hb)?!s||(o({url:e}),t.preventDefault(),!1):(t.preventDefault(),c({url:e}),!1),[s,c,o,e]);if(!e)return;const m=Object(f.a)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.a.createElement("a",{href:l(e),title:b(e),target:"_blank",rel:"noopener noreferrer",className:m,onClick:h,dir:d?"rtl":"auto"},a)}))},function(e,t,n){"use strict";var r=n(0),u=n(38);t.a=(e,t)=>{const n=Object(u.a)(t);return Object(r.n)(()=>e(n||[]),t)}},function(e,t,n){"use strict";n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c}));function r(e){return e>536870912?(e/1073741824).toFixed(1)+" GB":e>524288?(e/1048576).toFixed(1)+" MB":(e/1024).toFixed(1)+" KB"}function u(e){const{fileName:t,mimeType:n}=e;return d(t,n)}function d(e,t){return e&&-1!==e.indexOf(".")?e.split(".").pop():t.split("/").pop()}function o(e){switch(e){case"apk":case"xls":case"xlsx":return"green";case"zip":case"rar":case"7z":case"tar":case"gz":case"ppt":case"pptx":return"orange";case"pdf":case"xps":return"red";default:return"default"}}function c(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return o}));const r={missing_payment_information:{field:"cardNumber",fieldError:"Incorrect card number"},invalid_number:{field:"cardNumber",fieldError:"Incorrect card number"},number:{field:"cardNumber",fieldError:"Incorrect card number"},exp_year:{field:"expiry",fieldError:"Incorrect year"},exp_month:{field:"expiry",fieldError:"Incorrect month"},invalid_expiry_year:{field:"expiry",fieldError:"Incorrect year"},invalid_expiry_month:{field:"expiry",fieldError:"Incorrect month"},cvc:{field:"cvv",fieldError:"Incorrect CVV"},invalid_cvc:{field:"cvv",fieldError:"Incorrect CVV"}};function u(e){const{message:t,code:n,param:u}=e,{field:d,fieldError:o,description:c}=u?r[u]:r[n];return{field:d,fieldError:o,description:c||t}}const d={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",fieldError:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",fieldError:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",fieldError:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",fieldError:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",fieldError:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",fieldError:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",fieldError:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",fieldError:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",fieldError:"Incorrect email"}};function o(e){return Object.values(e).reduce((e,t)=>{const n=d[t.message];return n&&(e={...e,[n.field]:n.fieldError}),e},{})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"a",(function(){return o}));var r=n(9);let u;function d(e,t){t||(u&&!u.isCancelled&&(u.isCancelled=!0),u=t={isCancelled:!1}),Object(r.b)(()=>{!t.isCancelled&&e()&&d(e,t)})}function o(e){Object(r.b)(()=>{e()&&o(e)})}},function(e,t,n){"use strict";var r=n(0),u=n(54);n(97);t.a=({trigger:e,className:t,children:n,positionX:d="left",positionY:o="top",footer:c,forceOpen:a,onOpen:i,onClose:s})=>{const f=Object(r.q)(null),l=Object(r.q)(null),[b,h]=Object(r.r)(!1);return r.a.createElement("div",{ref:l,className:"DropdownMenu "+(t||""),onKeyDown:e=>{const t=f.current;if(!b||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{h(!b),b?s&&s():i&&i()},isOpen:b}),r.a.createElement(u.a,{ref:f,containerRef:l,isOpen:b||!!a,className:t||"",positionX:d,positionY:o,footer:c,autoClose:!0,onClose:()=>{h(!1),s&&s()},shouldSkipTransition:a},n))}},function(e,t,n){"use strict";var r=n(0);t.a=(e,t,n,u,d)=>{const[o,c]=Object(r.r)(-1);Object(r.n)(()=>{c(-1);const n=e.current;t&&n&&!d&&(n.tabIndex=-1,n.focus())},[e,t,d]);return Object(r.m)(t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n(o);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,a=Array.from(u?r.querySelectorAll(u):r.children);let i=d&&a.indexOf(d)||o;if(38===t.keyCode&&i>0)i--;else if(40===t.keyCode&&i{if(e.length>24)return!1;if(!Boolean(e.match(u)))return!1;let t=0;for(;r.a.exec(e);)if(t++,t>3)return r.a.lastIndex=0,!1;return t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return o}));const r=["female_sign","male_sign","medical_symbol"];function u(e){const t=e.split("-").map(e=>parseInt(e,16));return String.fromCodePoint(...t)}function d(e){let t;if(1===e.length)t=e.charCodeAt(0).toString(16).padStart(4,"0");else{const n=[];for(let t=0;t=55296&&e.charCodeAt(t)<=56319?e.charCodeAt(t+1)>=56320&&e.charCodeAt(t+1)<=57343&&n.push(1024*(e.charCodeAt(t)-55296)+(e.charCodeAt(t+1)-56320)+65536):(e.charCodeAt(t)<55296||e.charCodeAt(t)>57343)&&n.push(e.charCodeAt(t));t=n.map(e=>e.toString(16).padStart(4,"0")).join("-")}return t}function o(e){const t={categories:[],emojis:{}};for(let n=0;n{void 0!==e.props[r]&&void 0===t.props[r]&&g(n,r,e.props[r])}),u.forEach(r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?p(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(g(e,t,n),p(e,t,r))}(n,r,e.props[r],t.props[r]))})}(t,n,Object(r.b)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const u=new Set(t.children.map(e=>{const t="props"in e&&e.props.key;return d.p&&Object(r.f)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t}));let o=0;const c=e.children.reduce((e,r,d)=>{let c="props"in r?r.props.key:void 0;if(c&&!u.has(c))return f(n,r,void 0,t,-1),e;if(!c){const u=t.children[d],o=u&&"props"in u?u.props.key:void 0;if(!u||o)return f(n,r,void 0,t,-1),e;c="__indexKey#"+d}return e[c]={$element:r,index:o++,order:"props"in r?r.props.teactOrderKey:void 0},e},{});let a,i,s=[],l=0;t.children.forEach((e,r)=>{const u="props"in e?e.props.key:"__indexKey#"+r,d=c[u];if(!d)return a||(a=[],i=r),void a.push(e);a&&(s=s.concat(m(a,i,n,t)),i=void 0,a=void 0);const o="props"in e?e.props.teactOrderKey:void 0,b=d.index!==l&&d.order!==o,h=b&&l>d.index;b&&!h||l++,s.push(f(n,d.$element,e,t,r,{forceIndex:!0,...b&&{moveDirection:h?"down":"up"}}))}),a&&(s=s.concat(m(a,i,n,t)));return s}(e,t,n);const u=Math.max(e.children.length,t.children.length),o=[],c=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:c}:void 0);u&&o.push(u)}c&&n.appendChild(c);return o}(t,n,u?e:Object(r.b)(t))}}return n}function l(e,t,n,u){if(!Object(r.d)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){b(e=Object(r.i)(d),t,n,u);const o=e.children[0];Object(r.d)(o)&&(e.children=[l(o,e,0,u)]),d.isMounted=!0}return e}function b(e,t,n,r){const{componentInstance:u}=e;u.onUpdate=()=>{t.children[n]=f(r,t.children[n],u.$element,t,n,{skipComponentUpdate:!0})}}function h(e){if(Object(r.e)(e))return document.createTextNode("");if(Object(r.g)(e))return document.createTextNode(e.value);if(Object(r.d)(e))return h(e.children[0]);const{tag:t,props:n,children:u=[]}=e,d=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=d),Object.keys(n).forEach(e=>{p(d,e,n[e])}),e.children=u.map((t,n)=>f(d,void 0,t,e,n)),d}function m(e,t,n,r){if(1===e.length)return[f(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const u=document.createDocumentFragment(),d=e.map(e=>f(n,void 0,e,r,t,{fragment:u}));return n.childNodes[t]?n.insertBefore(u,n.childNodes[t]):n.appendChild(u),d}throw new Error("Unexpected input")}function p(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?Object(o.a)(e,t,n):t.startsWith("data-")||a.has(t)?e.setAttribute(t,n):c.has(t)||(e[i[t]||t]=n))}function g(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?Object(o.c)(e,t,n):t.startsWith("data-")||a.has(t)?e.removeAttribute(t):c.has(t)||delete e[i[t]||t]}t.a={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=Object(u.a)(s),s[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=s[n];r.children=[f(t,r.children[0],e,r,0)]}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(0),u=n(4),d=n(41),o=n(23),c=n(2),a=n(3),i=n(8),s=n(27);var f=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openUserInfo"]))(({className:e,sender:t,openUserInfo:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t.id})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("UserLink",e),onClick:d},u):u});var l=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["focusMessage"]))(({className:e,message:t,children:n,focusMessage:u})=>{const d=Object(r.m)(()=>{t&&u({chatId:t.chatId,messageId:t.id})},[u,t]);return t?r.a.createElement(s.a,{className:Object(i.a)("MessageLink",e),onClick:d},n):n});var b=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openChat"]))(({className:e,chatId:t,openChat:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("ChatLink",e),onClick:d},u):u});function h(e,t,n,c,a,i,s={}){if(!t.content.action)return[];const{text:f}=t.content.action,h=[],g={...s,maxTextLength:16};let y,v=p(f,"%action_origin%",n?!s.isEmbedded&&function(e,t,n){return Object(u.fb)(t)?function(e,t,n){const c=Object(d.a)(Object(u.l)(e,t));if(n)return c;return r.a.createElement(b,{className:"action-link",chatId:t.id},t&&Object(o.a)(c))}(e,t,n):m(t,n)}(e,n,s.asPlain)||" ":"User");return y=v.pop(),h.push(...v),v=p(y,"%target_user%",c?m(c,s.asPlain):"User"),y=v.pop(),h.push(...v),v=p(y,"%message%",a?function(e,t,n={}){const c=Object(u.N)(e,t),{photo:a,video:i,document:s,sticker:f}=Object(u.v)(t),b=c&&!a&&!i&&!s&&!f;let h=Object(d.a)(c,n.maxTextLength);a?h="a photo":i?h=i.isGif?"a GIF":"a video":s?h="a document":f&&(h=`«${c}»`);if(n.asPlain)return b?`«${h}»`:h;if(b)return r.a.createElement("span",null,"«",r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h)),"»");return r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h))}(e,a,g):"a message"),y=v.pop(),h.push(...v),v=p(y,"%product%",a?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(a):"a product"),y=v.pop(),h.push(...v),v=p(y,"%target_chat%",i?function(e,t){if(t)return"another chat";return r.a.createElement(b,{className:"action-link",chatId:e},"another chat")}(i,s.asPlain):"another chat"),h.push(...v),s.asPlain?h.join("").trim():h}function m(e,t){const n=Object(d.a)(Object(u.Z)(e));return t?n:r.a.createElement(f,{className:"action-link",sender:e},e&&Object(o.a)(n))}function p(e,t,n){const r=e.indexOf(t);if(r<0||!n)return[e];const u=[];return u.push(e.substring(0,r)),u.push(n),u.push(e.substring(r+t.length)),u}},function(e,t){},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return d})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const u=-1,d="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var r=n(0),u=n(2),d=n(3),o=n(6);t.a=Object(u.h)((e,{userId:t})=>({userOrChat:t?Object(o.Gb)(e,t):void 0}),(e,t)=>Object(d.l)(t,["openChat","openChatByUsername"]))(({username:e,userOrChat:t,children:n,openChat:u,openChatByUsername:d})=>r.a.createElement("a",{onClick:()=>{t?u({id:t.id}):e&&d({username:e.substring(1)})},className:"text-entity-link",dir:"auto"},n))},function(e,t,n){"use strict";var r=n(62),u=n(42);let d=!1;const o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,c=(e,t,n)=>(1-n)*e+n*t,a=Object.keys(u).map(e=>({property:e,colors:[i(u[e][0]),i(u[e][1])]}));function i(e){const t=o.exec(e);return{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16),a:void 0!==t[4]?parseInt(t[4],16):void 0}}function s(e,t,n=1){a.forEach(({property:r,colors:u})=>{const d=Math.round(c(u[e].r,u[t].r,n)),o=Math.round(c(u[e].g,u[t].g,n)),a=Math.round(c(u[e].b,u[t].b,n)),i=void 0!==u[e].a?Math.round(c(u[e].a,u[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==i?`rgba(${d},${o},${a},${i/255})`:`rgb(${d},${o},${a})`)})}t.a=(e,t)=>{const n="dark"===e,u=d&&t,o=n?0:1,c=n?1:0,a=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),d&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add("theme-"+e),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout(()=>{document.documentElement.classList.remove("no-animations")},500),d=!0,u?Object(r.b)(()=>{const e=Math.min((Date.now()-a)/200,1);return s(o,c,function(e){return 1-(1-e)**3.5}(e)),e<1}):s(o,c)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(1);function u(e){"function"==typeof window.navigator.setAppBadge&&window.navigator.setAppBadge(e).catch(e=>{r.p&&console.error(e)})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(0);function u(e,t,n){Object(r.n)(()=>{const r=e=>{const r=t.current,u=e.target;r&&u&&(r.contains(e.target)&&!u.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}},[e,t,n])}},function(e,t,n){e.exports=function(){return new Worker(n.p+"3d0807b05cc1ab7d3c59.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"01705582fc3eca0e007b.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0dbbe0a906f6c2adf071.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"a66075669d8d0ac2d740.worker.js")}},function(e,t,n){"use strict";var r=n(2),u=n(7),d=n(14),o=n(78),c=n(39);Object(r.b)("init",e=>{const{theme:t,animationLevel:n,messageTextSize:r,language:c}=e.settings.byKey;Object(d.c)(c),document.documentElement.style.setProperty("--message-text-size",r+"px"),document.body.classList.add("initial"),document.body.classList.add("animation-level-"+n),document.body.classList.add(u.l?"is-touch-env":"is-pointer-env"),Object(o.a)(t,n>0),u.j&&document.body.classList.add("is-safari"),u.e?document.body.classList.add("is-ios"):u.b&&document.body.classList.add("is-android")}),Object(r.b)("setIsUiReady",(e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return c.a.pushState({type:"login",contentKey:"authCode"}),{...e,authPhoneNumber:r}}),Object(r.b)("setAuthRememberMe",(e,t,n)=>({...e,authRememberMe:Boolean(n)})),Object(r.b)("clearAuthError",e=>({...e,authError:void 0})),Object(r.b)("setShouldSkipUiLoaderTransition",(e,t,n)=>{const{shouldSkipUiLoaderTransition:r}=n;return{...e,shouldSkipUiLoaderTransition:r}})},function(e,t,n){"use strict";var r=n(2),u=n(1),d=n(10),o=n(29),c=n(12),a=n(39),i=n(79),s=n(22);Object(r.b)("initApi",(e,t)=>{(async()=>{u.E?Object(s.d)():(await Object(s.c)(),Object(s.a)()),Object(d.c)(t.apiUpdate,Object(s.e)())})()}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return Object(d.a)("provideAuthPhoneNumber",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthCode",(e,t,n)=>{const{code:r}=n;return Object(d.a)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthPassword",(e,t,n)=>{const{password:r}=n;return Object(d.a)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("uploadProfilePhoto",(e,t,n)=>{const{file:r}=n;Object(d.a)("uploadProfilePhoto",r)}),Object(r.b)("signUp",(e,t,n)=>{const{firstName:r,lastName:u}=n;return Object(d.a)("provideAuthRegistration",{firstName:r,lastName:u}),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("returnToAuthPhoneNumber",e=>(Object(d.a)("restartAuth"),{...e,authError:void 0})),Object(r.b)("gotToAuthQrCode",e=>(Object(d.a)("restartAuthWithQr"),a.a.pushState({type:"login",contentKey:"authQr"}),{...e,authIsLoadingQrCode:!0,authError:void 0})),Object(r.b)("saveSession",(e,t,n)=>{Object(s.f)(n.sessionData,e.currentUserId)}),Object(r.b)("signOut",()=>{(async()=>{await Object(o.d)(),await Object(d.a)("destroy"),Object(r.d)().reset()})()}),Object(r.b)("reset",()=>{Object(s.b)(),c.b(u.N),c.b(u.O),c.b(u.P),c.b(u.m);const e=u.F.replace(/\d+$/,""),t=(u.F.match(/\d+$/)||[0])[0];for(let n=0;n{(async()=>{await Object(d.a)("disconnect")})()}),Object(r.b)("loadNearestCountry",e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await Object(d.a)("fetchNearestCountry");Object(r.g)({...Object(r.e)(),authNearestCountry:e})})()}),Object(r.b)("setDeviceToken",(e,t,n)=>{Object(r.g)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})}),Object(r.b)("deleteDeviceToken",e=>{const t={...e};delete t.push,Object(r.g)(t)})},function(e,t){var n,r,u=e.exports={};function d(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function c(e){if(n===setTimeout)return setTimeout(e,0);if((n===d||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:d}catch(e){n=d}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,i=[],s=!1,f=-1;function l(){s&&a&&(s=!1,a.length?i=a.concat(i):f=-1,i.length&&b())}function b(){if(!s){var e=c(l);s=!0;for(var t=i.length;t;){for(a=i,i=[];++f1)for(var n=1;n{switch(u.p&&"updateUserStatus"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){Object(d.c)(),Object(c.c)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=Object(r.e)();const n="authorizationStateReady"===t.authState,u=e.authorizationState;switch(Object(r.g)({...t,authState:u,authIsLoading:!1}),t=Object(r.e)(),u){case"authorizationStateLoggingOut":Object(r.g)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":Object(r.g)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":Object(r.g)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":Object(r.g)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":if(n)break;Object(r.g)({...t,isLoggingOut:!1,lastSyncTime:Date.now()})}}(n);break;case"updateAuthorizationError":!function(e){Object(r.g)({...Object(r.e)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=Object(r.e)();Object(r.g)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?Object(r.d)().sync():"connectionStateBroken"===t&&Object(r.d)().signOut()}(n);break;case"updateSession":!function(e){if(!Object(r.e)().authRememberMe)return;const{sessionData:t}=e;Object(r.d)().saveSession({sessionData:t})}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;Object(r.g)({...Object(o.nb)(Object(r.e)(),t.id,t),currentUserId:t.id}),function(e){const t=localStorage.getItem(u.nb);if(!t)return;const n=JSON.parse(t);n.id=e,localStorage.setItem(u.nb,JSON.stringify(n))}(t.id)}(n);break;case"error":"SESSION_REVOKED"===n.error.message&&t.signOut(),t.showError({error:n.error})}})},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(21),function(){function e(){var t=Error.call(this,"ServiceWorker is not supported.");return Object.setPrototypeOf(t,e.prototype),t}e.prototype=Object.create(Error.prototype)}();var r=n.p+"serviceWorker.js";var u=n(1),d=n(2),o=n(7),c=n(29);function a(e){const t=e.data;if(!t.type)return;const n=Object(d.d)();switch(t.type){case"focusMessage":n.focusMessage(t.payload)}}function i(){navigator.serviceWorker.removeEventListener("message",a),navigator.serviceWorker.addEventListener("message",a),Object(c.a)()}o.k&&(window.addEventListener("load",async()=>{try{await navigator.serviceWorker.register(r),u.p&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(u.p&&console.log("[SW] ServiceWorker ready"),i()):(u.p&&console.error("[SW] ServiceWorker not available"),Object(d.d)().showError({error:{message:"SERVICE_WORKER_DISABLED"}}))}catch(e){u.p&&console.error("[SW] ServiceWorker registration failed: ",e)}}),window.addEventListener("focus",async()=>{await navigator.serviceWorker.ready,i()}));var s=n(67);const f={isLeftColumnShown:!0,isChatInfoShown:!1,uiReadyState:0,authRememberMe:!0,blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{}},scheduledMessages:{byChatId:{}},chatFolders:{byId:{},activeChatFolder:0},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},emojiKeywords:{},gifs:{saved:{},search:{}},globalSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},mediaViewer:{},audioPlayer:{},forwardMessages:{},pollResults:{},payment:{},notifications:[],errors:[],activeSessions:[],settings:{byKey:{messageTextSize:u.s,animationLevel:u.d,messageSendKeyCombo:"enter",theme:"light",shouldAutoDownloadMediaFromContacts:!0,shouldAutoDownloadMediaInPrivateChats:!0,shouldAutoDownloadMediaInGroups:!0,shouldAutoDownloadMediaInChannels:!0,shouldAutoPlayGifs:!0,shouldAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en"},themes:{light:{isBlurred:!0,patternColor:u.t},dark:{isBlurred:!0,patternColor:u.o}},privacy:{},notifyExceptions:{}},twoFaSettings:{}};var l=n(5),b=n(9),h=n(3),m=n(6);const p=Object(b.g)((function(){Object(b.c)(()=>{if(!g)return;const e=Object(d.e)();if(e.isLoggingOut)return;const t={...f,...Object(h.l)(e,["authState","authPhoneNumber","authRememberMe","authNearestCountry","currentUserId","contactList","chatFolders","topPeers","recentEmojis","emojiKeywords","push"]),isChatInfoShown:v(e),users:w(e),chats:O(e),messages:I(e),globalSearch:{recentlyFoundChatIds:e.globalSearch.recentlyFoundChatIds},settings:j(e)},n=JSON.stringify(t);localStorage.setItem(u.B,n)})}),1e3,!1);let g=!1;function y(e){if(!u.A){if(localStorage.getItem(u.nb)||localStorage.getItem(u.H))return g=!0,Object(d.a)(p),function(e){u.p&&console.time("global-state-cache-read");const t=localStorage.getItem(u.B),n=t?JSON.parse(t):void 0;u.p&&console.timeEnd("global-state-cache-read");n&&(n.settings.byKey={...e.settings.byKey,...n.settings.byKey},n.settings.themes={...e.settings.themes,...n.settings.themes},n.chatFolders={...e.chatFolders,...n.chatFolders});return{...e,...n}}(e);g=!1}}function v(e){return window.innerWidth>u.ab&&e.isChatInfoShown}function w(e){const{users:{byId:t,selectedId:n}}=e,r=[...(e.chats.listIds.active||[]).slice(0,u.z).filter(e=>e>0),...Object.keys(t)].slice(0,u.C);return{byId:Object(h.l)(t,r),selectedId:window.innerWidth>u.ab?n:void 0}}function O(e){const t=[...(e.chats.listIds.active||[]).slice(0,u.z)],{chatId:n}=Object(m.y)(e)||{};return{...e.chats,byId:Object(h.l)(e.chats.byId,n?[...t,n]:t),listIds:{active:t},isFullyLoaded:{},orderedPinnedIds:{active:e.chats.orderedPinnedIds.active}}}function I(e){const t={},{chatId:n}=Object(m.y)(e)||{};[...(e.chats.listIds.active||[]).slice(0,u.z),...n?[n]:[]].forEach(n=>{const r=e.messages.byChatId[n];if(!r)return;const u=r.threadsById[l.MAIN_THREAD_ID];u&&u.viewportIds&&(t[n]={byId:Object(h.l)(r.byId,u.viewportIds),threadsById:{[l.MAIN_THREAD_ID]:u}})});const r=Object(m.y)(e);return{byChatId:t,messageLists:!r||o.g?void 0:[{...r,threadId:l.MAIN_THREAD_ID,type:"thread"}]}}function j(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}u.A||(Object(d.b)("saveSession",()=>{g=!0,Object(d.a)(p)}),Object(d.b)("reset",()=>{g=!1,Object(d.f)(p),localStorage.removeItem(u.B)})),Object(d.b)("init",()=>{const e=Object(h.d)(f),t=y(e)||e,n=Object(m.y)(t)||{};return window.history.replaceState(n,""),t});var C=n(0),E=n(57);const S=String(Date.now()+Math.random());let M;localStorage.setItem("tt-active-tab",S);const A=window.setInterval(()=>{M&&localStorage.getItem("tt-active-tab")!==S&&(M(),clearInterval(A))},2e3);var k=n(34),T=(n(85),n(86),n(88),n(31)),N=n(35),P=n(40),D=n(13);const L=["400 1em Roboto","500 1em Roboto"];function F(){if("fonts"in document)return Promise.all(L.map(e=>document.fonts.load(e)))}var B=n(55),x=n(11),R=n(8),U=(n(90),n.p+"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg"),_=n.p+"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg";function G(){const{listIds:e,byId:t}=Object(d.e)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map(e=>{const n=t[e];if(!n)return;const r=Object(T.d)(n);return r?B.b(r,l.ApiMediaFormat.DataUri):void 0}))}const $={main:()=>Promise.all([Object(x.d)(x.a.Main,"Main").then(F),G()]),authPhoneNumber:()=>Promise.all([F(),Object(D.g)(U)]),authCode:()=>Object(D.g)(_),authPassword:()=>Object(D.g)(_),authQrCode:F};var W=Object(d.h)(e=>{const{theme:t}=e.settings.byKey,{background:n,backgroundColor:r}=e.settings.themes[t]||{};return{shouldSkipUiLoaderTransition:e.shouldSkipUiLoaderTransition,uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(n),hasCustomBackgroundColor:Boolean(r),isRightColumnShown:Object(m.W)(e)}},(e,t)=>Object(h.l)(t,["setIsUiReady","setShouldSkipUiLoaderTransition"]))(({page:e,children:t,hasCustomBackground:n,hasCustomBackgroundColor:r,isRightColumnShown:u,shouldSkipUiLoaderTransition:d,setIsUiReady:o,setShouldSkipUiLoaderTransition:c})=>{const[a,i]=Object(k.a)(),{shouldRender:s,transitionClassNames:f}=Object(N.a)(!a,void 0,!0);return Object(C.n)(()=>{let t;return Promise.race([Object(b.e)(700),(async()=>{try{await $[e]()}catch(e){}})()]).then(()=>{i(),o({uiReadyState:1}),t=window.setTimeout(()=>{o({uiReadyState:2})},1e3)}),()=>{t&&(clearTimeout(t),t=void 0),o({uiReadyState:0})}},[]),Object(P.a)(()=>{d&&setTimeout(()=>{c({shouldSkipUiLoaderTransition:!1})},400)},[d]),C.a.createElement("div",{id:"UiLoader"},t,s&&!d&&C.a.createElement("div",{className:Object(R.a)("mask",f)},"main"===e?C.a.createElement(C.a.Fragment,null,C.a.createElement("div",{className:"left"}),C.a.createElement("div",{className:Object(R.a)("middle",n&&"custom-bg-image",r&&"custom-bg-color",u&&"with-right-column")}),u&&C.a.createElement("div",{className:"right"})):C.a.createElement("div",{className:"blank"})))}),H=n(18),K=n(32),z=n(48),V=n(47),q=n(16),J=n(53),Y=n(23),Q=n(63),Z=n(44),X=n(20);n(99);const ee=200+u.c;var te=Object(C.h)(({id:e,value:t,isLoading:n,onChange:r})=>{const u=Object(C.q)(null),[d,o]=Object(C.r)(),[c,a]=Object(C.r)(H.a);function i(e){o(e),a(function(e=""){return e.length?H.a.filter(t=>Object(J.a)(t.name,e)):H.a}(e))}const s=Object(C.m)(e=>{const{countryId:t}=e.currentTarget.firstElementChild.dataset,n=H.a.find(e=>e.id===t);n&&r(n),setTimeout(()=>i(void 0),ee)},[r]),f=Object(C.m)(e=>{i(e.currentTarget.value)},[]),l=Object(C.m)(e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===d&&(n.value=""),i(n.value)},[d,t]);return C.a.createElement(Q.a,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:o})=>{const c=()=>{if(o)return;setTimeout(()=>{u.current.select()},50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},a=void 0!==d?d:t&&t.name||"";return C.a.createElement("div",{className:Object(R.a)("input-group",t&&"touched")},C.a.createElement("input",{ref:u,className:Object(R.a)("form-control",o&&"focus"),type:"text",id:e,value:a,autoComplete:"off",onClick:c,onFocus:c,onInput:f,onKeyDown:l}),C.a.createElement("label",null,"Country"),n?C.a.createElement(X.a,{color:"black"}):C.a.createElement("i",{onClick:c,className:Object(R.a)("css-icon-down",o&&"open")}))}},c.map(e=>C.a.createElement(Z.a,{key:e.id,className:t&&e.id===t.id?"selected":"",onClick:s},C.a.createElement("span",{"data-country-id":e.id}),C.a.createElement("span",{className:"country-flag"},Object(Y.a)(e.flag,["hq_emoji"])),C.a.createElement("span",{className:"country-name"},e.name),C.a.createElement("span",{className:"country-code"},e.code))),!c.length&&C.a.createElement(Z.a,{key:"no-results",className:"no-results",disabled:!0},C.a.createElement("span",null,"No countries matched your filter.")))});let ne=!1;var re=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),(e,t)=>Object(h.l)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","gotToAuthQrCode"]))(({connectionState:e,authState:t,authPhoneNumber:n,authIsLoading:r,authIsLoadingQrCode:u,authError:d,authRememberMe:c,authNearestCountry:a,setAuthPhoneNumber:i,setAuthRememberMe:s,loadNearestCountry:f,clearAuthError:l,gotToAuthQrCode:b})=>{const h=Object(C.q)(null),[m,p]=Object(C.r)(),[g,y]=Object(C.r)(),[v,w]=Object(C.r)(!1),[O,I]=Object(C.r)(),j=m?`${m.code} ${g||""}`:g,E=j&&j.replace(/[^\d]+/g,"").length>=7;Object(C.n)(()=>{o.l||h.current.focus()},[m]),Object(C.n)(()=>{"connectionStateReady"!==e||a||f()},[e,a,f]),Object(C.n)(()=>{!a||m||v||p(Object(H.d)(a))},[m,a,v]);const S=Object(C.m)(e=>{const t=Object(H.e)(e),n=!m||t&&t.id!==m.id?t:m;e.length?(!m||n&&n.code!==m.code)&&p(n):p(void 0),y(Object(H.b)(e,n))},[m]);Object(C.n)(()=>{void 0===g&&n&&S(n)},[n,g,S]),Object(C.o)(()=>{h.current&&O&&h.current.setSelectionRange(...O)},[O]);const M=Object(C.m)(e=>{d&&l(),ne||(ne=!0,F(),Object(D.g)(_));const{value:t,selectionStart:n,selectionEnd:r}=e.target;I(n&&r&&r{s(e.target.checked)},[s]);const k="authorizationStateWaitPhoneNumber"===t;return C.a.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},C.a.createElement("div",{className:"auth-form"},C.a.createElement("div",{id:"logo"}),C.a.createElement("h2",null,"Sign in to Telegram"),C.a.createElement("p",{className:"note"},"Please confirm your country and",C.a.createElement("br",null),"enter your phone number."),C.a.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),r||E&&i({phoneNumber:j})}},C.a.createElement(te,{id:"sign-in-phone-code",value:m,isLoading:!a&&!m,onChange:p}),C.a.createElement(V.a,{ref:h,id:"sign-in-phone-number",label:"Phone Number",value:j,error:d,inputMode:"tel",onChange:M}),C.a.createElement(z.a,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(c),onChange:A}),E&&(k?C.a.createElement(K.a,{type:"submit",ripple:!0,isLoading:r},"Next"):C.a.createElement(q.a,null)),k&&C.a.createElement(K.a,{isText:!0,ripple:!0,isLoading:u,onClick:b},"Log in by QR code"))))})),ue=n(17);var de=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthCode");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});var oe=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthPassword");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});var ce=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthRegister");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});var ae=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Auth,"AuthQrCode");return e?C.a.createElement(e,null):C.a.createElement(q.a,null)});n(100);var ie=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["reset","initApi"]))(({authState:e,reset:t,initApi:n})=>{switch(Object(C.n)(()=>{t(),n()},[t,n]),Object(C.n)(()=>{},[]),e){case"authorizationStateWaitCode":return C.a.createElement(W,{page:"authCode",key:"authCode"},C.a.createElement(de,null));case"authorizationStateWaitPassword":return C.a.createElement(W,{page:"authPassword",key:"authPassword"},C.a.createElement(oe,null));case"authorizationStateWaitRegistration":return C.a.createElement(ce,null);case"authorizationStateWaitQrCode":return C.a.createElement(W,{page:"authQrCode",key:"authQrCode"},C.a.createElement(ae,null));case"authorizationStateWaitPhoneNumber":default:return C.a.createElement(W,{page:"authPhoneNumber",key:"authPhoneNumber"},C.a.createElement(re,null))}}));var se=Object(C.h)(()=>{const e=Object(ue.a)(x.a.Main,"Main");return e?C.a.createElement(e,null):void 0}),fe=n.p+"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png";n(101);var le=()=>C.a.createElement("div",{id:"AppInactive"},C.a.createElement("div",{className:"content"},C.a.createElement("img",{src:fe,alt:""}),C.a.createElement("h3",{className:"title"},"Such error, many tabs"),C.a.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",C.a.createElement("br",null),"Please reload this page to continue using this tab or close it."),C.a.createElement("div",{className:"actions"},C.a.createElement(K.a,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function be(){return d.c.createElement(W,{page:"main",key:"main"},d.c.createElement(se,null))}var he=Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["disconnect"]))(({authState:e,disconnect:t})=>{const[n,r]=Object(k.a)(!1);if(Object(C.n)(()=>{Object(E.b)(),M=()=>{t(),document.title=`${u.eb}${u.D}`,r()}},[t,r]),n)return d.c.createElement(le,null);if(e)switch(e){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return d.c.createElement(ie,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return be()}return localStorage.getItem(u.nb)||localStorage.getItem(u.H)?be():d.c.createElement(ie,null)});n(102);u.p&&console.log(">>> INIT"),Object(d.d)().init(),u.p&&console.log(">>> START INITIAL RENDER"),s.a.render(d.c.createElement(he,null),document.getElementById("root")),u.p&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",()=>{console.log("GLOBAL STATE",Object(d.e)())})}]); +//# sourceMappingURL=main.a06c93992fe858fca979.js.map \ No newline at end of file diff --git a/dist/main.a578e966316fd5919f1a.js.map b/dist/main.a06c93992fe858fca979.js.map similarity index 99% rename from dist/main.a578e966316fd5919f1a.js.map rename to dist/main.a06c93992fe858fca979.js.map index 9134c09f..64f397d4 100644 --- a/dist/main.a578e966316fd5919f1a.js.map +++ b/dist/main.a06c93992fe858fca979.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/config.ts","webpack:///./src/lib/teact/teactn.tsx","webpack:///./src/util/iteratees.ts","webpack:///./src/modules/helpers/messages.ts","webpack:///./src/modules/helpers/messageMedia.ts","webpack:///./src/modules/helpers/localSearch.ts","webpack:///./src/api/types/index.ts","webpack:///./src/modules/selectors/users.ts","webpack:///./src/modules/selectors/settings.ts","webpack:///./src/modules/selectors/chats.ts","webpack:///./src/modules/selectors/symbols.ts","webpack:///./src/modules/selectors/messages.ts","webpack:///./src/modules/selectors/localSearch.ts","webpack:///./src/modules/selectors/management.ts","webpack:///./src/modules/selectors/ui.ts","webpack:///./src/modules/selectors/globalSearch.ts","webpack:///./src/modules/selectors/payments.ts","webpack:///./src/util/environment.ts","webpack:///./src/util/buildClassName.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/util/files.ts","webpack:///./src/assets/lang/en-extra.json","webpack:///./src/assets/lang/es-extra.json","webpack:///./src/assets/lang/it-extra.json","webpack:///./src/assets/lang/pl-extra.json","webpack:///./src/assets/lang/ru-extra.json","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/types/index.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/modules/actions/api/sessions.ts","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/util/arePropsShallowEqual.ts","webpack:///./src/hooks/useLang.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/util/generateIdFor.ts","webpack:///./src/util/notifications.ts","webpack:///./src/modules/helpers/users.ts","webpack:///./src/modules/helpers/chats.ts","webpack:///./src/components/ui/Button.tsx","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/modules/reducers/chats.ts","webpack:///./src/modules/reducers/messages.ts","webpack:///./src/modules/reducers/symbols.ts","webpack:///./src/modules/reducers/users.ts","webpack:///./src/modules/reducers/globalSearch.ts","webpack:///./src/modules/reducers/localSearch.ts","webpack:///./src/modules/reducers/management.ts","webpack:///./src/modules/reducers/settings.ts","webpack:///./src/modules/reducers/twoFaSettings.ts","webpack:///./src/modules/reducers/payments.ts","webpack:///./src/hooks/usePrevious.ts","webpack:///./src/util/history.ts","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/util/trimText.ts","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/components/ui/MenuItem.tsx","webpack:///./src/components/ui/RippleEffect.tsx","webpack:///./src/util/webpToPng.ts","webpack:///./src/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/hooks/useEffectWithPrevDeps.ts","webpack:///./src/components/common/helpers/documentInfo.ts","webpack:///./src/modules/helpers/payments.ts","webpack:///./src/util/animation.ts","webpack:///./src/components/ui/DropdownMenu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.ts","webpack:///./src/util/emoji.ts","webpack:///./src/lib/teact/teact-dom.ts","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/components/middle/message/MentionLink.tsx","webpack:///./src/util/switchTheme.ts","webpack:///./src/util/appBadge.ts","webpack:///./src/hooks/useVirtualBackdrop.ts","webpack:///./src/api/gramjs/worker/worker.ts","webpack:///./node_modules/opus-recorder/dist/decoderWorker.min.js","webpack:///./node_modules/opus-recorder/dist/waveWorker.min.js","webpack:///./src/lib/webp/webp_wasm.worker.js","webpack:///./src/modules/actions/ui/initial.ts","webpack:///./src/modules/actions/api/initial.ts","webpack:///./node_modules/process/browser.js","webpack:///./src/modules/actions/apiUpdaters/initial.ts","webpack:///./src/serviceWorker.ts","webpack:///./src/util/setupServiceWorker.ts","webpack:///./src/global/initial.ts","webpack:///./src/global/cache.ts","webpack:///./src/global/index.ts","webpack:///./src/util/activeTabMonitor.ts","webpack:///./src/util/fonts.ts","webpack:///./src/assets/telegram-logo.svg","webpack:///./src/assets/monkey.svg","webpack:///./src/components/common/UiLoader.tsx","webpack:///./src/components/auth/CountryCodeInput.tsx","webpack:///./src/components/auth/AuthPhoneNumber.tsx","webpack:///./src/components/auth/AuthCode.async.tsx","webpack:///./src/components/auth/AuthPassword.async.tsx","webpack:///./src/components/auth/AuthRegister.async.tsx","webpack:///./src/components/auth/AuthQrCode.async.tsx","webpack:///./src/components/auth/Auth.tsx","webpack:///./src/components/main/Main.async.tsx","webpack:///./src/assets/app-inactive.png","webpack:///./src/components/main/AppInactive.tsx","webpack:///./src/App.tsx","webpack:///./src/index.tsx"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","installedModules","installedCssChunks","2","__webpack_require__","exports","module","l","e","promises","Promise","resolve","reject","href","fullhref","p","existingLinkTags","document","getElementsByTagName","dataHref","tag","getAttribute","rel","existingStyleTags","linkTag","createElement","type","onload","onerror","event","request","target","src","err","Error","code","parentNode","removeChild","appendChild","then","installedChunkData","promise","onScriptComplete","script","charset","timeout","nc","setAttribute","jsonpScriptSrc","error","clearTimeout","chunk","errorType","realSrc","message","name","undefined","setTimeout","head","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","console","jsonpArray","window","oldJsonpFunction","slice","s","VirtualElementTypesEnum","Fragment","renderingInstance","isEmptyElement","$element","Empty","isTextElement","Text","isTagElement","Tag","isComponentElement","Component","isRealElement","source","props","children","flatten","parsedChildren","componentInstance","isMounted","hooks","state","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","map","buildChildElement","buildTagElement","isEmptyPlaceholder","child","String","DEBUG_components","renderComponent","newRenderedValue","DEBUG_startAt","DEBUG","componentName","renderCount","renderTimes","DEBUG_MORE","log","performance","now","renderTime","warn","Math","round","handleError","renderedValue","newChild","hasElementChanged","$old","$new","unmountTree","forEach","hook","current","cleanup","effect","dependencies","nextValue","setter","forceUpdate","onUpdate","helpGc","unmountComponent","removeAllDelegatedListeners","mountComponent","forceUpdateComponent","currentElement","getTarget","setTarget","useState","initial","newValue","prepareForFrame","throttleWithPrimaryRaf","prepareComponentForFrame","throttleWithRaf","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","exec","some","dependency","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","withDebug","propsRef","renderedRef","getUnequalProps","join","addEventListener","orderBy","values","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","APP_VERSION","process","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","isBigScreen","Set","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","STICKER_SIZE_INLINE_DESKTOP_FACTOR","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","MEMOJI_STICKER_ID","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_TEMPLATE","RE_TME_LINK","RE_TME_INVITE_LINK","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","LANG_PACKS","TIPS_USERNAME","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacks","cb","runCallbacksThrottled","newGlobal","noThrottle","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","TeactNContainer","id","generateIdFor","useForceUpdate","delete","set","buildCollectionByKey","collection","reduce","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","filter","has","orderKey","sort","a","b","Array","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","from","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","lang","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","groupedId","isGif","emoji","title","performer","fileName","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","entities","link","find","entity","ApiMessageEntityTypes","TextUrl","url","Url","offset","substring","domain","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","action","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","sender","getUserFullName","getChatTitle","getSendingState","sendingState","isHistoryClearMessage","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","base","hasMessageLocalBlobUrl","canMessagePlayVideoInline","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageMediaFilename","date","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","reverseOrder","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","selectUser","global","userId","users","byId","selectNotifySettings","settings","selectNotifyExceptions","notifyExceptions","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","user","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","fullInfo","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","includes","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","selectIsChatMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","cleanedEmoji","replace","selectEmojiKeywords","language","emojiKeywords","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","selectThreadOriginChat","threadInfo","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","currentMessageList","selectIsViewportNewest","viewportIds","lastMessageId","selectChatMessage","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","focusedMessage","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","fromChatId","senderUserId","selectAllowedMessageActions","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","getHasAdminRight","canPin","canUnpin","pinnedMessageIds","canDelete","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","Infinity","selectFirstUnreadId","outlyingIds","lastReadId","isNotJoined","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","isCommonBoxChat","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","fromMessageId","selectMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","isChatGroup","userOrChat","contactList","userIds","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","chatThreadKey","currentSearch","localTextSearch","byChatThreadKey","isActive","selectCurrentMediaSearchPeerId","localMediaSearch","currentProfileUserId","selectedId","selectCurrentMediaSearch","peerId","selectManagement","management","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_MOBILE_SCREEN","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","UserInfo","ChatInfo","selectIsRightColumnShown","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_TOUCH_ENV","matchMedia","matches","innerWidth","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","parts","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","args","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","waiting","onIdle","requestIdleCallback","pause","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","isPrimary","requestAnimationFrame","currentCallbacks","currentPrimaryCallbacks","worker","requestStates","requestStatesByCallback","initApi","sessionData","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","Bundles","LOAD_PROMISES","MEMORY_CACHE","async","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","cacheApi","caches","Type","fetch","cacheName","Request","cache","open","Blob","blob","substr","headers","Json","json","save","cacheData","JSON","stringify","Response","put","clear","File","constructor","fileBits","options","rest","super","this","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","canvas","videoWidth","videoHeight","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","EXTRA_PACK_PATHS","en","enExtraJson","es","esExtraJson","it","itExtraJson","pl","plExtraJson","ru","ruExtraJson","PLURAL_OPTIONS","PLURAL_RULES","ar","ca","de","fa","fr","ko","nl","pt_BR","tr","uk","uz","langPack","createCallbackManager","currentLangCode","getTranslation","format","cached","langString","template","amount","optionIndex","getPluralOption","trim","processTemplate","formatInteger","setLanguage","langCode","newLangPack","remote","sourceLangPacks","fetchFromCacheOrRemote","pairs","extraLangPack","languages","langInfo","isRtl","rtl","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","noLoad","autoUpdate","formatsCache","defaultPhoneNumberFormat","parsed","str","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","repeat","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","startsWith","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","Spinner","buildClassName","handleErrorEvent","startedAt","isReloading","preventDefault","ErrorEvent","reason","alert","localStorage","getItem","removeItem","location","reload","APP_ENV","DC_IDS","storeSession","mainDcId","hashes","setItem","dcID","dcId","clearStoredSession","loadStoredSession","legacySessionJson","parse","hash","importLegacySession","sessionId","sessionJson","idb","clearLegacySessions","idbKeys","k","importTestSession","env","TEST_SESSION","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","renderText","part","filters","params","textParts","divEl","innerText","innerHTML","escapeHtml","EMOJI_REGEX","lastIndex","replaceEmojis","addLineBreaks","highlight","lowerCaseText","queryPosition","nextSymbol","newParts","links","RE_MENTION","nextLink","endsWith","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","entityResult","currentProps","newProps","currentKeys","currentKeysLength","prop","useOnChange","langProvider","setTrigger","trigger","Link","onClick","handleClick","dir","store","random","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","requestPermission","unsubscribeFromPush","dispatch","deviceToken","unsubscribe","deleteDeviceToken","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","subscribe","replaceSettings","loadNotificationSettings","subscribedAt","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","showNewMessageNotification","isActiveChat","hasFocus","hasPrivateChatsNotifications","hasGroupNotifications","hasBroadcastNotifications","checkIfShouldNotify","body","messageSender","messageAction","actionTargetMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","actionTargetUser","privateChatUserId","privateChatUser","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","getNotificationContent","controller","icon","badge","toString","vibrate","notification","onclick","close","focusMessage","focus","notifyClientReady","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","getTime","floor","today","setHours","formatTime","yesterday","setDate","getDate","formatFullDate","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","getChatSlowModeOptions","slowMode","getChatOrder","max","joinDate","isChatArchived","notifySettings","isMuted","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","isChat","chatOrUser","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","Button","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","handleMouseDown","aria-label","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeEventListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","setValue","isOpen","onCloseTransitionEnd","noOpenTransition","noCloseTransition","isClosed","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","isClosing","shouldRender","transitionClassNames","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChats","updatedById","addChats","addedById","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","canDeleteCurrentThread","currentThreadId","originalPost","deleteChatScheduledMessages","scheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","updateScheduledMessages","updateFocusedMessage","noHighlight","updateFocusDirection","direction","enterMessageSelectMode","toggleMessageSelection","childMessageIds","withShift","oldSelectedMessages","newMessageIds","newSelectedMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateUser","userUpdate","contactUserIds","updatedUser","updateUsers","addUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","getComplexKey","updateGlobalSearch","searchStatePartial","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","newState","fetchingStatus","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","newSettings","replaceThemeSettings","theme","themes","addNotifyException","notifyException","updateNotifySettings","peerType","isSilent","shouldShowPreviews","hasPrivateChatsMessagePreview","hasGroupMessagePreview","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","usePrevious","next","shouldSkipUndefined","HistoryWrapper","states","isHistoryChangedByUser","pushState","history","back","prevDeps","trimText","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","createStore","customStore","del","eachCursor","openCursor","continue","items","MenuItem","destructive","useLang","handleKeyDown","keyCode","data-char","origin","role","onKeyDown","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","webpToPng","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","onmessage","handleLibWebpMessage","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","labelText","htmlFor","subLabel","checked","blocking","onCheck","handleChange","captureEscKeyListener","captureKeyboardListener","onEsc","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","shouldSkipTransition","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","getFromMemory","cancelProgress","mediaData","fullSize","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","IS_LANDSCAPE","isLandscape","windowSize","updateSizes","handleResize","vh","setProperty","utf16","len","RangeError","adapt","delta","numpoints","firsttime","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","ensureProtocol","getDomain","decodedHref","decodeURI","convertPunycode","toggleSafeLinkModal","openTelegramLink","isNotSafe","ctrlKey","altKey","shiftKey","metaKey","classNames","getFileSizeString","bytes","ONE_GIGABYTE","ONE_MEGABYTE","getDocumentExtension","getFileExtension","getColorFromExtension","extension","STRIPE_ERRORS","missing_payment_information","field","fieldError","invalid_number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","SHIPPING_ERRORS","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","getShippingError","errors","cur","currentInstance","animateSingle","tick","instance","isCancelled","animate","DropdownMenu","forceOpen","onOpen","dropdownRef","setIsOpen","menu","focusedElement","activeElement","elementChildren","onTrigger","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","querySelectorAll","newIndex","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","updateComponent","setupComponentUpdateListener","initComponent","node","createNode","childNodes","insertBefore","replaceChild","areComponents","nextSibling","newKeys","removeAttribute","addAttribute","oldValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","createDocumentFragment","renderChildren","$firstChild","createTextNode","$child","$fragmentChild","cssText","render","headId","$head","openUserInfo","handleMessageClick","openChat","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","renderChatContent","renderUserContent","renderOriginContent","showQuotes","messageText","renderMessageContent","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","MESSAGE_DELETED","openChatByUsername","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","transition","updateAppBadge","setAppBadge","contains","animationLevel","messageTextSize","switchTheme","uiReadyState","contentKey","authPhoneNumber","authRememberMe","authError","shouldSkipUiLoaderTransition","apiUpdate","authIsLoading","password","file","authIsLoadingQrCode","reset","langCachePrefix","langCacheVersion","init","connectionState","authNearestCountry","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","arguments","apply","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","binding","cwd","chdir","umask","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","saveSession","onUpdateSession","currentUser","sessionUserAuth","userAuth","updateSessionUserId","onUpdateCurrentUser","showError","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","activeChatFolder","recentEmojis","added","recent","featured","saved","topPeers","audioPlayer","notifications","activeSessions","messageSendKeyCombo","shouldSuggestStickers","light","isBlurred","patternColor","dark","privacy","updateCacheThrottled","isAllowed","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","loadCache","initialState","time","timeEnd","readCache","idsToSave","cid","chatIdsToSave","mainThread","replaceState","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","mediaLoader","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","setIsUiReady","setShouldSkipUiLoaderTransition","isReady","markReady","useFlag","shouldRenderMask","safePreload","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","data-country-id","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","gotToAuthQrCode","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","setSelectionRange","handlePhoneNumberChange","selectionStart","selectionEnd","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","AuthQrCode","AppInactive","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GAKAK,EAAI,EAAGC,EAAW,GACpCD,EAAIF,EAASI,OAAQF,IACzBH,EAAUC,EAASE,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBV,IAAYU,EAAgBV,IACpFI,EAASO,KAAKD,EAAgBV,GAAS,IAExCU,EAAgBV,GAAW,EAE5B,IAAID,KAAYG,EACZI,OAAOC,UAAUC,eAAeC,KAAKP,EAAaH,KACpDa,EAAQb,GAAYG,EAAYH,IAKlC,IAFGc,GAAqBA,EAAoBf,GAEtCM,EAASC,QACdD,EAASU,OAATV,GAOF,IAAIW,EAAmB,GAGnBC,EAAqB,CACxBC,EAAG,GAMAP,EAAkB,CACrBO,EAAG,GAWJ,SAASC,EAAoBnB,GAG5B,GAAGgB,EAAiBhB,GACnB,OAAOgB,EAAiBhB,GAAUoB,QAGnC,IAAIC,EAASL,EAAiBhB,GAAY,CACzCI,EAAGJ,EACHsB,GAAG,EACHF,QAAS,IAUV,OANAP,EAAQb,GAAUU,KAAKW,EAAOD,QAASC,EAAQA,EAAOD,QAASD,GAG/DE,EAAOC,GAAI,EAGJD,EAAOD,QAKfD,EAAoBI,EAAI,SAAuBtB,GAC9C,IAAIuB,EAAW,GAKZP,EAAmBhB,GAAUuB,EAASZ,KAAKK,EAAmBhB,IACzB,IAAhCgB,EAAmBhB,IAFX,CAAC,EAAI,EAAE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AGd+jE,IAAS1Q,OACP,kBAAC,GAAD,MACAz6D,SAASqoE,eAAe,SAGtBthE,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAASkL,iBAAiB,WAAY,KAEpChH,QAAQkD,IAAI,eAAgB+K","file":"main.a578e966316fd5919f1a.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t};\n\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded CSS chunks\n \tvar installedCssChunks = {\n \t\t2: 0\n \t}\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"7710475e3e81de39d2af\",\"1\":\"aad05fd8644c664595f3\",\"3\":\"49069e079072f537e8c6\",\"4\":\"d58ed6ebd279d8e97ea9\",\"5\":\"3ab589fa3f713177f16b\",\"6\":\"cbe2455ba67c892471e4\",\"7\":\"3c4397f983ad7c01b144\",\"8\":\"a6fd4c4c763fc9d2ae68\",\"9\":\"6995fbf88b84d270550e\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// mini-css-extract-plugin CSS loading\n \t\tvar cssChunks = {\"0\":1,\"3\":1,\"4\":1,\"5\":1,\"6\":1};\n \t\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n \t\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n \t\t\tpromises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {\n \t\t\t\tvar href = \"\" + ({}[chunkId]||chunkId) + \".\" + {\"0\":\"7710475e3e81de39d2af\",\"1\":\"aad05fd8644c664595f3\",\"3\":\"49069e079072f537e8c6\",\"4\":\"d58ed6ebd279d8e97ea9\",\"5\":\"3ab589fa3f713177f16b\",\"6\":\"cbe2455ba67c892471e4\",\"7\":\"3c4397f983ad7c01b144\",\"8\":\"a6fd4c4c763fc9d2ae68\",\"9\":\"6995fbf88b84d270550e\"}[chunkId] + \".css\";\n \t\t\t\tvar fullhref = __webpack_require__.p + href;\n \t\t\t\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n \t\t\t\tfor(var i = 0; i < existingLinkTags.length; i++) {\n \t\t\t\t\tvar tag = existingLinkTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n \t\t\t\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return resolve();\n \t\t\t\t}\n \t\t\t\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n \t\t\t\tfor(var i = 0; i < existingStyleTags.length; i++) {\n \t\t\t\t\tvar tag = existingStyleTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\");\n \t\t\t\t\tif(dataHref === href || dataHref === fullhref) return resolve();\n \t\t\t\t}\n \t\t\t\tvar linkTag = document.createElement(\"link\");\n \t\t\t\tlinkTag.rel = \"stylesheet\";\n \t\t\t\tlinkTag.type = \"text/css\";\n \t\t\t\tlinkTag.onload = resolve;\n \t\t\t\tlinkTag.onerror = function(event) {\n \t\t\t\t\tvar request = event && event.target && event.target.src || fullhref;\n \t\t\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + request + \")\");\n \t\t\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n \t\t\t\t\terr.request = request;\n \t\t\t\t\tdelete installedCssChunks[chunkId]\n \t\t\t\t\tlinkTag.parentNode.removeChild(linkTag)\n \t\t\t\t\treject(err);\n \t\t\t\t};\n \t\t\t\tlinkTag.href = fullhref;\n\n \t\t\t\tvar head = document.getElementsByTagName(\"head\")[0];\n \t\t\t\thead.appendChild(linkTag);\n \t\t\t}).then(function() {\n \t\t\t\tinstalledCssChunks[chunkId] = 0;\n \t\t\t}));\n \t\t}\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\n \t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n \t\t\t// a Promise means \"currently loading\".\n \t\t\tif(installedChunkData) {\n \t\t\t\tpromises.push(installedChunkData[2]);\n \t\t\t} else {\n \t\t\t\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 103);\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, onTickEnd, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\nexport type FC_withDebug = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We force cleaning as many objects as possible. Not sure this is needed at all.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[Teact.useState]',\n componentInstance.name,\n // `componentInstance.Component` may be set to `null` by GC helper\n componentInstance.Component && (componentInstance.Component as FC_withDebug).DEBUG_contentComponentName\n ? `> ${(componentInstance.Component as FC_withDebug).DEBUG_contentComponentName}`\n : '',\n `Forced update at cursor #${cursor}, next value: `,\n byCursor[cursor].nextValue,\n );\n }\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[]): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual, withDebug = false) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && withDebug) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name}: Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\n// noThrottle = true is used as a workaround for iOS gesture history navigation\nexport function setGlobal(newGlobal?: GlobalState, noThrottle = false) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (!noThrottle) {\n runCallbacksThrottled();\n } else {\n runCallbacks();\n }\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload, noThrottle?: boolean) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, noThrottle);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload, noThrottle = false) => {\n onDispatch(name, payload, noThrottle);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${text ? text.text : lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji} ${lang('AttachSticker')} `;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n return `${noEmoji ? '' : '🎧 '}${caption || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${text ? text.text : lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && video.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(lang, sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video && video.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record, messageIds: number[], contentType: ApiMessageSearchType,\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n default:\n return [] as Array;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video;\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: number): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: number) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: number, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: number): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && !selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\nimport { LangCode, EmojiKeywords } from '../../types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectEmojiKeywords(global: GlobalState, language: LangCode): EmojiKeywords | undefined {\n return global.emojiKeywords[language] && global.emojiKeywords[language] !== undefined\n ? global.emojiKeywords[language] as EmojiKeywords\n : undefined;\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists && messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: number,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: number, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: number) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return senderId > 0 ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const isMessageEditable = (\n (isChatWithSelf || Date.now() - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId || Infinity);\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: number, threadId: number) {\n const chat = selectChat(global, chatId);\n\n if (threadId === MAIN_THREAD_ID) {\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n if (!lastReadId && chat && chat.isNotJoined) {\n return undefined;\n }\n\n if (outlyingIds) {\n const found = !lastReadId ? outlyingIds[0] : outlyingIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = !lastReadId ? listedIds[0] : listedIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(chatId));\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n }));\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: number, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: number,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n} from '../config';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'Mac OS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n));\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nlet isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiOnProgress, ApiSessionData, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nlet worker: Worker;\nconst requestStates = new Map();\nconst requestStatesByCallback = new Map();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [sessionData],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\nimport { getGlobal } from '../lib/teact/teactn';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n}\n\nconst EXTRA_PACK_PATHS: Record = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map();\n\nlet langPack: ApiLangPack;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n};\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages } = getGlobal().settings.byKey;\n const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined;\n getTranslation.isRtl = Boolean(langInfo && langInfo.rtl);\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 2c193ce 28.05.2021\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f|\\u2764\\ufe0f\\u200d\\ud83d\\udd25|\\u2764\\ufe0f\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n

\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\n","import {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport type ThemeKey = 'light' | 'dark';\nexport interface IThemeSettings {\n background?: string;\n backgroundColor?: string;\n patternColor?: string;\n isBlurred?: boolean;\n}\n\nexport type NotifySettings = {\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n};\n\nexport type LangCode = (\n 'en' | 'ar' | 'be' | 'ca' | 'nl' | 'fr' | 'de' | 'id' | 'it' | 'ko' | 'ms' | 'fa' | 'pl' | 'pt-br' | 'ru' | 'es'\n | 'tr' | 'uk' | 'uz'\n);\n\nexport interface ISettings extends NotifySettings, Record {\n theme: ThemeKey;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersIncludedChats,\n FoldersExcludedChats,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record;\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","import { DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY } from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache and refresh the page\n if (Date.now() - startedAt <= STARTUP_TIMEOUT && localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","import * as idb from 'idb-keyval';\n\nimport { ApiSessionData } from '../../../api/types';\n\nimport { DEBUG, LEGACY_SESSION_KEY, SESSION_USER_KEY } from '../../../config';\nimport * as cacheApi from '../../../util/cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: number) {\n const { mainDcId, keys, hashes } = sessionData;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify({ dcID: mainDcId, id: currentUserId }));\n localStorage.setItem('dc', String(mainDcId));\n Object.keys(keys).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_auth_key`, JSON.stringify(keys[dcId]));\n });\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\n}\n\nexport function clearStoredSession() {\n [\n SESSION_USER_KEY,\n 'dc',\n ...DC_IDS.map((dcId) => `dc${dcId}_auth_key`),\n ...DC_IDS.map((dcId) => `dc${dcId}_hash`),\n ].forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n\nexport function loadStoredSession(): ApiSessionData | undefined {\n const legacySessionJson = localStorage.getItem(SESSION_USER_KEY);\n if (!legacySessionJson) return undefined;\n\n const { dcID: mainDcId } = JSON.parse(legacySessionJson);\n const keys: Record = {};\n const hashes: Record = {};\n\n DC_IDS.forEach((dcId) => {\n try {\n const key = localStorage.getItem(`dc${dcId}_auth_key`);\n if (key) {\n keys[dcId] = JSON.parse(key);\n }\n\n const hash = localStorage.getItem(`dc${dcId}_hash`);\n if (hash) {\n hashes[dcId] = JSON.parse(hash);\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load stored session', err);\n }\n // Do nothing.\n }\n });\n\n if (!Object.keys(keys).length) return undefined;\n\n return {\n mainDcId,\n keys,\n hashes,\n };\n}\n\nexport async function importLegacySession() {\n const sessionId = localStorage.getItem(LEGACY_SESSION_KEY);\n if (!sessionId) return;\n\n const sessionJson = await idb.get(`GramJs:${sessionId}`);\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load legacy session', err);\n }\n // Do nothing.\n }\n}\n\n// Remove previously created IndexedDB and cache API sessions\nexport async function clearLegacySessions() {\n localStorage.removeItem(LEGACY_SESSION_KEY);\n\n const idbKeys = await idb.keys();\n\n await Promise.all>([\n cacheApi.clear('GramJs'),\n ...idbKeys\n .filter((k) => typeof k === 'string' && k.startsWith('GramJs:GramJs-session-'))\n .map((k) => idb.del(k)),\n ]);\n}\n\nexport function importTestSession() {\n const sessionJson = process.env.TEST_SESSION!;\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load test session', err);\n }\n // Do nothing.\n }\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? {emoji}\n : (\n \n ),\n );\n }\n if (type === 'html') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? emoji\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n : `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/ig;\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = [...(part.match(RE_LINK) || []), ...(part.match(RE_MENTION) || [])];\n if (!links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n if (currentProps === newProps) {\n return true;\n }\n\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n if (currentKeysLength === 0) {\n return true;\n }\n\n for (let i = 0; i < currentKeysLength; i++) {\n const prop = currentKeys[i];\n if (currentProps[prop] !== newProps[prop]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['%LENGTH%'];\n }\n\n return currentKeys.filter((prop) => currentProps[prop] !== newProps[prop]);\n}\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { callApi } from '../api/gramjs';\nimport { ApiChat, ApiMessage } from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({\n endpoint: data.endpoint,\n keys: data.keys,\n });\n}\n\nfunction checkIfPushSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nfunction checkIfNotificationsSupported() {\n // Let's check if the browser supports notifications\n if (!('Notification' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] This browser does not support desktop notification');\n }\n return false;\n }\n\n if (Notification.permission === 'denied' as NotificationPermission) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\n\nexport async function unsubscribe() {\n if (!checkIfPushSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribeFromPush(subscription);\n}\n\n// Load notification settings from the api\nasync function loadNotificationSettings() {\n const [result] = await Promise.all([\n callApi('fetchNotificationSettings'),\n callApi('fetchNotificationExceptions'),\n ]);\n\n if (!result) return;\n setGlobal(replaceSettings(getGlobal(), result));\n}\n\nexport async function subscribe() {\n loadNotificationSettings();\n\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat, isActive: boolean) {\n const global = getGlobal();\n\n if (selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global)) || chat.isNotJoined) {\n return false;\n }\n\n // Dont show notification for active chat if client has focus\n if (isActive && document.hasFocus()) return false;\n\n switch (chat.type) {\n case 'chatTypePrivate':\n case 'chatTypeSecret':\n return Boolean(global.settings.byKey.hasPrivateChatsNotifications);\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return Boolean(global.settings.byKey.hasGroupNotifications);\n case 'chatTypeChannel':\n return Boolean(global.settings.byKey.hasBroadcastNotifications);\n }\n return false;\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserId: actionTargetUserId,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n const actionTargetUser = actionTargetUserId ? selectUser(global, actionTargetUserId) : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n let body: string;\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nexport function showNewMessageNotification({\n chat,\n message,\n isActiveChat,\n}: { chat: ApiChat; message: Partial; isActiveChat: boolean}) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n if (!checkIfShouldNotify(chat, isActiveChat)) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon: 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag: message.id.toString(),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date();\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > today) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record,\n priorityIds?: number[],\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { LangFn } from '../../hooks/useLang';\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(lang: LangFn, chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return lang('SavedMessages');\n }\n return chat.title || lang('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && chat.defaultBannedRights[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isChatPrivate(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(chat.joinDate || 0, chat.lastMessage ? chat.lastMessage.date : 0);\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions?: Record,\n) {\n return !(notifyExceptions && notifyExceptions[chat.id] && !notifyExceptions[chat.id].isMuted) && (\n chat.isMuted\n || (isChatPrivate(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return lang('FromYou');\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: number[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent) => {\n e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {isLoading ? (\n
\n Please wait..\n \n
\n ) : children}\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement) {\n return (\n !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n ((hasOpenClassName && !noCloseTransition) || (noCloseTransition && isOpen)) && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(lang: LangFn, datetime: number | Date, isShort = false, noWeekdays = false) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n return isShort\n ? lowerFirst(lang(`Weekday.Short${weekDay}`))\n : upperFirst(lang(`Weekday.${weekDay}`));\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = lang(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date) {\n return date.toLocaleString(\n 'en-US',\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && listIds.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: number[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record;\n threadsById: Record;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, update: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam(\n global: GlobalState, chatId: number, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record>);\n\n Object.keys(addedByChatId).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, newById: Record,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && currentMessageList.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && listedIds.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && outlyingIds.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, threadId: number, update: Partial | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: number, updates: Partial[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: number, newById: Record, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record; hash: number }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: number,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: number,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results && results.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: number,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: number,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function replaceThemeSettings(\n global: GlobalState, theme: ThemeKey, newSettings?: Partial,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n themes: {\n ...global.settings.themes,\n [theme]: {\n ...(global.settings.themes[theme] || {}),\n ...newSettings,\n },\n },\n },\n };\n}\n\nexport function addNotifyException(\n global: GlobalState, id: number, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious(next: T): T | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined: true): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","\nexport const HistoryWrapper: {\n pushState(data: any): void;\n back(): void;\n states: any[];\n isHistoryChangedByUser: boolean;\n} = {\n states: [],\n isHistoryChangedByUser: true,\n pushState(data: any) {\n this.states.push(data);\n\n window.history.pushState(data, '');\n },\n back() {\n this.isHistoryChangedByUser = false;\n window.history.back();\n this.states.pop();\n },\n};\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }: Ripple) => (\n \n ))}\n
\n );\n};\n\nexport default memo(RippleEffect);\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, url: string): Promise {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise {\n return new Promise((resolve) => {\n worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n}) => {\n const lang = useLang();\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n
\n \n {labelText && (\n \n )}\n
\n );\n};\n\nexport default memo(InputText);\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","const RE_NOT_LETTER = /[^\\wа-яё]+/;\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n shouldSkipTransition,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const {\n transitionClassNames,\n } = useShowTransition(\n isOpen,\n onCloseAnimationEnd,\n shouldSkipTransition,\n undefined,\n shouldSkipTransition,\n );\n\n useEffect(\n () => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n \n );\n};\n\nexport default Menu;\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\n\nexport function fetch(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!);\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\n }\n\n if (progress === 1) {\n mediaSource.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer.appendBuffer(arrayBuffer!);\n });\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = blob.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onLeft' | 'onRight'\n| 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial>;\n\nconst keyToHandlerName: Record = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n ArrowLeft: 'onLeft',\n ArrowRight: 'onRight',\n Tab: 'onTab',\n};\n\nconst handlers: Record = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onLeft: [],\n onRight: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","import { throttle } from './schedulers';\nimport {\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../config';\nimport { IS_IOS, IS_MOBILE_SCREEN } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_MOBILE_SCREEN && isLandscape();\n\nlet windowSize = updateSizes();\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if ((isMobileScreen() !== IS_MOBILE_SCREEN) || (IS_MOBILE_SCREEN && IS_LANDSCAPE !== isLandscape())) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n};\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n toggleSafeLinkModal,\n openTelegramLink,\n}) => {\n const content = children || text;\n const isNotSafe = url !== content;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TME_INVITE_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {content}\n \n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSafeLinkModal', 'openTelegramLink',\n ]),\n)(SafeLink));\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","const STRIPE_ERRORS: Record> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingError(errors: Record) {\n return Object.values(errors).reduce((acc, cur) => {\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n forceOpen?: boolean;\n onOpen?: NoneToVoidFunction;\n onClose?: NoneToVoidFunction;\n children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n forceOpen,\n onOpen,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n if (isOpen) {\n if (onClose) onClose();\n } else if (onOpen) onOpen();\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n if (onClose) onClose();\n };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n \n );\n};\n\nexport default DropdownMenu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array;\n emojis: Record;\n};\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function nativeToUnfified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1][0])) {\n category.emojis.push(emojiRaw[1][0]);\n emojiData.emojis[emojiRaw[1][0]] = {\n id: emojiRaw[1][0],\n names: emojiRaw[1] as string[],\n native: unifiedToNative(emojiRaw[0] as string),\n image: (emojiRaw[0] as string).toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUser\n ? renderUserContent(targetUser, options.asPlain)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = `«${text}»`;\n }\n\n if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(lang, origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\n","import { DEBUG } from '../config';\n\nexport function updateAppBadge(unreadCount: number) {\n if (typeof window.navigator.setAppBadge !== 'function') {\n return;\n }\n\n window.navigator.setAppBadge(unreadCount).catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"6b9e1c477ee38548ce72.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { HistoryWrapper } from '../../../util/history';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel > 0);\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\n }\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n HistoryWrapper.pushState({\n type: 'login',\n contentKey: 'authCode',\n });\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('setShouldSkipUiLoaderTransition', (global, actions, payload) => {\n const { shouldSkipUiLoaderTransition } = payload;\n\n return {\n ...global,\n shouldSkipUiLoaderTransition,\n };\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { HistoryWrapper } from '../../../util/history';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n storeSession,\n loadStoredSession,\n clearStoredSession,\n importLegacySession,\n clearLegacySessions,\n importTestSession,\n} from './sessions';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n } else {\n importTestSession();\n }\n\n void initApi(actions.apiUpdate, loadStoredSession());\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('gotToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n HistoryWrapper.pushState({\n type: 'login',\n contentKey: 'authQr',\n });\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n storeSession(payload.sessionData, global.currentUserId);\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribe();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser,\n} from '../../../api/types';\nimport { DEBUG, SESSION_USER_KEY } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateSession':\n onUpdateSession(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n subscribe();\n setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n if (!getGlobal().authRememberMe) {\n return;\n }\n\n const { sessionData } = update;\n\n getDispatch().saveSession({ sessionData });\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n\n updateSessionUserId(currentUser.id);\n}\n\nfunction updateSessionUserId(currentUserId: number) {\n const sessionUserAuth = localStorage.getItem(SESSION_USER_KEY);\n if (!sessionUserAuth) return;\n\n const userAuth = JSON.parse(sessionUserAuth);\n userAuth.id = currentUserId;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify(userAuth));\n}\n","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n subscribeToWorker();\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n window.addEventListener('focus', async () => {\n await navigator.serviceWorker.ready;\n subscribeToWorker();\n });\n}\n","import { GlobalState } from './types';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n} from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n activeChatFolder: 0,\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n LEGACY_SESSION_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT, SESSION_USER_KEY,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n if (hasSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\n}\n\nfunction readCache(initialState: GlobalState) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n // Pre-fill defaults in nested objects which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'emojiKeywords',\n 'push',\n ]),\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey, themes } = global.settings;\n\n return {\n byKey,\n themes,\n privacy: {},\n notifyExceptions: {},\n };\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useOnChange from '../../hooks/useOnChange';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\nconst TRANSITION_TIME = 400;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipUiLoaderTransition,\n setIsUiReady,\n setShouldSkipUiLoaderTransition,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useOnChange(() => {\n if (shouldSkipUiLoaderTransition) {\n setTimeout(() => {\n setShouldSkipUiLoaderTransition({ shouldSkipUiLoaderTransition: false });\n }, TRANSITION_TIME);\n }\n }, [shouldSkipUiLoaderTransition]);\n\n return (\n
\n {children}\n {shouldRenderMask && !shouldSkipUiLoaderTransition && (\n
\n {page === 'main' ? (\n <>\n
\n \n {isRightColumnShown &&
}\n \n ) : (\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n shouldSkipUiLoaderTransition: global.shouldSkipUiLoaderTransition,\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady', 'setShouldSkipUiLoaderTransition']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC = ({\n id,\n value,\n isLoading,\n onChange,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [filter, setFilter] = useState();\n const [filteredList, setFilteredList] = useState(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, []);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList.map((country: Country) => (\n \n \n {renderText(country.flag, ['hq_emoji'])}\n {country.name}\n {country.code}\n \n ))}\n {!filteredList.length && (\n \n No countries matched your filter.\n \n )}\n \n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [country, setCountry] = useState();\n const [phoneNumber, setPhoneNumber] = useState();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n\n const fullNumber = country ? `${country.code} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n parseFullNumber(value);\n }, [authError, clearAuthError, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n
\n
\n
\n

Sign in to Telegram

\n

\n Please confirm your country and\n
enter your phone number.\n

\n
\n \n \n \n {canSubmit && (\n isAuthReady ? (\n \n ) : (\n \n )\n )}\n {isAuthReady && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'gotToAuthQrCode',\n ]),\n)(AuthPhoneNumber));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthCodeAsync: FC = () => {\n const AuthCode = useModuleLoader(Bundles.Auth, 'AuthCode');\n\n return AuthCode ? : ;\n};\n\nexport default memo(AuthCodeAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthPasswordAsync: FC = () => {\n const AuthPassword = useModuleLoader(Bundles.Auth, 'AuthPassword');\n\n return AuthPassword ? : ;\n};\n\nexport default memo(AuthPasswordAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? : ;\n};\n\nexport default memo(AuthRegisterAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthQrCodeAsync: FC = () => {\n const AuthQrCode = useModuleLoader(Bundles.Auth, 'AuthQrCode');\n\n return AuthQrCode ? : ;\n};\n\nexport default memo(AuthQrCodeAsync);\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\n\nimport UiLoader from '../common/UiLoader';\nimport AuthPhoneNumber from './AuthPhoneNumber';\nimport AuthCode from './AuthCode.async';\nimport AuthPassword from './AuthPassword.async';\nimport AuthRegister from './AuthRegister.async';\nimport AuthQrCode from './AuthQrCode.async';\n\nimport './Auth.scss';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst Auth: FC = ({ authState, reset, initApi }) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n useEffect(() => {\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return ;\n case 'authorizationStateWaitPassword':\n return ;\n case 'authorizationStateWaitRegistration':\n return ;\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateWaitPhoneNumber':\n default:\n return ;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi']),\n)(Auth));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MainAsync: FC = () => {\n const Main = useModuleLoader(Bundles.Main, 'Main');\n\n return Main ?
: undefined;\n};\n\nexport default memo(MainAsync);\n","export default __webpack_public_path__ + \"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png\";","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n
\n
\n \"\"\n

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport {\n LEGACY_SESSION_KEY, INACTIVE_MARKER, SESSION_USER_KEY, PAGE_TITLE,\n} from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n\n return hasSession ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/config.ts","webpack:///./src/lib/teact/teactn.tsx","webpack:///./src/util/iteratees.ts","webpack:///./src/modules/helpers/messages.ts","webpack:///./src/modules/helpers/messageMedia.ts","webpack:///./src/modules/helpers/localSearch.ts","webpack:///./src/api/types/index.ts","webpack:///./src/modules/selectors/users.ts","webpack:///./src/modules/selectors/settings.ts","webpack:///./src/modules/selectors/chats.ts","webpack:///./src/modules/selectors/symbols.ts","webpack:///./src/modules/selectors/messages.ts","webpack:///./src/modules/selectors/localSearch.ts","webpack:///./src/modules/selectors/management.ts","webpack:///./src/modules/selectors/ui.ts","webpack:///./src/modules/selectors/globalSearch.ts","webpack:///./src/modules/selectors/payments.ts","webpack:///./src/util/environment.ts","webpack:///./src/util/buildClassName.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/util/files.ts","webpack:///./src/assets/lang/en-extra.json","webpack:///./src/assets/lang/es-extra.json","webpack:///./src/assets/lang/it-extra.json","webpack:///./src/assets/lang/pl-extra.json","webpack:///./src/assets/lang/ru-extra.json","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/types/index.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/modules/actions/api/sessions.ts","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/util/arePropsShallowEqual.ts","webpack:///./src/hooks/useLang.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/util/generateIdFor.ts","webpack:///./src/util/notifications.ts","webpack:///./src/modules/helpers/users.ts","webpack:///./src/modules/helpers/chats.ts","webpack:///./src/components/ui/Button.tsx","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/modules/reducers/chats.ts","webpack:///./src/modules/reducers/messages.ts","webpack:///./src/modules/reducers/symbols.ts","webpack:///./src/modules/reducers/users.ts","webpack:///./src/modules/reducers/globalSearch.ts","webpack:///./src/modules/reducers/localSearch.ts","webpack:///./src/modules/reducers/management.ts","webpack:///./src/modules/reducers/settings.ts","webpack:///./src/modules/reducers/twoFaSettings.ts","webpack:///./src/modules/reducers/payments.ts","webpack:///./src/hooks/usePrevious.ts","webpack:///./src/util/history.ts","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/util/trimText.ts","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/components/ui/MenuItem.tsx","webpack:///./src/components/ui/RippleEffect.tsx","webpack:///./src/util/webpToPng.ts","webpack:///./src/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/hooks/useEffectWithPrevDeps.ts","webpack:///./src/components/common/helpers/documentInfo.ts","webpack:///./src/modules/helpers/payments.ts","webpack:///./src/util/animation.ts","webpack:///./src/components/ui/DropdownMenu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.ts","webpack:///./src/util/emoji.ts","webpack:///./src/lib/teact/teact-dom.ts","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/components/middle/message/MentionLink.tsx","webpack:///./src/util/switchTheme.ts","webpack:///./src/util/appBadge.ts","webpack:///./src/hooks/useVirtualBackdrop.ts","webpack:///./src/api/gramjs/worker/worker.ts","webpack:///./node_modules/opus-recorder/dist/decoderWorker.min.js","webpack:///./node_modules/opus-recorder/dist/waveWorker.min.js","webpack:///./src/lib/webp/webp_wasm.worker.js","webpack:///./src/modules/actions/ui/initial.ts","webpack:///./src/modules/actions/api/initial.ts","webpack:///./node_modules/process/browser.js","webpack:///./src/modules/actions/apiUpdaters/initial.ts","webpack:///./src/serviceWorker.ts","webpack:///./src/util/setupServiceWorker.ts","webpack:///./src/global/initial.ts","webpack:///./src/global/cache.ts","webpack:///./src/global/index.ts","webpack:///./src/util/activeTabMonitor.ts","webpack:///./src/util/fonts.ts","webpack:///./src/assets/telegram-logo.svg","webpack:///./src/assets/monkey.svg","webpack:///./src/components/common/UiLoader.tsx","webpack:///./src/components/auth/CountryCodeInput.tsx","webpack:///./src/components/auth/AuthPhoneNumber.tsx","webpack:///./src/components/auth/AuthCode.async.tsx","webpack:///./src/components/auth/AuthPassword.async.tsx","webpack:///./src/components/auth/AuthRegister.async.tsx","webpack:///./src/components/auth/AuthQrCode.async.tsx","webpack:///./src/components/auth/Auth.tsx","webpack:///./src/components/main/Main.async.tsx","webpack:///./src/assets/app-inactive.png","webpack:///./src/components/main/AppInactive.tsx","webpack:///./src/App.tsx","webpack:///./src/index.tsx"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","installedModules","installedCssChunks","2","__webpack_require__","exports","module","l","e","promises","Promise","resolve","reject","href","fullhref","p","existingLinkTags","document","getElementsByTagName","dataHref","tag","getAttribute","rel","existingStyleTags","linkTag","createElement","type","onload","onerror","event","request","target","src","err","Error","code","parentNode","removeChild","appendChild","then","installedChunkData","promise","onScriptComplete","script","charset","timeout","nc","setAttribute","jsonpScriptSrc","error","clearTimeout","chunk","errorType","realSrc","message","name","undefined","setTimeout","head","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","console","jsonpArray","window","oldJsonpFunction","slice","s","VirtualElementTypesEnum","Fragment","renderingInstance","isEmptyElement","$element","Empty","isTextElement","Text","isTagElement","Tag","isComponentElement","Component","isRealElement","source","props","children","flatten","parsedChildren","componentInstance","isMounted","hooks","state","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","map","buildChildElement","buildTagElement","isEmptyPlaceholder","child","String","DEBUG_components","renderComponent","newRenderedValue","DEBUG_startAt","DEBUG","componentName","renderCount","renderTimes","DEBUG_MORE","log","performance","now","renderTime","warn","Math","round","handleError","renderedValue","newChild","hasElementChanged","$old","$new","unmountTree","forEach","hook","current","cleanup","effect","dependencies","nextValue","setter","forceUpdate","onUpdate","helpGc","unmountComponent","removeAllDelegatedListeners","mountComponent","forceUpdateComponent","currentElement","getTarget","setTarget","useState","initial","newValue","prepareForFrame","throttleWithPrimaryRaf","prepareComponentForFrame","throttleWithRaf","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","exec","some","dependency","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","withDebug","propsRef","renderedRef","getUnequalProps","join","addEventListener","orderBy","values","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","APP_VERSION","process","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","isBigScreen","Set","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","STICKER_SIZE_INLINE_DESKTOP_FACTOR","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","MEMOJI_STICKER_ID","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_TEMPLATE","RE_TME_LINK","RE_TME_INVITE_LINK","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","LANG_PACKS","TIPS_USERNAME","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacks","cb","runCallbacksThrottled","newGlobal","noThrottle","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","TeactNContainer","id","generateIdFor","useForceUpdate","delete","set","buildCollectionByKey","collection","reduce","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","filter","has","orderKey","sort","a","b","Array","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","from","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","lang","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","groupedId","isGif","emoji","title","performer","fileName","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","entities","link","find","entity","ApiMessageEntityTypes","TextUrl","url","Url","offset","substring","domain","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","action","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","sender","getUserFullName","getChatTitle","getSendingState","sendingState","isHistoryClearMessage","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","base","hasMessageLocalBlobUrl","canMessagePlayVideoInline","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageMediaFilename","date","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","reverseOrder","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","selectUser","global","userId","users","byId","selectNotifySettings","settings","selectNotifyExceptions","notifyExceptions","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","user","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","fullInfo","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","includes","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","selectIsChatMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","cleanedEmoji","replace","selectEmojiKeywords","language","emojiKeywords","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","selectThreadOriginChat","threadInfo","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","currentMessageList","selectIsViewportNewest","viewportIds","lastMessageId","selectChatMessage","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","focusedMessage","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","fromChatId","senderUserId","selectAllowedMessageActions","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","getHasAdminRight","canPin","canUnpin","pinnedMessageIds","canDelete","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","Infinity","selectFirstUnreadId","outlyingIds","lastReadId","isNotJoined","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","isCommonBoxChat","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","fromMessageId","selectMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","isChatGroup","userOrChat","contactList","userIds","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","chatThreadKey","currentSearch","localTextSearch","byChatThreadKey","isActive","selectCurrentMediaSearchPeerId","localMediaSearch","currentProfileUserId","selectedId","selectCurrentMediaSearch","peerId","selectManagement","management","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_MOBILE_SCREEN","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","UserInfo","ChatInfo","selectIsRightColumnShown","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_TOUCH_ENV","matchMedia","matches","innerWidth","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","parts","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","args","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","waiting","onIdle","requestIdleCallback","pause","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","isPrimary","requestAnimationFrame","currentCallbacks","currentPrimaryCallbacks","worker","requestStates","requestStatesByCallback","initApi","sessionData","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","Bundles","LOAD_PROMISES","MEMORY_CACHE","async","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","cacheApi","caches","Type","fetch","cacheName","Request","cache","open","Blob","blob","substr","headers","Json","json","save","cacheData","JSON","stringify","Response","put","clear","File","constructor","fileBits","options","rest","super","this","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","canvas","videoWidth","videoHeight","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","EXTRA_PACK_PATHS","en","enExtraJson","es","esExtraJson","it","itExtraJson","pl","plExtraJson","ru","ruExtraJson","PLURAL_OPTIONS","PLURAL_RULES","ar","ca","de","fa","fr","ko","nl","pt_BR","tr","uk","uz","langPack","createCallbackManager","currentLangCode","getTranslation","format","cached","langString","template","amount","optionIndex","getPluralOption","trim","processTemplate","formatInteger","setLanguage","langCode","newLangPack","remote","sourceLangPacks","fetchFromCacheOrRemote","pairs","extraLangPack","languages","langInfo","isRtl","rtl","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","noLoad","autoUpdate","formatsCache","defaultPhoneNumberFormat","parsed","str","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","repeat","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","startsWith","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","Spinner","buildClassName","handleErrorEvent","startedAt","isReloading","preventDefault","ErrorEvent","reason","alert","localStorage","getItem","removeItem","location","reload","APP_ENV","DC_IDS","storeSession","mainDcId","hashes","setItem","dcID","dcId","clearStoredSession","loadStoredSession","legacySessionJson","parse","hash","importLegacySession","sessionId","sessionJson","idb","clearLegacySessions","idbKeys","k","importTestSession","env","TEST_SESSION","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","renderText","part","filters","params","textParts","divEl","innerText","innerHTML","escapeHtml","EMOJI_REGEX","lastIndex","replaceEmojis","addLineBreaks","highlight","lowerCaseText","queryPosition","nextSymbol","newParts","links","RE_MENTION","nextLink","endsWith","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","entityResult","currentProps","newProps","currentKeys","currentKeysLength","prop","useOnChange","langProvider","setTrigger","trigger","Link","onClick","handleClick","dir","store","random","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","requestPermission","unsubscribeFromPush","dispatch","deviceToken","unsubscribe","deleteDeviceToken","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","subscribe","replaceSettings","loadNotificationSettings","subscribedAt","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","showNewMessageNotification","isActiveChat","hasFocus","hasPrivateChatsNotifications","hasGroupNotifications","hasBroadcastNotifications","checkIfShouldNotify","body","messageSender","messageAction","actionTargetMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","actionTargetUser","privateChatUserId","privateChatUser","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","getNotificationContent","controller","icon","badge","toString","vibrate","notification","onclick","close","focusMessage","focus","notifyClientReady","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","getTime","floor","today","setHours","formatTime","yesterday","setDate","getDate","formatFullDate","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","getChatSlowModeOptions","slowMode","getChatOrder","max","joinDate","isChatArchived","notifySettings","isMuted","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","isChat","chatOrUser","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","Button","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","handleMouseDown","aria-label","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeEventListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","setValue","isOpen","onCloseTransitionEnd","noOpenTransition","noCloseTransition","isClosed","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","isClosing","shouldRender","transitionClassNames","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChats","updatedById","addChats","addedById","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","canDeleteCurrentThread","currentThreadId","originalPost","deleteChatScheduledMessages","scheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","updateScheduledMessages","updateFocusedMessage","noHighlight","updateFocusDirection","direction","enterMessageSelectMode","toggleMessageSelection","childMessageIds","withShift","oldSelectedMessages","newMessageIds","newSelectedMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateUser","userUpdate","contactUserIds","updatedUser","updateUsers","addUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","getComplexKey","updateGlobalSearch","searchStatePartial","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","newState","fetchingStatus","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","newSettings","replaceThemeSettings","theme","themes","addNotifyException","notifyException","updateNotifySettings","peerType","isSilent","shouldShowPreviews","hasPrivateChatsMessagePreview","hasGroupMessagePreview","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","usePrevious","next","shouldSkipUndefined","HistoryWrapper","states","isHistoryChangedByUser","pushState","history","back","prevDeps","trimText","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","createStore","customStore","del","eachCursor","openCursor","continue","items","MenuItem","destructive","useLang","handleKeyDown","keyCode","data-char","origin","role","onKeyDown","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","webpToPng","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","onmessage","handleLibWebpMessage","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","labelText","htmlFor","subLabel","checked","blocking","onCheck","handleChange","captureEscKeyListener","captureKeyboardListener","onEsc","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","shouldSkipTransition","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","getFromMemory","cancelProgress","mediaData","fullSize","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","IS_LANDSCAPE","isLandscape","windowSize","updateSizes","handleResize","vh","setProperty","utf16","len","RangeError","adapt","delta","numpoints","firsttime","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","ensureProtocol","getDomain","decodedHref","decodeURI","convertPunycode","toggleSafeLinkModal","openTelegramLink","isNotSafe","ctrlKey","altKey","shiftKey","metaKey","classNames","getFileSizeString","bytes","ONE_GIGABYTE","ONE_MEGABYTE","getDocumentExtension","getFileExtension","getColorFromExtension","extension","STRIPE_ERRORS","missing_payment_information","field","fieldError","invalid_number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","SHIPPING_ERRORS","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","getShippingError","errors","cur","currentInstance","animateSingle","tick","instance","isCancelled","animate","DropdownMenu","forceOpen","onOpen","dropdownRef","setIsOpen","menu","focusedElement","activeElement","elementChildren","onTrigger","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","querySelectorAll","newIndex","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","updateComponent","setupComponentUpdateListener","initComponent","node","createNode","childNodes","insertBefore","replaceChild","areComponents","nextSibling","newKeys","removeAttribute","addAttribute","oldValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","createDocumentFragment","renderChildren","$firstChild","createTextNode","$child","$fragmentChild","cssText","render","headId","$head","openUserInfo","handleMessageClick","openChat","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","renderChatContent","renderUserContent","renderOriginContent","showQuotes","messageText","renderMessageContent","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","MESSAGE_DELETED","openChatByUsername","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","transition","updateAppBadge","setAppBadge","contains","animationLevel","messageTextSize","switchTheme","uiReadyState","contentKey","authPhoneNumber","authRememberMe","authError","shouldSkipUiLoaderTransition","apiUpdate","authIsLoading","password","file","authIsLoadingQrCode","reset","langCachePrefix","langCacheVersion","init","connectionState","authNearestCountry","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","arguments","apply","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","binding","cwd","chdir","umask","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","saveSession","onUpdateSession","currentUser","sessionUserAuth","userAuth","updateSessionUserId","onUpdateCurrentUser","showError","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","activeChatFolder","recentEmojis","added","recent","featured","saved","topPeers","audioPlayer","notifications","activeSessions","messageSendKeyCombo","shouldSuggestStickers","light","isBlurred","patternColor","dark","privacy","updateCacheThrottled","isAllowed","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","loadCache","initialState","time","timeEnd","readCache","idsToSave","cid","chatIdsToSave","mainThread","replaceState","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","mediaLoader","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","setIsUiReady","setShouldSkipUiLoaderTransition","isReady","markReady","useFlag","shouldRenderMask","safePreload","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","data-country-id","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","gotToAuthQrCode","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","setSelectionRange","handlePhoneNumberChange","selectionStart","selectionEnd","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","AuthQrCode","AppInactive","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GAKAK,EAAI,EAAGC,EAAW,GACpCD,EAAIF,EAASI,OAAQF,IACzBH,EAAUC,EAASE,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBV,IAAYU,EAAgBV,IACpFI,EAASO,KAAKD,EAAgBV,GAAS,IAExCU,EAAgBV,GAAW,EAE5B,IAAID,KAAYG,EACZI,OAAOC,UAAUC,eAAe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AAS,CAAC,eAFzCyB,CAhD6B,EAAG2uD,YAAWuJ,iBACxD,MAAOC,EAAYC,GAAgBhE,aAAQ,GAc3C,GAZAj9D,YAAU,KACRgmD,cfTFt8C,EeU6B,KACzBq3D,IACAhrE,SAASgY,MAAS,GAAE3M,OAAaC,MAEjC4/D,MAED,CAACF,EAAYE,IAIZD,EACF,OAAO,kBAAC,GAAD,MAGT,GAAIxJ,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,kBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAOsJ,KAMb,OAFmBvpC,aAAaC,QAAQ71B,OAAqB41B,aAAaC,QAAQ51B,KAE9Dk/D,KAAe,kBAAC,GAAD,Q,OC7CjChkE,KAEF7C,QAAQkD,IAAI,YAGdgL,cAAc2sD,OAEVh4D,KAEF7C,QAAQkD,IAAI,4BAGd+jE,IAAS1Q,OACP,kBAAC,GAAD,MACAz6D,SAASqoE,eAAe,SAGtBthE,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAASkL,iBAAiB,WAAY,KAEpChH,QAAQkD,IAAI,eAAgB+K","file":"main.a06c93992fe858fca979.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t};\n\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded CSS chunks\n \tvar installedCssChunks = {\n \t\t2: 0\n \t}\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"7710475e3e81de39d2af\",\"1\":\"aad05fd8644c664595f3\",\"3\":\"49069e079072f537e8c6\",\"4\":\"d58ed6ebd279d8e97ea9\",\"5\":\"3ab589fa3f713177f16b\",\"6\":\"cbe2455ba67c892471e4\",\"7\":\"4122a010f2ae7876c212\",\"8\":\"a6fd4c4c763fc9d2ae68\",\"9\":\"6995fbf88b84d270550e\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// mini-css-extract-plugin CSS loading\n \t\tvar cssChunks = {\"0\":1,\"3\":1,\"4\":1,\"5\":1,\"6\":1};\n \t\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n \t\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n \t\t\tpromises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {\n \t\t\t\tvar href = \"\" + ({}[chunkId]||chunkId) + \".\" + {\"0\":\"7710475e3e81de39d2af\",\"1\":\"aad05fd8644c664595f3\",\"3\":\"49069e079072f537e8c6\",\"4\":\"d58ed6ebd279d8e97ea9\",\"5\":\"3ab589fa3f713177f16b\",\"6\":\"cbe2455ba67c892471e4\",\"7\":\"4122a010f2ae7876c212\",\"8\":\"a6fd4c4c763fc9d2ae68\",\"9\":\"6995fbf88b84d270550e\"}[chunkId] + \".css\";\n \t\t\t\tvar fullhref = __webpack_require__.p + href;\n \t\t\t\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n \t\t\t\tfor(var i = 0; i < existingLinkTags.length; i++) {\n \t\t\t\t\tvar tag = existingLinkTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n \t\t\t\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return resolve();\n \t\t\t\t}\n \t\t\t\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n \t\t\t\tfor(var i = 0; i < existingStyleTags.length; i++) {\n \t\t\t\t\tvar tag = existingStyleTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\");\n \t\t\t\t\tif(dataHref === href || dataHref === fullhref) return resolve();\n \t\t\t\t}\n \t\t\t\tvar linkTag = document.createElement(\"link\");\n \t\t\t\tlinkTag.rel = \"stylesheet\";\n \t\t\t\tlinkTag.type = \"text/css\";\n \t\t\t\tlinkTag.onload = resolve;\n \t\t\t\tlinkTag.onerror = function(event) {\n \t\t\t\t\tvar request = event && event.target && event.target.src || fullhref;\n \t\t\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + request + \")\");\n \t\t\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n \t\t\t\t\terr.request = request;\n \t\t\t\t\tdelete installedCssChunks[chunkId]\n \t\t\t\t\tlinkTag.parentNode.removeChild(linkTag)\n \t\t\t\t\treject(err);\n \t\t\t\t};\n \t\t\t\tlinkTag.href = fullhref;\n\n \t\t\t\tvar head = document.getElementsByTagName(\"head\")[0];\n \t\t\t\thead.appendChild(linkTag);\n \t\t\t}).then(function() {\n \t\t\t\tinstalledCssChunks[chunkId] = 0;\n \t\t\t}));\n \t\t}\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\n \t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n \t\t\t// a Promise means \"currently loading\".\n \t\t\tif(installedChunkData) {\n \t\t\t\tpromises.push(installedChunkData[2]);\n \t\t\t} else {\n \t\t\t\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 103);\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, onTickEnd, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\nexport type FC_withDebug = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We force cleaning as many objects as possible. Not sure this is needed at all.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[Teact.useState]',\n componentInstance.name,\n // `componentInstance.Component` may be set to `null` by GC helper\n componentInstance.Component && (componentInstance.Component as FC_withDebug).DEBUG_contentComponentName\n ? `> ${(componentInstance.Component as FC_withDebug).DEBUG_contentComponentName}`\n : '',\n `Forced update at cursor #${cursor}, next value: `,\n byCursor[cursor].nextValue,\n );\n }\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[]): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual, withDebug = false) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && withDebug) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name}: Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\n// noThrottle = true is used as a workaround for iOS gesture history navigation\nexport function setGlobal(newGlobal?: GlobalState, noThrottle = false) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (!noThrottle) {\n runCallbacksThrottled();\n } else {\n runCallbacks();\n }\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload, noThrottle?: boolean) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, noThrottle);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload, noThrottle = false) => {\n onDispatch(name, payload, noThrottle);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${text ? text.text : lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji} ${lang('AttachSticker')} `;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n return `${noEmoji ? '' : '🎧 '}${caption || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${text ? text.text : lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && video.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(lang, sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video && video.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): IDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record, messageIds: number[], contentType: ApiMessageSearchType,\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n default:\n return [] as Array;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video;\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: number): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: number) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: number, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: number): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && !selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\nimport { LangCode, EmojiKeywords } from '../../types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectEmojiKeywords(global: GlobalState, language: LangCode): EmojiKeywords | undefined {\n return global.emojiKeywords[language] && global.emojiKeywords[language] !== undefined\n ? global.emojiKeywords[language] as EmojiKeywords\n : undefined;\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists && messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: number,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: number, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: number) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return senderId > 0 ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const isMessageEditable = (\n (isChatWithSelf || Date.now() - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId || Infinity);\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: number, threadId: number) {\n const chat = selectChat(global, chatId);\n\n if (threadId === MAIN_THREAD_ID) {\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n if (!lastReadId && chat && chat.isNotJoined) {\n return undefined;\n }\n\n if (outlyingIds) {\n const found = !lastReadId ? outlyingIds[0] : outlyingIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = !lastReadId ? listedIds[0] : listedIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(chatId));\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n }));\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: number, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: number,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n} from '../config';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'Mac OS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n));\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nlet isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiOnProgress, ApiSessionData, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nlet worker: Worker;\nconst requestStates = new Map();\nconst requestStatesByCallback = new Map();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [sessionData],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\nimport { getGlobal } from '../lib/teact/teactn';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n}\n\nconst EXTRA_PACK_PATHS: Record = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map();\n\nlet langPack: ApiLangPack;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n};\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages } = getGlobal().settings.byKey;\n const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined;\n getTranslation.isRtl = Boolean(langInfo && langInfo.rtl);\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 2c193ce 28.05.2021\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f|\\u2764\\ufe0f\\u200d\\ud83d\\udd25|\\u2764\\ufe0f\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n

\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\n","import {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport type ThemeKey = 'light' | 'dark';\nexport interface IThemeSettings {\n background?: string;\n backgroundColor?: string;\n patternColor?: string;\n isBlurred?: boolean;\n}\n\nexport type NotifySettings = {\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n};\n\nexport type LangCode = (\n 'en' | 'ar' | 'be' | 'ca' | 'nl' | 'fr' | 'de' | 'id' | 'it' | 'ko' | 'ms' | 'fa' | 'pl' | 'pt-br' | 'ru' | 'es'\n | 'tr' | 'uk' | 'uz'\n);\n\nexport interface ISettings extends NotifySettings, Record {\n theme: ThemeKey;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersIncludedChats,\n FoldersExcludedChats,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record;\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","import { DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY } from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache and refresh the page\n if (Date.now() - startedAt <= STARTUP_TIMEOUT && localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","import * as idb from 'idb-keyval';\n\nimport { ApiSessionData } from '../../../api/types';\n\nimport { DEBUG, LEGACY_SESSION_KEY, SESSION_USER_KEY } from '../../../config';\nimport * as cacheApi from '../../../util/cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: number) {\n const { mainDcId, keys, hashes } = sessionData;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify({ dcID: mainDcId, id: currentUserId }));\n localStorage.setItem('dc', String(mainDcId));\n Object.keys(keys).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_auth_key`, JSON.stringify(keys[dcId]));\n });\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\n}\n\nexport function clearStoredSession() {\n [\n SESSION_USER_KEY,\n 'dc',\n ...DC_IDS.map((dcId) => `dc${dcId}_auth_key`),\n ...DC_IDS.map((dcId) => `dc${dcId}_hash`),\n ].forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n\nexport function loadStoredSession(): ApiSessionData | undefined {\n const legacySessionJson = localStorage.getItem(SESSION_USER_KEY);\n if (!legacySessionJson) return undefined;\n\n const { dcID: mainDcId } = JSON.parse(legacySessionJson);\n const keys: Record = {};\n const hashes: Record = {};\n\n DC_IDS.forEach((dcId) => {\n try {\n const key = localStorage.getItem(`dc${dcId}_auth_key`);\n if (key) {\n keys[dcId] = JSON.parse(key);\n }\n\n const hash = localStorage.getItem(`dc${dcId}_hash`);\n if (hash) {\n hashes[dcId] = JSON.parse(hash);\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load stored session', err);\n }\n // Do nothing.\n }\n });\n\n if (!Object.keys(keys).length) return undefined;\n\n return {\n mainDcId,\n keys,\n hashes,\n };\n}\n\nexport async function importLegacySession() {\n const sessionId = localStorage.getItem(LEGACY_SESSION_KEY);\n if (!sessionId) return;\n\n const sessionJson = await idb.get(`GramJs:${sessionId}`);\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load legacy session', err);\n }\n // Do nothing.\n }\n}\n\n// Remove previously created IndexedDB and cache API sessions\nexport async function clearLegacySessions() {\n localStorage.removeItem(LEGACY_SESSION_KEY);\n\n const idbKeys = await idb.keys();\n\n await Promise.all>([\n cacheApi.clear('GramJs'),\n ...idbKeys\n .filter((k) => typeof k === 'string' && k.startsWith('GramJs:GramJs-session-'))\n .map((k) => idb.del(k)),\n ]);\n}\n\nexport function importTestSession() {\n const sessionJson = process.env.TEST_SESSION!;\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load test session', err);\n }\n // Do nothing.\n }\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? {emoji}\n : (\n \n ),\n );\n }\n if (type === 'html') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? emoji\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n : `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/ig;\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = [...(part.match(RE_LINK) || []), ...(part.match(RE_MENTION) || [])];\n if (!links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n if (currentProps === newProps) {\n return true;\n }\n\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n if (currentKeysLength === 0) {\n return true;\n }\n\n for (let i = 0; i < currentKeysLength; i++) {\n const prop = currentKeys[i];\n if (currentProps[prop] !== newProps[prop]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['%LENGTH%'];\n }\n\n return currentKeys.filter((prop) => currentProps[prop] !== newProps[prop]);\n}\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { callApi } from '../api/gramjs';\nimport { ApiChat, ApiMessage } from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({\n endpoint: data.endpoint,\n keys: data.keys,\n });\n}\n\nfunction checkIfPushSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nfunction checkIfNotificationsSupported() {\n // Let's check if the browser supports notifications\n if (!('Notification' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] This browser does not support desktop notification');\n }\n return false;\n }\n\n if (Notification.permission === 'denied' as NotificationPermission) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\n\nexport async function unsubscribe() {\n if (!checkIfPushSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribeFromPush(subscription);\n}\n\n// Load notification settings from the api\nasync function loadNotificationSettings() {\n const [result] = await Promise.all([\n callApi('fetchNotificationSettings'),\n callApi('fetchNotificationExceptions'),\n ]);\n\n if (!result) return;\n setGlobal(replaceSettings(getGlobal(), result));\n}\n\nexport async function subscribe() {\n loadNotificationSettings();\n\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat, isActive: boolean) {\n const global = getGlobal();\n\n if (selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global)) || chat.isNotJoined) {\n return false;\n }\n\n // Dont show notification for active chat if client has focus\n if (isActive && document.hasFocus()) return false;\n\n switch (chat.type) {\n case 'chatTypePrivate':\n case 'chatTypeSecret':\n return Boolean(global.settings.byKey.hasPrivateChatsNotifications);\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return Boolean(global.settings.byKey.hasGroupNotifications);\n case 'chatTypeChannel':\n return Boolean(global.settings.byKey.hasBroadcastNotifications);\n }\n return false;\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserId: actionTargetUserId,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n const actionTargetUser = actionTargetUserId ? selectUser(global, actionTargetUserId) : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n let body: string;\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nexport function showNewMessageNotification({\n chat,\n message,\n isActiveChat,\n}: { chat: ApiChat; message: Partial; isActiveChat: boolean}) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n if (!checkIfShouldNotify(chat, isActiveChat)) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon: 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag: message.id.toString(),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date();\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > today) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record,\n priorityIds?: number[],\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { LangFn } from '../../hooks/useLang';\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(lang: LangFn, chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return lang('SavedMessages');\n }\n return chat.title || lang('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && chat.defaultBannedRights[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isChatPrivate(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(chat.joinDate || 0, chat.lastMessage ? chat.lastMessage.date : 0);\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions?: Record,\n) {\n return !(notifyExceptions && notifyExceptions[chat.id] && !notifyExceptions[chat.id].isMuted) && (\n chat.isMuted\n || (isChatPrivate(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return lang('FromYou');\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: number[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent) => {\n e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {isLoading ? (\n
\n Please wait..\n \n
\n ) : children}\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement) {\n return (\n !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n ((hasOpenClassName && !noCloseTransition) || (noCloseTransition && isOpen)) && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(lang: LangFn, datetime: number | Date, isShort = false, noWeekdays = false) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n return isShort\n ? lowerFirst(lang(`Weekday.Short${weekDay}`))\n : upperFirst(lang(`Weekday.${weekDay}`));\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = lang(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date) {\n return date.toLocaleString(\n 'en-US',\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && listIds.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: number[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record;\n threadsById: Record;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, update: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam(\n global: GlobalState, chatId: number, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record>);\n\n Object.keys(addedByChatId).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, newById: Record,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && currentMessageList.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && listedIds.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && outlyingIds.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, threadId: number, update: Partial | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: number, updates: Partial[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: number, newById: Record, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record; hash: number }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: number,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: number,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results && results.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: number,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: number,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function replaceThemeSettings(\n global: GlobalState, theme: ThemeKey, newSettings?: Partial,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n themes: {\n ...global.settings.themes,\n [theme]: {\n ...(global.settings.themes[theme] || {}),\n ...newSettings,\n },\n },\n },\n };\n}\n\nexport function addNotifyException(\n global: GlobalState, id: number, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious(next: T): T | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined: true): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","\nexport const HistoryWrapper: {\n pushState(data: any): void;\n back(): void;\n states: any[];\n isHistoryChangedByUser: boolean;\n} = {\n states: [],\n isHistoryChangedByUser: true,\n pushState(data: any) {\n this.states.push(data);\n\n window.history.pushState(data, '');\n },\n back() {\n this.isHistoryChangedByUser = false;\n window.history.back();\n this.states.pop();\n },\n};\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }: Ripple) => (\n \n ))}\n
\n );\n};\n\nexport default memo(RippleEffect);\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, url: string): Promise {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise {\n return new Promise((resolve) => {\n worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n}) => {\n const lang = useLang();\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n
\n \n {labelText && (\n \n )}\n
\n );\n};\n\nexport default memo(InputText);\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","const RE_NOT_LETTER = /[^\\wа-яё]+/;\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n shouldSkipTransition,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const {\n transitionClassNames,\n } = useShowTransition(\n isOpen,\n onCloseAnimationEnd,\n shouldSkipTransition,\n undefined,\n shouldSkipTransition,\n );\n\n useEffect(\n () => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n
\n );\n};\n\nexport default Menu;\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\n\nexport function fetch(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!);\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\n }\n\n if (progress === 1) {\n mediaSource.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer.appendBuffer(arrayBuffer!);\n });\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = blob.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onLeft' | 'onRight'\n| 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial>;\n\nconst keyToHandlerName: Record = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n ArrowLeft: 'onLeft',\n ArrowRight: 'onRight',\n Tab: 'onTab',\n};\n\nconst handlers: Record = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onLeft: [],\n onRight: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","import { throttle } from './schedulers';\nimport {\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../config';\nimport { IS_IOS, IS_MOBILE_SCREEN } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_MOBILE_SCREEN && isLandscape();\n\nlet windowSize = updateSizes();\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if ((isMobileScreen() !== IS_MOBILE_SCREEN) || (IS_MOBILE_SCREEN && IS_LANDSCAPE !== isLandscape())) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n};\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n toggleSafeLinkModal,\n openTelegramLink,\n}) => {\n const content = children || text;\n const isNotSafe = url !== content;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TME_INVITE_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {content}\n \n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSafeLinkModal', 'openTelegramLink',\n ]),\n)(SafeLink));\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","const STRIPE_ERRORS: Record> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingError(errors: Record) {\n return Object.values(errors).reduce((acc, cur) => {\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n forceOpen?: boolean;\n onOpen?: NoneToVoidFunction;\n onClose?: NoneToVoidFunction;\n children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n forceOpen,\n onOpen,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n if (isOpen) {\n if (onClose) onClose();\n } else if (onOpen) onOpen();\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n if (onClose) onClose();\n };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n
\n );\n};\n\nexport default DropdownMenu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array;\n emojis: Record;\n};\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function nativeToUnfified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1][0])) {\n category.emojis.push(emojiRaw[1][0]);\n emojiData.emojis[emojiRaw[1][0]] = {\n id: emojiRaw[1][0],\n names: emojiRaw[1] as string[],\n native: unifiedToNative(emojiRaw[0] as string),\n image: (emojiRaw[0] as string).toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUser\n ? renderUserContent(targetUser, options.asPlain)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = `«${text}»`;\n }\n\n if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(lang, origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\n","import { DEBUG } from '../config';\n\nexport function updateAppBadge(unreadCount: number) {\n if (typeof window.navigator.setAppBadge !== 'function') {\n return;\n }\n\n window.navigator.setAppBadge(unreadCount).catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"3d0807b05cc1ab7d3c59.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { HistoryWrapper } from '../../../util/history';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel > 0);\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\n }\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n HistoryWrapper.pushState({\n type: 'login',\n contentKey: 'authCode',\n });\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('setShouldSkipUiLoaderTransition', (global, actions, payload) => {\n const { shouldSkipUiLoaderTransition } = payload;\n\n return {\n ...global,\n shouldSkipUiLoaderTransition,\n };\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { HistoryWrapper } from '../../../util/history';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n storeSession,\n loadStoredSession,\n clearStoredSession,\n importLegacySession,\n clearLegacySessions,\n importTestSession,\n} from './sessions';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n } else {\n importTestSession();\n }\n\n void initApi(actions.apiUpdate, loadStoredSession());\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('gotToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n HistoryWrapper.pushState({\n type: 'login',\n contentKey: 'authQr',\n });\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n storeSession(payload.sessionData, global.currentUserId);\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribe();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser,\n} from '../../../api/types';\nimport { DEBUG, SESSION_USER_KEY } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateSession':\n onUpdateSession(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n subscribe();\n setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n if (!getGlobal().authRememberMe) {\n return;\n }\n\n const { sessionData } = update;\n\n getDispatch().saveSession({ sessionData });\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n\n updateSessionUserId(currentUser.id);\n}\n\nfunction updateSessionUserId(currentUserId: number) {\n const sessionUserAuth = localStorage.getItem(SESSION_USER_KEY);\n if (!sessionUserAuth) return;\n\n const userAuth = JSON.parse(sessionUserAuth);\n userAuth.id = currentUserId;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify(userAuth));\n}\n","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n subscribeToWorker();\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n window.addEventListener('focus', async () => {\n await navigator.serviceWorker.ready;\n subscribeToWorker();\n });\n}\n","import { GlobalState } from './types';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n} from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n activeChatFolder: 0,\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n LEGACY_SESSION_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT, SESSION_USER_KEY,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n if (hasSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\n}\n\nfunction readCache(initialState: GlobalState) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n // Pre-fill defaults in nested objects which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'emojiKeywords',\n 'push',\n ]),\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey, themes } = global.settings;\n\n return {\n byKey,\n themes,\n privacy: {},\n notifyExceptions: {},\n };\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useOnChange from '../../hooks/useOnChange';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\nconst TRANSITION_TIME = 400;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipUiLoaderTransition,\n setIsUiReady,\n setShouldSkipUiLoaderTransition,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useOnChange(() => {\n if (shouldSkipUiLoaderTransition) {\n setTimeout(() => {\n setShouldSkipUiLoaderTransition({ shouldSkipUiLoaderTransition: false });\n }, TRANSITION_TIME);\n }\n }, [shouldSkipUiLoaderTransition]);\n\n return (\n
\n {children}\n {shouldRenderMask && !shouldSkipUiLoaderTransition && (\n
\n {page === 'main' ? (\n <>\n
\n \n {isRightColumnShown &&
}\n \n ) : (\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n shouldSkipUiLoaderTransition: global.shouldSkipUiLoaderTransition,\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady', 'setShouldSkipUiLoaderTransition']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC = ({\n id,\n value,\n isLoading,\n onChange,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [filter, setFilter] = useState();\n const [filteredList, setFilteredList] = useState(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, []);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList.map((country: Country) => (\n \n \n {renderText(country.flag, ['hq_emoji'])}\n {country.name}\n {country.code}\n \n ))}\n {!filteredList.length && (\n \n No countries matched your filter.\n \n )}\n \n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [country, setCountry] = useState();\n const [phoneNumber, setPhoneNumber] = useState();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n\n const fullNumber = country ? `${country.code} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n parseFullNumber(value);\n }, [authError, clearAuthError, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n
\n
\n
\n

Sign in to Telegram

\n

\n Please confirm your country and\n
enter your phone number.\n

\n
\n \n \n \n {canSubmit && (\n isAuthReady ? (\n \n ) : (\n \n )\n )}\n {isAuthReady && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'gotToAuthQrCode',\n ]),\n)(AuthPhoneNumber));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthCodeAsync: FC = () => {\n const AuthCode = useModuleLoader(Bundles.Auth, 'AuthCode');\n\n return AuthCode ? : ;\n};\n\nexport default memo(AuthCodeAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthPasswordAsync: FC = () => {\n const AuthPassword = useModuleLoader(Bundles.Auth, 'AuthPassword');\n\n return AuthPassword ? : ;\n};\n\nexport default memo(AuthPasswordAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? : ;\n};\n\nexport default memo(AuthRegisterAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthQrCodeAsync: FC = () => {\n const AuthQrCode = useModuleLoader(Bundles.Auth, 'AuthQrCode');\n\n return AuthQrCode ? : ;\n};\n\nexport default memo(AuthQrCodeAsync);\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\n\nimport UiLoader from '../common/UiLoader';\nimport AuthPhoneNumber from './AuthPhoneNumber';\nimport AuthCode from './AuthCode.async';\nimport AuthPassword from './AuthPassword.async';\nimport AuthRegister from './AuthRegister.async';\nimport AuthQrCode from './AuthQrCode.async';\n\nimport './Auth.scss';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst Auth: FC = ({ authState, reset, initApi }) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n useEffect(() => {\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return ;\n case 'authorizationStateWaitPassword':\n return ;\n case 'authorizationStateWaitRegistration':\n return ;\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateWaitPhoneNumber':\n default:\n return ;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi']),\n)(Auth));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MainAsync: FC = () => {\n const Main = useModuleLoader(Bundles.Main, 'Main');\n\n return Main ?
: undefined;\n};\n\nexport default memo(MainAsync);\n","export default __webpack_public_path__ + \"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png\";","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n
\n
\n \"\"\n

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport {\n LEGACY_SESSION_KEY, INACTIVE_MARKER, SESSION_USER_KEY, PAGE_TITLE,\n} from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n\n return hasSession ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/report.html b/dist/report.html index 3642580c..d1b8b3ce 100644 --- a/dist/report.html +++ b/dist/report.html @@ -3,7 +3,7 @@ - telegram-t [13 Jun 2021 at 19:59] + telegram-t [14 Jun 2021 at 00:40]