@mtcute/core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -260,7 +260,7 @@ export declare class BaseTelegramClient extends EventEmitter {
260
260
  /**
261
261
  * Adds all peers from a given object to entity cache in storage.
262
262
  */
263
- _cachePeersFrom(obj: object): Promise<void>;
263
+ _cachePeersFrom(obj: object): Promise<boolean>;
264
264
  /**
265
265
  * Export current session to a single *LONG* string, containing
266
266
  * all the needed information.
@@ -169,7 +169,9 @@ class BaseTelegramClient extends events_1.default {
169
169
  }
170
170
  const stack = this._niceStacks ? new Error().stack : undefined;
171
171
  const res = await this.network.call(message, params, stack);
172
- await this._cachePeersFrom(res);
172
+ if (await this._cachePeersFrom(res)) {
173
+ await this.saveStorage();
174
+ }
173
175
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
174
176
  return res;
175
177
  }
@@ -265,7 +267,9 @@ class BaseTelegramClient extends events_1.default {
265
267
  if (count > 0) {
266
268
  await this.storage.updatePeers(parsedPeers);
267
269
  this.log.debug('cached %d peers', count);
270
+ return true;
268
271
  }
272
+ return false;
269
273
  }
270
274
  /**
271
275
  * Export current session to a single *LONG* string, containing
@@ -1 +1 @@
1
- {"version":3,"file":"base-client.js","sourceRoot":"","sources":["../../src/base-client.ts"],"names":[],"mappings":";;;;;;AAAA,uDAAuD;AACvD,oDAAiC;AACjC,gDAAuB;AAEvB,mCAA+B;AAC/B,2DAA+E;AAC/E,2DAA+E;AAG/E,mEAA2D;AAE3D,qEAAwG;AAIxG,+CAeyB;AAwKzB;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,gBAAY;IAwDhD,YAAY,IAA+B;QACvC,KAAK,EAAE,CAAA;QAjBX,uDAAuD;QAC7C,oBAAe,GAAG,CAAC,CAAA;QAEpB,YAAO,GAAG,IAAI,iCAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,gBA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,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACpE,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;QAE1D,OAAO,IAAA,6BAAkB,EAAC,IAAI,CAAC,UAAU,EAAE;YACvC,OAAO,EAAE,CAAC;YACV,IAAI,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YAClC,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,UAAU;YACV,OAAO;SACV,CAAC,CAAA;IACN,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,OAAe,EAAE,KAAK,GAAG,KAAK;QACxC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAA;QAC1B,IAAI,CAAC,YAAY,GAAG,KAAK,CAAA;IAC7B,CAAC;CACJ;AApZD,gDAoZC","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport EventEmitter from 'events'\nimport Long from 'long'\n\nimport { tl } from '@mtcute/tl'\nimport { __tlReaderMap as defaultReaderMap } from '@mtcute/tl/binary/reader.js'\nimport { __tlWriterMap as defaultWriterMap } from '@mtcute/tl/binary/writer.js'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { ConfigManager } from './network/config-manager.js'\nimport { ReconnectionStrategy, SessionConnection, TransportFactory } from './network/index.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network/network-manager.js'\nimport { PersistentConnectionParams } from './network/persistent-connection.js'\nimport { ITelegramStorage } from './storage/index.js'\nimport { MustEqual } from './types/index.js'\nimport {\n ControllablePromise,\n createControllablePromise,\n CryptoProviderFactory,\n defaultCryptoProviderFactory,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n getAllPeersFrom,\n ICryptoProvider,\n LogManager,\n readStringSession,\n toggleChannelIdMark,\n writeStringSession,\n} from './utils/index.js'\n\n/** Options for {@link BaseTelegramClient} */\nexport interface BaseTelegramClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number | string\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: ITelegramStorage\n\n /**\n * Cryptography provider factory to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto?: CryptoProviderFactory\n\n /**\n * Whether to use IPv6 datacenters\n * (IPv6 will be preferred when choosing a DC by id)\n * (default: false)\n */\n useIpv6?: boolean\n\n /**\n * Primary DC to use for initial connection.\n * This does not mean this will be the only DC used,\n * nor that this DC will actually be primary, this only\n * determines the first DC the library will try to connect to.\n * Can be used to connect to other networks (like test DCs).\n *\n * When session already contains primary DC, this parameter is ignored.\n *\n * @default Production DC 2.\n */\n defaultDcs?: ITelegramStorage.DcOptions\n\n /**\n * Whether to connect to test servers.\n *\n * If passed, {@link defaultDc} defaults to Test DC 2.\n *\n * **Must** be passed if using test servers, even if\n * you passed custom {@link defaultDc}\n */\n testMode?: boolean\n\n /**\n * Additional options for initConnection call.\n * `apiId` and `query` are not available and will be ignored.\n * Omitted values will be filled with defaults\n */\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n\n /**\n * Transport factory to use in the client.\n *\n * @default platform-specific transport: WebSocket on the web, TCP in node\n */\n transport?: TransportFactory\n\n /**\n * Reconnection strategy.\n *\n * @default simple reconnection strategy: first 0ms, then up to 5s (increasing by 1s)\n */\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n\n /**\n * Maximum duration of a flood_wait that will be waited automatically.\n * Flood waits above this threshold will throw a FloodWaitError.\n * Set to 0 to disable. Can be overridden with `throwFlood` parameter in call() params\n *\n * @default 10000\n */\n floodSleepThreshold?: number\n\n /**\n * Maximum number of retries when calling RPC methods.\n * Call is retried when InternalError or FloodWaitError is encountered.\n * Can be set to Infinity.\n *\n * @default 5\n */\n maxRetryCount?: number\n\n /**\n * If true, every single API call will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * Note that this only wraps calls made with `.call()` within the primary\n * connection. Additional connections and direct `.sendForResult()` calls\n * must be wrapped manually.\n *\n * @default false\n */\n disableUpdates?: boolean\n\n /**\n * mtcute can send all unknown RPC errors to [danog](https://github.com/danog)'s\n * [error reporting service](https://rpc.pwrtelegram.xyz/).\n *\n * This is fully anonymous (except maybe IP) and is only used to improve the library\n * and developer experience for everyone working with MTProto. This is fully opt-in,\n * and if you're too paranoid, you can disable it by manually passing `enableErrorReporting: false` to the client.\n *\n * @default false\n */\n enableErrorReporting?: boolean\n\n /**\n * If true, RPC errors will have a stack trace of the initial `.call()`\n * or `.sendForResult()` call position, which drastically improves\n * debugging experience.<br>\n * If false, they will have a stack trace of mtcute internals.\n *\n * Internally this creates a stack capture before every RPC call\n * and stores it until the result is received. This might\n * use a lot more memory than normal, thus can be disabled here.\n *\n * @default true\n */\n niceStacks?: boolean\n\n /**\n * Extra parameters for {@link NetworkManager}\n */\n network?: NetworkManagerExtraParams\n\n /**\n * Set logging level for the client.\n *\n * See static members of {@link LogManager} for possible values.\n */\n logLevel?: number\n\n /**\n * **EXPERT USE ONLY!**\n *\n * Override TL layer used for the connection.\n *\n * **Does not** change the schema used.\n */\n overrideLayer?: number\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override reader map used for the connection.\n */\n readerMap?: TlReaderMap\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override writer map used for the connection.\n */\n writerMap?: TlWriterMap\n}\n\n/**\n * Basic Telegram client that only implements the bare minimum\n * to make RPC calls and receive low-level updates.\n */\nexport class BaseTelegramClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link BaseTelegramClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /**\n * Telegram storage taken from {@link BaseTelegramClientOptions.storage}\n */\n readonly storage: ITelegramStorage\n\n /**\n * API hash taken from {@link BaseTelegramClientOptions.apiHash}\n */\n protected readonly _apiHash: string\n\n /**\n * \"Use IPv6\" taken from {@link BaseTelegramClientOptions.useIpv6}\n */\n protected readonly _useIpv6: boolean\n\n /**\n * \"Test mode\" taken from {@link BaseTelegramClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link BaseTelegramClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n protected _defaultDcs: ITelegramStorage.DcOptions\n\n private _niceStacks: boolean\n /** TL layer used by the client */\n readonly _layer: number\n /** TL readers map used by the client */\n readonly _readerMap: TlReaderMap\n /** TL writers map used by the client */\n readonly _writerMap: TlWriterMap\n\n /** Unix timestamp when the last update was received */\n protected _lastUpdateTime = 0\n\n readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n // not really connected, but rather \"connect() was called\"\n private _connected: ControllablePromise<void> | boolean = false\n\n private _onError?: (err: unknown, connection?: SessionConnection) => void\n\n private _importFrom?: string\n private _importForce?: boolean\n\n readonly log = new LogManager('client')\n readonly network: NetworkManager\n\n constructor(opts: BaseTelegramClientOptions) {\n super()\n\n const apiId = typeof opts.apiId === 'string' ? parseInt(opts.apiId) : opts.apiId\n\n if (isNaN(apiId)) {\n throw new Error('apiId must be a number or a numeric string!')\n }\n\n if (opts.logLevel !== undefined) {\n this.log.level = opts.logLevel\n }\n\n this.crypto = (opts.crypto ?? defaultCryptoProviderFactory)()\n\n this.storage = opts.storage\n this._apiHash = opts.apiHash\n this._useIpv6 = Boolean(opts.useIpv6)\n this._testMode = Boolean(opts.testMode)\n\n let dc = opts.defaultDcs\n\n if (!dc) {\n if (this._testMode) {\n dc = this._useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = this._useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = opts.niceStacks ?? true\n\n this._layer = opts.overrideLayer ?? tl.LAYER\n this._readerMap = opts.readerMap ?? defaultReaderMap\n this._writerMap = opts.writerMap ?? defaultWriterMap\n\n this.network = new NetworkManager(\n {\n apiId,\n crypto: this.crypto,\n disableUpdates: opts.disableUpdates ?? false,\n initConnectionOptions: opts.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: opts.reconnectionStrategy,\n storage: this.storage,\n testMode: this._testMode,\n transport: opts.transport,\n _emitError: this._emitError.bind(this),\n floodSleepThreshold: opts.floodSleepThreshold ?? 10000,\n maxRetryCount: opts.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(opts.useIpv6),\n keepAliveAction: this._keepAliveAction.bind(this),\n enableErrorReporting: opts.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n ...(opts.network ?? {}),\n },\n this._config,\n )\n\n this.storage.setup?.(this.log, this._readerMap, this._writerMap)\n }\n\n protected _keepAliveAction(): void {\n this.emit('keep_alive')\n }\n\n protected async _loadStorage(): Promise<void> {\n await this.storage.load?.()\n }\n\n _beforeStorageSave: (() => Promise<void>)[] = []\n\n beforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave.push(cb)\n }\n\n offBeforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave = this._beforeStorageSave.filter((x) => x !== cb)\n }\n\n async saveStorage(): Promise<void> {\n for (const cb of this._beforeStorageSave) {\n await cb()\n }\n await this.storage.save?.()\n }\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n if (this._connected) {\n // avoid double-connect\n await this._connected\n\n return\n }\n\n const promise = (this._connected = createControllablePromise())\n\n await this.crypto.initialize?.()\n await this._loadStorage()\n const primaryDc = await this.storage.getDefaultDcs()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n\n const defaultDcAuthKey = await this.storage.getAuthKeyFor(this._defaultDcs.main.id)\n\n if ((this._importForce || !defaultDcAuthKey) && this._importFrom) {\n const data = readStringSession(this._readerMap, this._importFrom)\n\n if (data.testMode !== this._testMode) {\n throw new Error(\n 'This session string is not for the current backend. ' +\n `Session is ${data.testMode ? 'test' : 'prod'}, but the client is ${\n this._testMode ? 'test' : 'prod'\n }`,\n )\n }\n\n this._defaultDcs = data.primaryDcs\n await this.storage.setDefaultDcs(data.primaryDcs)\n\n if (data.self) {\n await this.storage.setSelf(data.self)\n }\n\n // await this.primaryConnection.setupKeys(data.authKey)\n await this.storage.setAuthKeyFor(data.primaryDcs.main.id, data.authKey)\n\n await this.saveStorage()\n }\n\n this.emit('before_connect')\n\n this.network\n .connect(this._defaultDcs)\n .then(() => {\n promise.resolve()\n this._connected = true\n })\n .catch((err: Error) => this._emitError(err))\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this.emit('before_close')\n\n this._config.destroy()\n this.network.destroy()\n\n await this.saveStorage()\n await this.storage.destroy?.()\n\n this.emit('closed')\n }\n\n /**\n * Make an RPC call to the primary DC.\n * This method handles DC migration, flood waits and retries automatically.\n *\n * If you want more low-level control, use\n * `primaryConnection.sendForResult()` (which is what this method wraps)\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n if (this._connected !== true) {\n await this.connect()\n }\n\n const stack = this._niceStacks ? new Error().stack : undefined\n\n const res = await this.network.call(message, params, stack)\n await this._cachePeersFrom(res)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n /**\n * Change transport for the client.\n *\n * Can be used, for example, to change proxy at runtime\n *\n * This effectively calls `changeTransport()` on\n * `primaryConnection` and all additional connections.\n *\n * @param factory New transport factory\n */\n changeTransport(factory: TransportFactory): void {\n this.network.changeTransport(factory)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler\n * Error handler. Called with one or two parameters.\n * The first one is always the error, and the second is\n * the connection in which the error has occurred, in case\n * this was connection-related error.\n */\n onError(handler: (err: unknown, connection?: SessionConnection) => void): void {\n this._onError = handler\n }\n\n notifyLoggedIn(auth: tl.auth.RawAuthorization): void {\n this.network.notifyLoggedIn(auth)\n this.emit('logged_in', auth)\n }\n\n _emitError(err: unknown, connection?: SessionConnection): void {\n if (this._onError) {\n this._onError(err, connection)\n } else {\n console.error(err)\n }\n }\n\n /**\n * Adds all peers from a given object to entity cache in storage.\n */\n async _cachePeersFrom(obj: object): Promise<void> {\n const parsedPeers: ITelegramStorage.PeerInfo[] = []\n\n let count = 0\n\n for (const peer of getAllPeersFrom(obj as tl.TlObject)) {\n if ((peer as any).min) {\n // no point in caching min peers as we can't use them\n continue\n }\n\n count += 1\n\n switch (peer._) {\n case 'user':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n\n parsedPeers.push({\n id: peer.id,\n accessHash: peer.accessHash,\n username: peer.username?.toLowerCase(),\n phone: peer.phone,\n type: 'user',\n full: peer,\n })\n break\n case 'chat':\n case 'chatForbidden':\n parsedPeers.push({\n id: -peer.id,\n accessHash: Long.ZERO,\n type: 'chat',\n full: peer,\n })\n break\n case 'channel':\n case 'channelForbidden':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n parsedPeers.push({\n id: toggleChannelIdMark(peer.id),\n accessHash: peer.accessHash,\n username: peer._ === 'channel' ? peer.username?.toLowerCase() : undefined,\n type: 'channel',\n full: peer,\n })\n break\n }\n }\n\n if (count > 0) {\n await this.storage.updatePeers(parsedPeers)\n this.log.debug('cached %d peers', count)\n }\n }\n\n /**\n * Export current session to a single *LONG* string, containing\n * all the needed information.\n *\n * > **Warning!** Anyone with this string will be able\n * > to authorize as you and do anything. Treat this\n * > as your password, and never give it away!\n * >\n * > In case you have accidentally leaked this string,\n * > make sure to revoke this session in account settings:\n * > \"Privacy & Security\" > \"Active sessions\" >\n * > find the one containing `mtcute` > Revoke,\n * > or, in case this is a bot, revoke bot token\n * > with [@BotFather](//t.me/botfather)\n */\n async exportSession(): Promise<string> {\n const primaryDcs = await this.storage.getDefaultDcs()\n if (!primaryDcs) throw new Error('No default DC set')\n\n const authKey = await this.storage.getAuthKeyFor(primaryDcs.main.id)\n if (!authKey) throw new Error('Auth key is not ready yet')\n\n return writeStringSession(this._writerMap, {\n version: 2,\n self: await this.storage.getSelf(),\n testMode: this._testMode,\n primaryDcs,\n authKey,\n })\n }\n\n /**\n * Request the session to be imported from the given session string.\n *\n * Note that the string will not be parsed and imported right away,\n * instead, it will be imported when `connect()` is called\n *\n * Also note that the session will only be imported in case\n * the storage is missing authorization (i.e. does not contain\n * auth key for the primary DC), otherwise it will be ignored (unless `force).\n *\n * @param session Session string to import\n * @param force Whether to overwrite existing session\n */\n importSession(session: string, force = false): void {\n this._importFrom = session\n this._importForce = force\n }\n}\n"]}
1
+ {"version":3,"file":"base-client.js","sourceRoot":"","sources":["../../src/base-client.ts"],"names":[],"mappings":";;;;;;AAAA,uDAAuD;AACvD,oDAAiC;AACjC,gDAAuB;AAEvB,mCAA+B;AAC/B,2DAA+E;AAC/E,2DAA+E;AAG/E,mEAA2D;AAE3D,qEAAwG;AAIxG,+CAeyB;AAwKzB;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,gBAAY;IAwDhD,YAAY,IAA+B;QACvC,KAAK,EAAE,CAAA;QAjBX,uDAAuD;QAC7C,oBAAe,GAAG,CAAC,CAAA;QAEpB,YAAO,GAAG,IAAI,iCAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAA;QAE9E,0DAA0D;QAClD,eAAU,GAAwC,KAAK,CAAA;QAOtD,QAAG,GAAG,IAAI,qBAAU,CAAC,QAAQ,CAAC,CAAA;QA8EvC,uBAAkB,GAA4B,EAAE,CAAA;QAxE5C,MAAM,KAAK,GAAG,OAAO,IAAI,CAAC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AC,CAAA;QAE1D,OAAO,IAAA,6BAAkB,EAAC,IAAI,CAAC,UAAU,EAAE;YACvC,OAAO,EAAE,CAAC;YACV,IAAI,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YAClC,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,UAAU;YACV,OAAO;SACV,CAAC,CAAA;IACN,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,OAAe,EAAE,KAAK,GAAG,KAAK;QACxC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAA;QAC1B,IAAI,CAAC,YAAY,GAAG,KAAK,CAAA;IAC7B,CAAC;CACJ;AA3ZD,gDA2ZC","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport EventEmitter from 'events'\nimport Long from 'long'\n\nimport { tl } from '@mtcute/tl'\nimport { __tlReaderMap as defaultReaderMap } from '@mtcute/tl/binary/reader.js'\nimport { __tlWriterMap as defaultWriterMap } from '@mtcute/tl/binary/writer.js'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { ConfigManager } from './network/config-manager.js'\nimport { ReconnectionStrategy, SessionConnection, TransportFactory } from './network/index.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network/network-manager.js'\nimport { PersistentConnectionParams } from './network/persistent-connection.js'\nimport { ITelegramStorage } from './storage/index.js'\nimport { MustEqual } from './types/index.js'\nimport {\n ControllablePromise,\n createControllablePromise,\n CryptoProviderFactory,\n defaultCryptoProviderFactory,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n getAllPeersFrom,\n ICryptoProvider,\n LogManager,\n readStringSession,\n toggleChannelIdMark,\n writeStringSession,\n} from './utils/index.js'\n\n/** Options for {@link BaseTelegramClient} */\nexport interface BaseTelegramClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number | string\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: ITelegramStorage\n\n /**\n * Cryptography provider factory to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto?: CryptoProviderFactory\n\n /**\n * Whether to use IPv6 datacenters\n * (IPv6 will be preferred when choosing a DC by id)\n * (default: false)\n */\n useIpv6?: boolean\n\n /**\n * Primary DC to use for initial connection.\n * This does not mean this will be the only DC used,\n * nor that this DC will actually be primary, this only\n * determines the first DC the library will try to connect to.\n * Can be used to connect to other networks (like test DCs).\n *\n * When session already contains primary DC, this parameter is ignored.\n *\n * @default Production DC 2.\n */\n defaultDcs?: ITelegramStorage.DcOptions\n\n /**\n * Whether to connect to test servers.\n *\n * If passed, {@link defaultDc} defaults to Test DC 2.\n *\n * **Must** be passed if using test servers, even if\n * you passed custom {@link defaultDc}\n */\n testMode?: boolean\n\n /**\n * Additional options for initConnection call.\n * `apiId` and `query` are not available and will be ignored.\n * Omitted values will be filled with defaults\n */\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n\n /**\n * Transport factory to use in the client.\n *\n * @default platform-specific transport: WebSocket on the web, TCP in node\n */\n transport?: TransportFactory\n\n /**\n * Reconnection strategy.\n *\n * @default simple reconnection strategy: first 0ms, then up to 5s (increasing by 1s)\n */\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n\n /**\n * Maximum duration of a flood_wait that will be waited automatically.\n * Flood waits above this threshold will throw a FloodWaitError.\n * Set to 0 to disable. Can be overridden with `throwFlood` parameter in call() params\n *\n * @default 10000\n */\n floodSleepThreshold?: number\n\n /**\n * Maximum number of retries when calling RPC methods.\n * Call is retried when InternalError or FloodWaitError is encountered.\n * Can be set to Infinity.\n *\n * @default 5\n */\n maxRetryCount?: number\n\n /**\n * If true, every single API call will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * Note that this only wraps calls made with `.call()` within the primary\n * connection. Additional connections and direct `.sendForResult()` calls\n * must be wrapped manually.\n *\n * @default false\n */\n disableUpdates?: boolean\n\n /**\n * mtcute can send all unknown RPC errors to [danog](https://github.com/danog)'s\n * [error reporting service](https://rpc.pwrtelegram.xyz/).\n *\n * This is fully anonymous (except maybe IP) and is only used to improve the library\n * and developer experience for everyone working with MTProto. This is fully opt-in,\n * and if you're too paranoid, you can disable it by manually passing `enableErrorReporting: false` to the client.\n *\n * @default false\n */\n enableErrorReporting?: boolean\n\n /**\n * If true, RPC errors will have a stack trace of the initial `.call()`\n * or `.sendForResult()` call position, which drastically improves\n * debugging experience.<br>\n * If false, they will have a stack trace of mtcute internals.\n *\n * Internally this creates a stack capture before every RPC call\n * and stores it until the result is received. This might\n * use a lot more memory than normal, thus can be disabled here.\n *\n * @default true\n */\n niceStacks?: boolean\n\n /**\n * Extra parameters for {@link NetworkManager}\n */\n network?: NetworkManagerExtraParams\n\n /**\n * Set logging level for the client.\n *\n * See static members of {@link LogManager} for possible values.\n */\n logLevel?: number\n\n /**\n * **EXPERT USE ONLY!**\n *\n * Override TL layer used for the connection.\n *\n * **Does not** change the schema used.\n */\n overrideLayer?: number\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override reader map used for the connection.\n */\n readerMap?: TlReaderMap\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override writer map used for the connection.\n */\n writerMap?: TlWriterMap\n}\n\n/**\n * Basic Telegram client that only implements the bare minimum\n * to make RPC calls and receive low-level updates.\n */\nexport class BaseTelegramClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link BaseTelegramClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /**\n * Telegram storage taken from {@link BaseTelegramClientOptions.storage}\n */\n readonly storage: ITelegramStorage\n\n /**\n * API hash taken from {@link BaseTelegramClientOptions.apiHash}\n */\n protected readonly _apiHash: string\n\n /**\n * \"Use IPv6\" taken from {@link BaseTelegramClientOptions.useIpv6}\n */\n protected readonly _useIpv6: boolean\n\n /**\n * \"Test mode\" taken from {@link BaseTelegramClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link BaseTelegramClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n protected _defaultDcs: ITelegramStorage.DcOptions\n\n private _niceStacks: boolean\n /** TL layer used by the client */\n readonly _layer: number\n /** TL readers map used by the client */\n readonly _readerMap: TlReaderMap\n /** TL writers map used by the client */\n readonly _writerMap: TlWriterMap\n\n /** Unix timestamp when the last update was received */\n protected _lastUpdateTime = 0\n\n readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n // not really connected, but rather \"connect() was called\"\n private _connected: ControllablePromise<void> | boolean = false\n\n private _onError?: (err: unknown, connection?: SessionConnection) => void\n\n private _importFrom?: string\n private _importForce?: boolean\n\n readonly log = new LogManager('client')\n readonly network: NetworkManager\n\n constructor(opts: BaseTelegramClientOptions) {\n super()\n\n const apiId = typeof opts.apiId === 'string' ? parseInt(opts.apiId) : opts.apiId\n\n if (isNaN(apiId)) {\n throw new Error('apiId must be a number or a numeric string!')\n }\n\n if (opts.logLevel !== undefined) {\n this.log.level = opts.logLevel\n }\n\n this.crypto = (opts.crypto ?? defaultCryptoProviderFactory)()\n\n this.storage = opts.storage\n this._apiHash = opts.apiHash\n this._useIpv6 = Boolean(opts.useIpv6)\n this._testMode = Boolean(opts.testMode)\n\n let dc = opts.defaultDcs\n\n if (!dc) {\n if (this._testMode) {\n dc = this._useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = this._useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = opts.niceStacks ?? true\n\n this._layer = opts.overrideLayer ?? tl.LAYER\n this._readerMap = opts.readerMap ?? defaultReaderMap\n this._writerMap = opts.writerMap ?? defaultWriterMap\n\n this.network = new NetworkManager(\n {\n apiId,\n crypto: this.crypto,\n disableUpdates: opts.disableUpdates ?? false,\n initConnectionOptions: opts.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: opts.reconnectionStrategy,\n storage: this.storage,\n testMode: this._testMode,\n transport: opts.transport,\n _emitError: this._emitError.bind(this),\n floodSleepThreshold: opts.floodSleepThreshold ?? 10000,\n maxRetryCount: opts.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(opts.useIpv6),\n keepAliveAction: this._keepAliveAction.bind(this),\n enableErrorReporting: opts.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n ...(opts.network ?? {}),\n },\n this._config,\n )\n\n this.storage.setup?.(this.log, this._readerMap, this._writerMap)\n }\n\n protected _keepAliveAction(): void {\n this.emit('keep_alive')\n }\n\n protected async _loadStorage(): Promise<void> {\n await this.storage.load?.()\n }\n\n _beforeStorageSave: (() => Promise<void>)[] = []\n\n beforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave.push(cb)\n }\n\n offBeforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave = this._beforeStorageSave.filter((x) => x !== cb)\n }\n\n async saveStorage(): Promise<void> {\n for (const cb of this._beforeStorageSave) {\n await cb()\n }\n await this.storage.save?.()\n }\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n if (this._connected) {\n // avoid double-connect\n await this._connected\n\n return\n }\n\n const promise = (this._connected = createControllablePromise())\n\n await this.crypto.initialize?.()\n await this._loadStorage()\n const primaryDc = await this.storage.getDefaultDcs()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n\n const defaultDcAuthKey = await this.storage.getAuthKeyFor(this._defaultDcs.main.id)\n\n if ((this._importForce || !defaultDcAuthKey) && this._importFrom) {\n const data = readStringSession(this._readerMap, this._importFrom)\n\n if (data.testMode !== this._testMode) {\n throw new Error(\n 'This session string is not for the current backend. ' +\n `Session is ${data.testMode ? 'test' : 'prod'}, but the client is ${\n this._testMode ? 'test' : 'prod'\n }`,\n )\n }\n\n this._defaultDcs = data.primaryDcs\n await this.storage.setDefaultDcs(data.primaryDcs)\n\n if (data.self) {\n await this.storage.setSelf(data.self)\n }\n\n // await this.primaryConnection.setupKeys(data.authKey)\n await this.storage.setAuthKeyFor(data.primaryDcs.main.id, data.authKey)\n\n await this.saveStorage()\n }\n\n this.emit('before_connect')\n\n this.network\n .connect(this._defaultDcs)\n .then(() => {\n promise.resolve()\n this._connected = true\n })\n .catch((err: Error) => this._emitError(err))\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this.emit('before_close')\n\n this._config.destroy()\n this.network.destroy()\n\n await this.saveStorage()\n await this.storage.destroy?.()\n\n this.emit('closed')\n }\n\n /**\n * Make an RPC call to the primary DC.\n * This method handles DC migration, flood waits and retries automatically.\n *\n * If you want more low-level control, use\n * `primaryConnection.sendForResult()` (which is what this method wraps)\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n if (this._connected !== true) {\n await this.connect()\n }\n\n const stack = this._niceStacks ? new Error().stack : undefined\n\n const res = await this.network.call(message, params, stack)\n\n if (await this._cachePeersFrom(res)) {\n await this.saveStorage()\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n /**\n * Change transport for the client.\n *\n * Can be used, for example, to change proxy at runtime\n *\n * This effectively calls `changeTransport()` on\n * `primaryConnection` and all additional connections.\n *\n * @param factory New transport factory\n */\n changeTransport(factory: TransportFactory): void {\n this.network.changeTransport(factory)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler\n * Error handler. Called with one or two parameters.\n * The first one is always the error, and the second is\n * the connection in which the error has occurred, in case\n * this was connection-related error.\n */\n onError(handler: (err: unknown, connection?: SessionConnection) => void): void {\n this._onError = handler\n }\n\n notifyLoggedIn(auth: tl.auth.RawAuthorization): void {\n this.network.notifyLoggedIn(auth)\n this.emit('logged_in', auth)\n }\n\n _emitError(err: unknown, connection?: SessionConnection): void {\n if (this._onError) {\n this._onError(err, connection)\n } else {\n console.error(err)\n }\n }\n\n /**\n * Adds all peers from a given object to entity cache in storage.\n */\n async _cachePeersFrom(obj: object): Promise<boolean> {\n const parsedPeers: ITelegramStorage.PeerInfo[] = []\n\n let count = 0\n\n for (const peer of getAllPeersFrom(obj as tl.TlObject)) {\n if ((peer as any).min) {\n // no point in caching min peers as we can't use them\n continue\n }\n\n count += 1\n\n switch (peer._) {\n case 'user':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n\n parsedPeers.push({\n id: peer.id,\n accessHash: peer.accessHash,\n username: peer.username?.toLowerCase(),\n phone: peer.phone,\n type: 'user',\n full: peer,\n })\n break\n case 'chat':\n case 'chatForbidden':\n parsedPeers.push({\n id: -peer.id,\n accessHash: Long.ZERO,\n type: 'chat',\n full: peer,\n })\n break\n case 'channel':\n case 'channelForbidden':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n parsedPeers.push({\n id: toggleChannelIdMark(peer.id),\n accessHash: peer.accessHash,\n username: peer._ === 'channel' ? peer.username?.toLowerCase() : undefined,\n type: 'channel',\n full: peer,\n })\n break\n }\n }\n\n if (count > 0) {\n await this.storage.updatePeers(parsedPeers)\n this.log.debug('cached %d peers', count)\n\n return true\n }\n\n return false\n }\n\n /**\n * Export current session to a single *LONG* string, containing\n * all the needed information.\n *\n * > **Warning!** Anyone with this string will be able\n * > to authorize as you and do anything. Treat this\n * > as your password, and never give it away!\n * >\n * > In case you have accidentally leaked this string,\n * > make sure to revoke this session in account settings:\n * > \"Privacy & Security\" > \"Active sessions\" >\n * > find the one containing `mtcute` > Revoke,\n * > or, in case this is a bot, revoke bot token\n * > with [@BotFather](//t.me/botfather)\n */\n async exportSession(): Promise<string> {\n const primaryDcs = await this.storage.getDefaultDcs()\n if (!primaryDcs) throw new Error('No default DC set')\n\n const authKey = await this.storage.getAuthKeyFor(primaryDcs.main.id)\n if (!authKey) throw new Error('Auth key is not ready yet')\n\n return writeStringSession(this._writerMap, {\n version: 2,\n self: await this.storage.getSelf(),\n testMode: this._testMode,\n primaryDcs,\n authKey,\n })\n }\n\n /**\n * Request the session to be imported from the given session string.\n *\n * Note that the string will not be parsed and imported right away,\n * instead, it will be imported when `connect()` is called\n *\n * Also note that the session will only be imported in case\n * the storage is missing authorization (i.e. does not contain\n * auth key for the primary DC), otherwise it will be ignored (unless `force).\n *\n * @param session Session string to import\n * @param force Whether to overwrite existing session\n */\n importSession(session: string, force = false): void {\n this._importFrom = session\n this._importForce = force\n }\n}\n"]}
package/cjs/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export * from './storage/index.js';
4
4
  export * from './types/index.js';
5
5
  export * from './utils/peer-utils.js';
6
6
  /** @hidden */
7
- export * from '@mtcute/tl';
7
+ export { mtp, tl } from '@mtcute/tl';
8
8
  import Long from 'long';
9
9
  /** @hidden */
10
10
  export { Long };
package/cjs/index.js CHANGED
@@ -17,14 +17,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.Long = void 0;
20
+ exports.Long = exports.tl = exports.mtp = void 0;
21
21
  __exportStar(require("./base-client.js"), exports);
22
22
  __exportStar(require("./network/index.js"), exports);
23
23
  __exportStar(require("./storage/index.js"), exports);
24
24
  __exportStar(require("./types/index.js"), exports);
25
25
  __exportStar(require("./utils/peer-utils.js"), exports);
26
26
  /** @hidden */
27
- __exportStar(require("@mtcute/tl"), exports);
27
+ var tl_1 = require("@mtcute/tl");
28
+ Object.defineProperty(exports, "mtp", { enumerable: true, get: function () { return tl_1.mtp; } });
29
+ Object.defineProperty(exports, "tl", { enumerable: true, get: function () { return tl_1.tl; } });
28
30
  const long_1 = __importDefault(require("long"));
29
31
  exports.Long = long_1.default;
30
32
  //# sourceMappingURL=index.js.map
package/cjs/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,mDAAgC;AAChC,qDAAkC;AAClC,qDAAkC;AAClC,mDAAgC;AAChC,wDAAqC;AAErC,cAAc;AACd,6CAA0B;AAC1B,gDAAuB;AAEd,eAFF,cAAI,CAEE","sourcesContent":["export * from './base-client.js'\nexport * from './network/index.js'\nexport * from './storage/index.js'\nexport * from './types/index.js'\nexport * from './utils/peer-utils.js'\n\n/** @hidden */\nexport * from '@mtcute/tl'\nimport Long from 'long'\n/** @hidden */\nexport { Long }\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,mDAAgC;AAChC,qDAAkC;AAClC,qDAAkC;AAClC,mDAAgC;AAChC,wDAAqC;AAErC,cAAc;AACd,iCAAoC;AAA3B,yFAAA,GAAG,OAAA;AAAE,wFAAA,EAAE,OAAA;AAChB,gDAAuB;AAEd,eAFF,cAAI,CAEE","sourcesContent":["export * from './base-client.js'\nexport * from './network/index.js'\nexport * from './storage/index.js'\nexport * from './types/index.js'\nexport * from './utils/peer-utils.js'\n\n/** @hidden */\nexport { mtp, tl } from '@mtcute/tl'\nimport Long from 'long'\n/** @hidden */\nexport { Long }\n"]}
@@ -226,7 +226,7 @@ class NetworkManager {
226
226
  _: 'initConnection',
227
227
  deviceModel,
228
228
  systemVersion: '1.0',
229
- appVersion: '0.2.0',
229
+ appVersion: '0.2.2',
230
230
  systemLangCode: 'en',
231
231
  langPack: '',
232
232
  langCode: 'en',
@@ -260,7 +260,7 @@ export declare class BaseTelegramClient extends EventEmitter {
260
260
  /**
261
261
  * Adds all peers from a given object to entity cache in storage.
262
262
  */
263
- _cachePeersFrom(obj: object): Promise<void>;
263
+ _cachePeersFrom(obj: object): Promise<boolean>;
264
264
  /**
265
265
  * Export current session to a single *LONG* string, containing
266
266
  * all the needed information.
@@ -163,7 +163,9 @@ export class BaseTelegramClient extends EventEmitter {
163
163
  }
164
164
  const stack = this._niceStacks ? new Error().stack : undefined;
165
165
  const res = await this.network.call(message, params, stack);
166
- await this._cachePeersFrom(res);
166
+ if (await this._cachePeersFrom(res)) {
167
+ await this.saveStorage();
168
+ }
167
169
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
168
170
  return res;
169
171
  }
@@ -259,7 +261,9 @@ export class BaseTelegramClient extends EventEmitter {
259
261
  if (count > 0) {
260
262
  await this.storage.updatePeers(parsedPeers);
261
263
  this.log.debug('cached %d peers', count);
264
+ return true;
262
265
  }
266
+ return false;
263
267
  }
264
268
  /**
265
269
  * Export current session to a single *LONG* string, containing
@@ -1 +1 @@
1
- {"version":3,"file":"base-client.js","sourceRoot":"","sources":["../../src/base-client.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,YAAY,MAAM,QAAQ,CAAA;AACjC,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB,OAAO,EAAE,EAAE,EAAE,MAAM,YAAY,CAAA;AAC/B,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAC/E,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAG/E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAE3D,OAAO,EAAE,cAAc,EAA6C,MAAM,8BAA8B,CAAA;AAIxG,OAAO,EAEH,yBAAyB,EAEzB,4BAA4B,EAC5B,mBAAmB,EACnB,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EACjB,eAAe,EAEf,UAAU,EACV,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,GACrB,MAAM,kBAAkB,CAAA;AAwKzB;;;GAGG;AACH,MAAM,OA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AU,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAA;QACrD,IAAI,CAAC,UAAU;YAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAErD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACpE,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;QAE1D,OAAO,kBAAkB,CAAC,IAAI,CAAC,UAAU,EAAE;YACvC,OAAO,EAAE,CAAC;YACV,IAAI,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YAClC,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,UAAU;YACV,OAAO;SACV,CAAC,CAAA;IACN,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,OAAe,EAAE,KAAK,GAAG,KAAK;QACxC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAA;QAC1B,IAAI,CAAC,YAAY,GAAG,KAAK,CAAA;IAC7B,CAAC;CACJ","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport EventEmitter from 'events'\nimport Long from 'long'\n\nimport { tl } from '@mtcute/tl'\nimport { __tlReaderMap as defaultReaderMap } from '@mtcute/tl/binary/reader.js'\nimport { __tlWriterMap as defaultWriterMap } from '@mtcute/tl/binary/writer.js'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { ConfigManager } from './network/config-manager.js'\nimport { ReconnectionStrategy, SessionConnection, TransportFactory } from './network/index.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network/network-manager.js'\nimport { PersistentConnectionParams } from './network/persistent-connection.js'\nimport { ITelegramStorage } from './storage/index.js'\nimport { MustEqual } from './types/index.js'\nimport {\n ControllablePromise,\n createControllablePromise,\n CryptoProviderFactory,\n defaultCryptoProviderFactory,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n getAllPeersFrom,\n ICryptoProvider,\n LogManager,\n readStringSession,\n toggleChannelIdMark,\n writeStringSession,\n} from './utils/index.js'\n\n/** Options for {@link BaseTelegramClient} */\nexport interface BaseTelegramClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number | string\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: ITelegramStorage\n\n /**\n * Cryptography provider factory to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto?: CryptoProviderFactory\n\n /**\n * Whether to use IPv6 datacenters\n * (IPv6 will be preferred when choosing a DC by id)\n * (default: false)\n */\n useIpv6?: boolean\n\n /**\n * Primary DC to use for initial connection.\n * This does not mean this will be the only DC used,\n * nor that this DC will actually be primary, this only\n * determines the first DC the library will try to connect to.\n * Can be used to connect to other networks (like test DCs).\n *\n * When session already contains primary DC, this parameter is ignored.\n *\n * @default Production DC 2.\n */\n defaultDcs?: ITelegramStorage.DcOptions\n\n /**\n * Whether to connect to test servers.\n *\n * If passed, {@link defaultDc} defaults to Test DC 2.\n *\n * **Must** be passed if using test servers, even if\n * you passed custom {@link defaultDc}\n */\n testMode?: boolean\n\n /**\n * Additional options for initConnection call.\n * `apiId` and `query` are not available and will be ignored.\n * Omitted values will be filled with defaults\n */\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n\n /**\n * Transport factory to use in the client.\n *\n * @default platform-specific transport: WebSocket on the web, TCP in node\n */\n transport?: TransportFactory\n\n /**\n * Reconnection strategy.\n *\n * @default simple reconnection strategy: first 0ms, then up to 5s (increasing by 1s)\n */\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n\n /**\n * Maximum duration of a flood_wait that will be waited automatically.\n * Flood waits above this threshold will throw a FloodWaitError.\n * Set to 0 to disable. Can be overridden with `throwFlood` parameter in call() params\n *\n * @default 10000\n */\n floodSleepThreshold?: number\n\n /**\n * Maximum number of retries when calling RPC methods.\n * Call is retried when InternalError or FloodWaitError is encountered.\n * Can be set to Infinity.\n *\n * @default 5\n */\n maxRetryCount?: number\n\n /**\n * If true, every single API call will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * Note that this only wraps calls made with `.call()` within the primary\n * connection. Additional connections and direct `.sendForResult()` calls\n * must be wrapped manually.\n *\n * @default false\n */\n disableUpdates?: boolean\n\n /**\n * mtcute can send all unknown RPC errors to [danog](https://github.com/danog)'s\n * [error reporting service](https://rpc.pwrtelegram.xyz/).\n *\n * This is fully anonymous (except maybe IP) and is only used to improve the library\n * and developer experience for everyone working with MTProto. This is fully opt-in,\n * and if you're too paranoid, you can disable it by manually passing `enableErrorReporting: false` to the client.\n *\n * @default false\n */\n enableErrorReporting?: boolean\n\n /**\n * If true, RPC errors will have a stack trace of the initial `.call()`\n * or `.sendForResult()` call position, which drastically improves\n * debugging experience.<br>\n * If false, they will have a stack trace of mtcute internals.\n *\n * Internally this creates a stack capture before every RPC call\n * and stores it until the result is received. This might\n * use a lot more memory than normal, thus can be disabled here.\n *\n * @default true\n */\n niceStacks?: boolean\n\n /**\n * Extra parameters for {@link NetworkManager}\n */\n network?: NetworkManagerExtraParams\n\n /**\n * Set logging level for the client.\n *\n * See static members of {@link LogManager} for possible values.\n */\n logLevel?: number\n\n /**\n * **EXPERT USE ONLY!**\n *\n * Override TL layer used for the connection.\n *\n * **Does not** change the schema used.\n */\n overrideLayer?: number\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override reader map used for the connection.\n */\n readerMap?: TlReaderMap\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override writer map used for the connection.\n */\n writerMap?: TlWriterMap\n}\n\n/**\n * Basic Telegram client that only implements the bare minimum\n * to make RPC calls and receive low-level updates.\n */\nexport class BaseTelegramClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link BaseTelegramClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /**\n * Telegram storage taken from {@link BaseTelegramClientOptions.storage}\n */\n readonly storage: ITelegramStorage\n\n /**\n * API hash taken from {@link BaseTelegramClientOptions.apiHash}\n */\n protected readonly _apiHash: string\n\n /**\n * \"Use IPv6\" taken from {@link BaseTelegramClientOptions.useIpv6}\n */\n protected readonly _useIpv6: boolean\n\n /**\n * \"Test mode\" taken from {@link BaseTelegramClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link BaseTelegramClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n protected _defaultDcs: ITelegramStorage.DcOptions\n\n private _niceStacks: boolean\n /** TL layer used by the client */\n readonly _layer: number\n /** TL readers map used by the client */\n readonly _readerMap: TlReaderMap\n /** TL writers map used by the client */\n readonly _writerMap: TlWriterMap\n\n /** Unix timestamp when the last update was received */\n protected _lastUpdateTime = 0\n\n readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n // not really connected, but rather \"connect() was called\"\n private _connected: ControllablePromise<void> | boolean = false\n\n private _onError?: (err: unknown, connection?: SessionConnection) => void\n\n private _importFrom?: string\n private _importForce?: boolean\n\n readonly log = new LogManager('client')\n readonly network: NetworkManager\n\n constructor(opts: BaseTelegramClientOptions) {\n super()\n\n const apiId = typeof opts.apiId === 'string' ? parseInt(opts.apiId) : opts.apiId\n\n if (isNaN(apiId)) {\n throw new Error('apiId must be a number or a numeric string!')\n }\n\n if (opts.logLevel !== undefined) {\n this.log.level = opts.logLevel\n }\n\n this.crypto = (opts.crypto ?? defaultCryptoProviderFactory)()\n\n this.storage = opts.storage\n this._apiHash = opts.apiHash\n this._useIpv6 = Boolean(opts.useIpv6)\n this._testMode = Boolean(opts.testMode)\n\n let dc = opts.defaultDcs\n\n if (!dc) {\n if (this._testMode) {\n dc = this._useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = this._useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = opts.niceStacks ?? true\n\n this._layer = opts.overrideLayer ?? tl.LAYER\n this._readerMap = opts.readerMap ?? defaultReaderMap\n this._writerMap = opts.writerMap ?? defaultWriterMap\n\n this.network = new NetworkManager(\n {\n apiId,\n crypto: this.crypto,\n disableUpdates: opts.disableUpdates ?? false,\n initConnectionOptions: opts.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: opts.reconnectionStrategy,\n storage: this.storage,\n testMode: this._testMode,\n transport: opts.transport,\n _emitError: this._emitError.bind(this),\n floodSleepThreshold: opts.floodSleepThreshold ?? 10000,\n maxRetryCount: opts.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(opts.useIpv6),\n keepAliveAction: this._keepAliveAction.bind(this),\n enableErrorReporting: opts.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n ...(opts.network ?? {}),\n },\n this._config,\n )\n\n this.storage.setup?.(this.log, this._readerMap, this._writerMap)\n }\n\n protected _keepAliveAction(): void {\n this.emit('keep_alive')\n }\n\n protected async _loadStorage(): Promise<void> {\n await this.storage.load?.()\n }\n\n _beforeStorageSave: (() => Promise<void>)[] = []\n\n beforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave.push(cb)\n }\n\n offBeforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave = this._beforeStorageSave.filter((x) => x !== cb)\n }\n\n async saveStorage(): Promise<void> {\n for (const cb of this._beforeStorageSave) {\n await cb()\n }\n await this.storage.save?.()\n }\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n if (this._connected) {\n // avoid double-connect\n await this._connected\n\n return\n }\n\n const promise = (this._connected = createControllablePromise())\n\n await this.crypto.initialize?.()\n await this._loadStorage()\n const primaryDc = await this.storage.getDefaultDcs()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n\n const defaultDcAuthKey = await this.storage.getAuthKeyFor(this._defaultDcs.main.id)\n\n if ((this._importForce || !defaultDcAuthKey) && this._importFrom) {\n const data = readStringSession(this._readerMap, this._importFrom)\n\n if (data.testMode !== this._testMode) {\n throw new Error(\n 'This session string is not for the current backend. ' +\n `Session is ${data.testMode ? 'test' : 'prod'}, but the client is ${\n this._testMode ? 'test' : 'prod'\n }`,\n )\n }\n\n this._defaultDcs = data.primaryDcs\n await this.storage.setDefaultDcs(data.primaryDcs)\n\n if (data.self) {\n await this.storage.setSelf(data.self)\n }\n\n // await this.primaryConnection.setupKeys(data.authKey)\n await this.storage.setAuthKeyFor(data.primaryDcs.main.id, data.authKey)\n\n await this.saveStorage()\n }\n\n this.emit('before_connect')\n\n this.network\n .connect(this._defaultDcs)\n .then(() => {\n promise.resolve()\n this._connected = true\n })\n .catch((err: Error) => this._emitError(err))\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this.emit('before_close')\n\n this._config.destroy()\n this.network.destroy()\n\n await this.saveStorage()\n await this.storage.destroy?.()\n\n this.emit('closed')\n }\n\n /**\n * Make an RPC call to the primary DC.\n * This method handles DC migration, flood waits and retries automatically.\n *\n * If you want more low-level control, use\n * `primaryConnection.sendForResult()` (which is what this method wraps)\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n if (this._connected !== true) {\n await this.connect()\n }\n\n const stack = this._niceStacks ? new Error().stack : undefined\n\n const res = await this.network.call(message, params, stack)\n await this._cachePeersFrom(res)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n /**\n * Change transport for the client.\n *\n * Can be used, for example, to change proxy at runtime\n *\n * This effectively calls `changeTransport()` on\n * `primaryConnection` and all additional connections.\n *\n * @param factory New transport factory\n */\n changeTransport(factory: TransportFactory): void {\n this.network.changeTransport(factory)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler\n * Error handler. Called with one or two parameters.\n * The first one is always the error, and the second is\n * the connection in which the error has occurred, in case\n * this was connection-related error.\n */\n onError(handler: (err: unknown, connection?: SessionConnection) => void): void {\n this._onError = handler\n }\n\n notifyLoggedIn(auth: tl.auth.RawAuthorization): void {\n this.network.notifyLoggedIn(auth)\n this.emit('logged_in', auth)\n }\n\n _emitError(err: unknown, connection?: SessionConnection): void {\n if (this._onError) {\n this._onError(err, connection)\n } else {\n console.error(err)\n }\n }\n\n /**\n * Adds all peers from a given object to entity cache in storage.\n */\n async _cachePeersFrom(obj: object): Promise<void> {\n const parsedPeers: ITelegramStorage.PeerInfo[] = []\n\n let count = 0\n\n for (const peer of getAllPeersFrom(obj as tl.TlObject)) {\n if ((peer as any).min) {\n // no point in caching min peers as we can't use them\n continue\n }\n\n count += 1\n\n switch (peer._) {\n case 'user':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n\n parsedPeers.push({\n id: peer.id,\n accessHash: peer.accessHash,\n username: peer.username?.toLowerCase(),\n phone: peer.phone,\n type: 'user',\n full: peer,\n })\n break\n case 'chat':\n case 'chatForbidden':\n parsedPeers.push({\n id: -peer.id,\n accessHash: Long.ZERO,\n type: 'chat',\n full: peer,\n })\n break\n case 'channel':\n case 'channelForbidden':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n parsedPeers.push({\n id: toggleChannelIdMark(peer.id),\n accessHash: peer.accessHash,\n username: peer._ === 'channel' ? peer.username?.toLowerCase() : undefined,\n type: 'channel',\n full: peer,\n })\n break\n }\n }\n\n if (count > 0) {\n await this.storage.updatePeers(parsedPeers)\n this.log.debug('cached %d peers', count)\n }\n }\n\n /**\n * Export current session to a single *LONG* string, containing\n * all the needed information.\n *\n * > **Warning!** Anyone with this string will be able\n * > to authorize as you and do anything. Treat this\n * > as your password, and never give it away!\n * >\n * > In case you have accidentally leaked this string,\n * > make sure to revoke this session in account settings:\n * > \"Privacy & Security\" > \"Active sessions\" >\n * > find the one containing `mtcute` > Revoke,\n * > or, in case this is a bot, revoke bot token\n * > with [@BotFather](//t.me/botfather)\n */\n async exportSession(): Promise<string> {\n const primaryDcs = await this.storage.getDefaultDcs()\n if (!primaryDcs) throw new Error('No default DC set')\n\n const authKey = await this.storage.getAuthKeyFor(primaryDcs.main.id)\n if (!authKey) throw new Error('Auth key is not ready yet')\n\n return writeStringSession(this._writerMap, {\n version: 2,\n self: await this.storage.getSelf(),\n testMode: this._testMode,\n primaryDcs,\n authKey,\n })\n }\n\n /**\n * Request the session to be imported from the given session string.\n *\n * Note that the string will not be parsed and imported right away,\n * instead, it will be imported when `connect()` is called\n *\n * Also note that the session will only be imported in case\n * the storage is missing authorization (i.e. does not contain\n * auth key for the primary DC), otherwise it will be ignored (unless `force).\n *\n * @param session Session string to import\n * @param force Whether to overwrite existing session\n */\n importSession(session: string, force = false): void {\n this._importFrom = session\n this._importForce = force\n }\n}\n"]}
1
+ {"version":3,"file":"base-client.js","sourceRoot":"","sources":["../../src/base-client.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,YAAY,MAAM,QAAQ,CAAA;AACjC,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB,OAAO,EAAE,EAAE,EAAE,MAAM,YAAY,CAAA;AAC/B,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAC/E,OAAO,EAAE,aAAa,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAG/E,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAE3D,OAAO,EAAE,cAAc,EAA6C,MAAM,8BAA8B,CAAA;AAIxG,OAAO,EAEH,yBAAyB,EAEzB,4BAA4B,EAC5B,mBAAmB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MAAM,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAA;YAC3C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAA;YAExC,OAAO,IAAI,CAAA;SACd;QAED,OAAO,KAAK,CAAA;IAChB,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,aAAa;QACf,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAA;QACrD,IAAI,CAAC,UAAU;YAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAA;QAErD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACpE,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;QAE1D,OAAO,kBAAkB,CAAC,IAAI,CAAC,UAAU,EAAE;YACvC,OAAO,EAAE,CAAC;YACV,IAAI,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YAClC,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,UAAU;YACV,OAAO;SACV,CAAC,CAAA;IACN,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,OAAe,EAAE,KAAK,GAAG,KAAK;QACxC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAA;QAC1B,IAAI,CAAC,YAAY,GAAG,KAAK,CAAA;IAC7B,CAAC;CACJ","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport EventEmitter from 'events'\nimport Long from 'long'\n\nimport { tl } from '@mtcute/tl'\nimport { __tlReaderMap as defaultReaderMap } from '@mtcute/tl/binary/reader.js'\nimport { __tlWriterMap as defaultWriterMap } from '@mtcute/tl/binary/writer.js'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { ConfigManager } from './network/config-manager.js'\nimport { ReconnectionStrategy, SessionConnection, TransportFactory } from './network/index.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network/network-manager.js'\nimport { PersistentConnectionParams } from './network/persistent-connection.js'\nimport { ITelegramStorage } from './storage/index.js'\nimport { MustEqual } from './types/index.js'\nimport {\n ControllablePromise,\n createControllablePromise,\n CryptoProviderFactory,\n defaultCryptoProviderFactory,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n getAllPeersFrom,\n ICryptoProvider,\n LogManager,\n readStringSession,\n toggleChannelIdMark,\n writeStringSession,\n} from './utils/index.js'\n\n/** Options for {@link BaseTelegramClient} */\nexport interface BaseTelegramClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number | string\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: ITelegramStorage\n\n /**\n * Cryptography provider factory to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto?: CryptoProviderFactory\n\n /**\n * Whether to use IPv6 datacenters\n * (IPv6 will be preferred when choosing a DC by id)\n * (default: false)\n */\n useIpv6?: boolean\n\n /**\n * Primary DC to use for initial connection.\n * This does not mean this will be the only DC used,\n * nor that this DC will actually be primary, this only\n * determines the first DC the library will try to connect to.\n * Can be used to connect to other networks (like test DCs).\n *\n * When session already contains primary DC, this parameter is ignored.\n *\n * @default Production DC 2.\n */\n defaultDcs?: ITelegramStorage.DcOptions\n\n /**\n * Whether to connect to test servers.\n *\n * If passed, {@link defaultDc} defaults to Test DC 2.\n *\n * **Must** be passed if using test servers, even if\n * you passed custom {@link defaultDc}\n */\n testMode?: boolean\n\n /**\n * Additional options for initConnection call.\n * `apiId` and `query` are not available and will be ignored.\n * Omitted values will be filled with defaults\n */\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n\n /**\n * Transport factory to use in the client.\n *\n * @default platform-specific transport: WebSocket on the web, TCP in node\n */\n transport?: TransportFactory\n\n /**\n * Reconnection strategy.\n *\n * @default simple reconnection strategy: first 0ms, then up to 5s (increasing by 1s)\n */\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n\n /**\n * Maximum duration of a flood_wait that will be waited automatically.\n * Flood waits above this threshold will throw a FloodWaitError.\n * Set to 0 to disable. Can be overridden with `throwFlood` parameter in call() params\n *\n * @default 10000\n */\n floodSleepThreshold?: number\n\n /**\n * Maximum number of retries when calling RPC methods.\n * Call is retried when InternalError or FloodWaitError is encountered.\n * Can be set to Infinity.\n *\n * @default 5\n */\n maxRetryCount?: number\n\n /**\n * If true, every single API call will be wrapped with `tl.invokeWithoutUpdates`,\n * effectively disabling the server-sent events for the clients.\n * May be useful in some cases.\n *\n * Note that this only wraps calls made with `.call()` within the primary\n * connection. Additional connections and direct `.sendForResult()` calls\n * must be wrapped manually.\n *\n * @default false\n */\n disableUpdates?: boolean\n\n /**\n * mtcute can send all unknown RPC errors to [danog](https://github.com/danog)'s\n * [error reporting service](https://rpc.pwrtelegram.xyz/).\n *\n * This is fully anonymous (except maybe IP) and is only used to improve the library\n * and developer experience for everyone working with MTProto. This is fully opt-in,\n * and if you're too paranoid, you can disable it by manually passing `enableErrorReporting: false` to the client.\n *\n * @default false\n */\n enableErrorReporting?: boolean\n\n /**\n * If true, RPC errors will have a stack trace of the initial `.call()`\n * or `.sendForResult()` call position, which drastically improves\n * debugging experience.<br>\n * If false, they will have a stack trace of mtcute internals.\n *\n * Internally this creates a stack capture before every RPC call\n * and stores it until the result is received. This might\n * use a lot more memory than normal, thus can be disabled here.\n *\n * @default true\n */\n niceStacks?: boolean\n\n /**\n * Extra parameters for {@link NetworkManager}\n */\n network?: NetworkManagerExtraParams\n\n /**\n * Set logging level for the client.\n *\n * See static members of {@link LogManager} for possible values.\n */\n logLevel?: number\n\n /**\n * **EXPERT USE ONLY!**\n *\n * Override TL layer used for the connection.\n *\n * **Does not** change the schema used.\n */\n overrideLayer?: number\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override reader map used for the connection.\n */\n readerMap?: TlReaderMap\n\n /**\n * **EXPERT USE ONLY**\n *\n * Override writer map used for the connection.\n */\n writerMap?: TlWriterMap\n}\n\n/**\n * Basic Telegram client that only implements the bare minimum\n * to make RPC calls and receive low-level updates.\n */\nexport class BaseTelegramClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link BaseTelegramClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /**\n * Telegram storage taken from {@link BaseTelegramClientOptions.storage}\n */\n readonly storage: ITelegramStorage\n\n /**\n * API hash taken from {@link BaseTelegramClientOptions.apiHash}\n */\n protected readonly _apiHash: string\n\n /**\n * \"Use IPv6\" taken from {@link BaseTelegramClientOptions.useIpv6}\n */\n protected readonly _useIpv6: boolean\n\n /**\n * \"Test mode\" taken from {@link BaseTelegramClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link BaseTelegramClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n protected _defaultDcs: ITelegramStorage.DcOptions\n\n private _niceStacks: boolean\n /** TL layer used by the client */\n readonly _layer: number\n /** TL readers map used by the client */\n readonly _readerMap: TlReaderMap\n /** TL writers map used by the client */\n readonly _writerMap: TlWriterMap\n\n /** Unix timestamp when the last update was received */\n protected _lastUpdateTime = 0\n\n readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n // not really connected, but rather \"connect() was called\"\n private _connected: ControllablePromise<void> | boolean = false\n\n private _onError?: (err: unknown, connection?: SessionConnection) => void\n\n private _importFrom?: string\n private _importForce?: boolean\n\n readonly log = new LogManager('client')\n readonly network: NetworkManager\n\n constructor(opts: BaseTelegramClientOptions) {\n super()\n\n const apiId = typeof opts.apiId === 'string' ? parseInt(opts.apiId) : opts.apiId\n\n if (isNaN(apiId)) {\n throw new Error('apiId must be a number or a numeric string!')\n }\n\n if (opts.logLevel !== undefined) {\n this.log.level = opts.logLevel\n }\n\n this.crypto = (opts.crypto ?? defaultCryptoProviderFactory)()\n\n this.storage = opts.storage\n this._apiHash = opts.apiHash\n this._useIpv6 = Boolean(opts.useIpv6)\n this._testMode = Boolean(opts.testMode)\n\n let dc = opts.defaultDcs\n\n if (!dc) {\n if (this._testMode) {\n dc = this._useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = this._useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = opts.niceStacks ?? true\n\n this._layer = opts.overrideLayer ?? tl.LAYER\n this._readerMap = opts.readerMap ?? defaultReaderMap\n this._writerMap = opts.writerMap ?? defaultWriterMap\n\n this.network = new NetworkManager(\n {\n apiId,\n crypto: this.crypto,\n disableUpdates: opts.disableUpdates ?? false,\n initConnectionOptions: opts.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: opts.reconnectionStrategy,\n storage: this.storage,\n testMode: this._testMode,\n transport: opts.transport,\n _emitError: this._emitError.bind(this),\n floodSleepThreshold: opts.floodSleepThreshold ?? 10000,\n maxRetryCount: opts.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(opts.useIpv6),\n keepAliveAction: this._keepAliveAction.bind(this),\n enableErrorReporting: opts.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n ...(opts.network ?? {}),\n },\n this._config,\n )\n\n this.storage.setup?.(this.log, this._readerMap, this._writerMap)\n }\n\n protected _keepAliveAction(): void {\n this.emit('keep_alive')\n }\n\n protected async _loadStorage(): Promise<void> {\n await this.storage.load?.()\n }\n\n _beforeStorageSave: (() => Promise<void>)[] = []\n\n beforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave.push(cb)\n }\n\n offBeforeStorageSave(cb: () => Promise<void>): void {\n this._beforeStorageSave = this._beforeStorageSave.filter((x) => x !== cb)\n }\n\n async saveStorage(): Promise<void> {\n for (const cb of this._beforeStorageSave) {\n await cb()\n }\n await this.storage.save?.()\n }\n\n /**\n * Initialize the connection to the primary DC.\n *\n * You shouldn't usually call this method directly as it is called\n * implicitly the first time you call {@link call}.\n */\n async connect(): Promise<void> {\n if (this._connected) {\n // avoid double-connect\n await this._connected\n\n return\n }\n\n const promise = (this._connected = createControllablePromise())\n\n await this.crypto.initialize?.()\n await this._loadStorage()\n const primaryDc = await this.storage.getDefaultDcs()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n\n const defaultDcAuthKey = await this.storage.getAuthKeyFor(this._defaultDcs.main.id)\n\n if ((this._importForce || !defaultDcAuthKey) && this._importFrom) {\n const data = readStringSession(this._readerMap, this._importFrom)\n\n if (data.testMode !== this._testMode) {\n throw new Error(\n 'This session string is not for the current backend. ' +\n `Session is ${data.testMode ? 'test' : 'prod'}, but the client is ${\n this._testMode ? 'test' : 'prod'\n }`,\n )\n }\n\n this._defaultDcs = data.primaryDcs\n await this.storage.setDefaultDcs(data.primaryDcs)\n\n if (data.self) {\n await this.storage.setSelf(data.self)\n }\n\n // await this.primaryConnection.setupKeys(data.authKey)\n await this.storage.setAuthKeyFor(data.primaryDcs.main.id, data.authKey)\n\n await this.saveStorage()\n }\n\n this.emit('before_connect')\n\n this.network\n .connect(this._defaultDcs)\n .then(() => {\n promise.resolve()\n this._connected = true\n })\n .catch((err: Error) => this._emitError(err))\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this.emit('before_close')\n\n this._config.destroy()\n this.network.destroy()\n\n await this.saveStorage()\n await this.storage.destroy?.()\n\n this.emit('closed')\n }\n\n /**\n * Make an RPC call to the primary DC.\n * This method handles DC migration, flood waits and retries automatically.\n *\n * If you want more low-level control, use\n * `primaryConnection.sendForResult()` (which is what this method wraps)\n *\n * This method is still quite low-level and you shouldn't use this\n * when using high-level API provided by `@mtcute/client`.\n *\n * @param message RPC method to call\n * @param params Additional call parameters\n */\n async call<T extends tl.RpcMethod>(\n message: MustEqual<T, tl.RpcMethod>,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']]> {\n if (this._connected !== true) {\n await this.connect()\n }\n\n const stack = this._niceStacks ? new Error().stack : undefined\n\n const res = await this.network.call(message, params, stack)\n\n if (await this._cachePeersFrom(res)) {\n await this.saveStorage()\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n /**\n * Change transport for the client.\n *\n * Can be used, for example, to change proxy at runtime\n *\n * This effectively calls `changeTransport()` on\n * `primaryConnection` and all additional connections.\n *\n * @param factory New transport factory\n */\n changeTransport(factory: TransportFactory): void {\n this.network.changeTransport(factory)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler\n * Error handler. Called with one or two parameters.\n * The first one is always the error, and the second is\n * the connection in which the error has occurred, in case\n * this was connection-related error.\n */\n onError(handler: (err: unknown, connection?: SessionConnection) => void): void {\n this._onError = handler\n }\n\n notifyLoggedIn(auth: tl.auth.RawAuthorization): void {\n this.network.notifyLoggedIn(auth)\n this.emit('logged_in', auth)\n }\n\n _emitError(err: unknown, connection?: SessionConnection): void {\n if (this._onError) {\n this._onError(err, connection)\n } else {\n console.error(err)\n }\n }\n\n /**\n * Adds all peers from a given object to entity cache in storage.\n */\n async _cachePeersFrom(obj: object): Promise<boolean> {\n const parsedPeers: ITelegramStorage.PeerInfo[] = []\n\n let count = 0\n\n for (const peer of getAllPeersFrom(obj as tl.TlObject)) {\n if ((peer as any).min) {\n // no point in caching min peers as we can't use them\n continue\n }\n\n count += 1\n\n switch (peer._) {\n case 'user':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n\n parsedPeers.push({\n id: peer.id,\n accessHash: peer.accessHash,\n username: peer.username?.toLowerCase(),\n phone: peer.phone,\n type: 'user',\n full: peer,\n })\n break\n case 'chat':\n case 'chatForbidden':\n parsedPeers.push({\n id: -peer.id,\n accessHash: Long.ZERO,\n type: 'chat',\n full: peer,\n })\n break\n case 'channel':\n case 'channelForbidden':\n if (!peer.accessHash) {\n this.log.warn('received user without access hash: %j', peer)\n continue\n }\n parsedPeers.push({\n id: toggleChannelIdMark(peer.id),\n accessHash: peer.accessHash,\n username: peer._ === 'channel' ? peer.username?.toLowerCase() : undefined,\n type: 'channel',\n full: peer,\n })\n break\n }\n }\n\n if (count > 0) {\n await this.storage.updatePeers(parsedPeers)\n this.log.debug('cached %d peers', count)\n\n return true\n }\n\n return false\n }\n\n /**\n * Export current session to a single *LONG* string, containing\n * all the needed information.\n *\n * > **Warning!** Anyone with this string will be able\n * > to authorize as you and do anything. Treat this\n * > as your password, and never give it away!\n * >\n * > In case you have accidentally leaked this string,\n * > make sure to revoke this session in account settings:\n * > \"Privacy & Security\" > \"Active sessions\" >\n * > find the one containing `mtcute` > Revoke,\n * > or, in case this is a bot, revoke bot token\n * > with [@BotFather](//t.me/botfather)\n */\n async exportSession(): Promise<string> {\n const primaryDcs = await this.storage.getDefaultDcs()\n if (!primaryDcs) throw new Error('No default DC set')\n\n const authKey = await this.storage.getAuthKeyFor(primaryDcs.main.id)\n if (!authKey) throw new Error('Auth key is not ready yet')\n\n return writeStringSession(this._writerMap, {\n version: 2,\n self: await this.storage.getSelf(),\n testMode: this._testMode,\n primaryDcs,\n authKey,\n })\n }\n\n /**\n * Request the session to be imported from the given session string.\n *\n * Note that the string will not be parsed and imported right away,\n * instead, it will be imported when `connect()` is called\n *\n * Also note that the session will only be imported in case\n * the storage is missing authorization (i.e. does not contain\n * auth key for the primary DC), otherwise it will be ignored (unless `force).\n *\n * @param session Session string to import\n * @param force Whether to overwrite existing session\n */\n importSession(session: string, force = false): void {\n this._importFrom = session\n this._importForce = force\n }\n}\n"]}
package/esm/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export * from './storage/index.js';
4
4
  export * from './types/index.js';
5
5
  export * from './utils/peer-utils.js';
6
6
  /** @hidden */
7
- export * from '@mtcute/tl';
7
+ export { mtp, tl } from '@mtcute/tl';
8
8
  import Long from 'long';
9
9
  /** @hidden */
10
10
  export { Long };
package/esm/index.js CHANGED
@@ -4,7 +4,7 @@ export * from './storage/index.js';
4
4
  export * from './types/index.js';
5
5
  export * from './utils/peer-utils.js';
6
6
  /** @hidden */
7
- export * from '@mtcute/tl';
7
+ export { mtp, tl } from '@mtcute/tl';
8
8
  import Long from 'long';
9
9
  /** @hidden */
10
10
  export { Long };
package/esm/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAA;AAChC,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,cAAc,kBAAkB,CAAA;AAChC,cAAc,uBAAuB,CAAA;AAErC,cAAc;AACd,cAAc,YAAY,CAAA;AAC1B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,cAAc;AACd,OAAO,EAAE,IAAI,EAAE,CAAA","sourcesContent":["export * from './base-client.js'\nexport * from './network/index.js'\nexport * from './storage/index.js'\nexport * from './types/index.js'\nexport * from './utils/peer-utils.js'\n\n/** @hidden */\nexport * from '@mtcute/tl'\nimport Long from 'long'\n/** @hidden */\nexport { Long }\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAA;AAChC,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,cAAc,kBAAkB,CAAA;AAChC,cAAc,uBAAuB,CAAA;AAErC,cAAc;AACd,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,YAAY,CAAA;AACpC,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,cAAc;AACd,OAAO,EAAE,IAAI,EAAE,CAAA","sourcesContent":["export * from './base-client.js'\nexport * from './network/index.js'\nexport * from './storage/index.js'\nexport * from './types/index.js'\nexport * from './utils/peer-utils.js'\n\n/** @hidden */\nexport { mtp, tl } from '@mtcute/tl'\nimport Long from 'long'\n/** @hidden */\nexport { Long }\n"]}
@@ -222,7 +222,7 @@ export class NetworkManager {
222
222
  _: 'initConnection',
223
223
  deviceModel,
224
224
  systemVersion: '1.0',
225
- appVersion: '0.2.0',
225
+ appVersion: '0.2.2',
226
226
  systemLangCode: 'en',
227
227
  langPack: '',
228
228
  langCode: 'en',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mtcute/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Core functions and base MTProto client",
5
5
  "author": "Alina Sireneva <alina@tei.su>",
6
6
  "license": "MIT",