@mtcute/core 0.12.0 → 0.12.1
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.
- package/cjs/network/client.d.ts +2 -1
- package/cjs/network/client.js +9 -1
- package/cjs/network/client.js.map +1 -1
- package/cjs/network/network-manager.js +1 -1
- package/cjs/network/session-connection.js +1 -0
- package/cjs/network/session-connection.js.map +1 -1
- package/esm/network/client.d.ts +2 -1
- package/esm/network/client.js +9 -1
- package/esm/network/client.js.map +1 -1
- package/esm/network/network-manager.js +1 -1
- package/esm/network/session-connection.js +1 -0
- package/esm/network/session-connection.js.map +1 -1
- package/package.json +1 -1
package/cjs/network/client.d.ts
CHANGED
|
@@ -196,10 +196,11 @@ export declare class MtClient extends EventEmitter {
|
|
|
196
196
|
/** TL writers map used by the client */
|
|
197
197
|
readonly _writerMap: TlWriterMap;
|
|
198
198
|
readonly _config: ConfigManager;
|
|
199
|
-
|
|
199
|
+
private _emitError?;
|
|
200
200
|
readonly log: Logger;
|
|
201
201
|
readonly network: NetworkManager;
|
|
202
202
|
constructor(params: MtClientOptions);
|
|
203
|
+
emitError(err: unknown, connection?: SessionConnection): void;
|
|
203
204
|
private _prepare;
|
|
204
205
|
/**
|
|
205
206
|
* **ADVANCED**
|
package/cjs/network/client.js
CHANGED
|
@@ -43,7 +43,7 @@ class MtClient extends events_1.default {
|
|
|
43
43
|
/** TL writers map used by the client */
|
|
44
44
|
_writerMap;
|
|
45
45
|
_config = new config_manager_js_1.ConfigManager(() => this.call({ _: 'help.getConfig' }));
|
|
46
|
-
|
|
46
|
+
_emitError;
|
|
47
47
|
log;
|
|
48
48
|
network;
|
|
49
49
|
constructor(params) {
|
|
@@ -102,6 +102,14 @@ class MtClient extends events_1.default {
|
|
|
102
102
|
...params.network,
|
|
103
103
|
}, this._config);
|
|
104
104
|
}
|
|
105
|
+
emitError(err, connection) {
|
|
106
|
+
if (this._emitError) {
|
|
107
|
+
this._emitError(err, connection);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
this.log.error('unhandled error:', err);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
105
113
|
_prepare = (0, index_js_1.asyncResettable)(async () => {
|
|
106
114
|
await this.crypto.initialize?.();
|
|
107
115
|
await this.storage.load();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/network/client.ts"],"names":[],"mappings":";;;;;;AAAA,uDAAuD;AACvD,oDAAiC;AAEjC,mCAA+B;AAC/B,2DAA+E;AAC/E,2DAA+E;AAI/E,sDAAkF;AAElF,gDAU0B;AAC1B,2DAAmD;AACnD,6DAAgG;AAsLhG;;;;GAIG;AACH,MAAa,QAAS,SAAQ,gBAAY;IAmCjB;IAlCrB;;OAEG;IACM,MAAM,CAAiB;IAEhC,sBAAsB;IACb,OAAO,CAAgB;IAEhC;;OAEG;IACgB,SAAS,CAAS;IAErC;;;OAGG;IACH,WAAW,CAAW;IAEd,WAAW,CAAS;IAC5B,kCAAkC;IACzB,MAAM,CAAQ;IACvB,wCAAwC;IAC/B,UAAU,CAAa;IAChC,wCAAwC;IAC/B,UAAU,CAAa;IAEvB,OAAO,GAAG,IAAI,iCAAa,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAA;IAE9E,SAAS,GAA2D,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAEtF,GAAG,CAAQ;IACX,OAAO,CAAgB;IAEhC,YAAqB,MAAuB;QACxC,KAAK,EAAE,CAAA;QADU,WAAM,GAAN,MAAM,CAAiB;QAGxC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,IAAI,IAAI,qBAAU,EAAE,CAAA;QAE5C,IAAI,MAAM,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YAChC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,G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AA;QAE9D,+DAA+D;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;IACpD,CAAC;IAED;;;;OAIG;IACH,OAAO,CAAC,OAA+B;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAA;IAC5B,CAAC;CACJ;AAtLD,4BAsLC","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport EventEmitter from 'events'\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 { IMtStorageProvider } from '../storage/provider.js'\nimport { StorageManager, StorageManagerExtraOptions } from '../storage/storage.js'\nimport { MustEqual } from '../types/index.js'\nimport {\n asyncResettable,\n DcOptions,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n ICryptoProvider,\n Logger,\n LogManager,\n} from '../utils/index.js'\nimport { ConfigManager } from './config-manager.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network-manager.js'\nimport { PersistentConnectionParams } from './persistent-connection.js'\nimport { ReconnectionStrategy } from './reconnection.js'\nimport { SessionConnection } from './session-connection.js'\nimport { TransportFactory } from './transports/index.js'\n\n/** Options for {@link MtClient} */\nexport interface MtClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: IMtStorageProvider\n\n /** Additional options for the storage manager */\n storageOptions?: StorageManagerExtraOptions\n\n /**\n * Cryptography provider to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto: ICryptoProvider\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?: 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 * Logger instance for the client.\n * If not passed, a new one will be created.\n */\n logger?: Logger\n\n /**\n * Set logging level for the client.\n * Shorthand for `client.log.level = level`.\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 MTProto client implementation, only doing the bare minimum\n * to make RPC calls and receive low-level updates, as well as providing\n * some APIs to manage that.\n */\nexport class MtClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link MtClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /** Storage manager */\n readonly storage: StorageManager\n\n /**\n * \"Test mode\" taken from {@link MtClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link MtClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n _defaultDcs: 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 readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n emitError: (err: unknown, connection?: SessionConnection) => void = console.error.bind(console)\n\n readonly log: Logger\n readonly network: NetworkManager\n\n constructor(readonly params: MtClientOptions) {\n super()\n\n this.log = params.logger ?? new LogManager()\n\n if (params.logLevel !== undefined) {\n this.log.mgr.level = params.logLevel\n }\n\n this.crypto = params.crypto\n this._testMode = Boolean(params.testMode)\n\n let dc = params.defaultDcs\n\n if (!dc) {\n if (params.testMode) {\n dc = params.useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = params.useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = params.niceStacks ?? true\n\n this._layer = params.overrideLayer ?? tl.LAYER\n this._readerMap = params.readerMap ?? defaultReaderMap\n this._writerMap = params.writerMap ?? defaultWriterMap\n\n this.storage = new StorageManager({\n provider: params.storage,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n ...params.storageOptions,\n })\n\n this.network = new NetworkManager(\n {\n apiId: params.apiId,\n crypto: this.crypto,\n disableUpdates: params.disableUpdates ?? false,\n initConnectionOptions: params.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: params.reconnectionStrategy,\n storage: this.storage,\n testMode: Boolean(params.testMode),\n transport: params.transport,\n emitError: this.emitError.bind(this),\n floodSleepThreshold: params.floodSleepThreshold ?? 10000,\n maxRetryCount: params.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(params.useIpv6),\n enableErrorReporting: params.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n onConnecting: () => this.emit('connecting'),\n onNetworkChanged: (connected) => this.emit('networkChanged', connected),\n onUpdate: (upd) => this.emit('update', upd),\n ...params.network,\n },\n this._config,\n )\n }\n\n private _prepare = asyncResettable(async () => {\n await this.crypto.initialize?.()\n await this.storage.load()\n\n const primaryDc = await this.storage.dcs.fetch()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n })\n\n /**\n * **ADVANCED**\n *\n * Do all the preparations, but don't connect just yet.\n * Useful when you want to do some preparations before\n * connecting, like setting up session.\n *\n * Call {@link connect} to actually connect.\n */\n prepare() {\n return this._prepare.run()\n }\n\n private _connect = asyncResettable(async () => {\n await this._prepare.run()\n await this.network.connect(this._defaultDcs)\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 return this._connect.run()\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this._config.destroy()\n await this.network.destroy()\n\n await this.storage.save()\n await this.storage.destroy?.()\n\n this._prepare.reset()\n this._connect.reset()\n }\n\n /**\n * Make an RPC call.\n *\n * The connection must have been {@link connect}-ed\n * before calling this method.\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 const stack = this._niceStacks ? new Error().stack : undefined\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return this.network.call(message, params, stack)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler Error handler.\n */\n onError(handler: (err: unknown) => void): void {\n this.emitError = handler\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/network/client.ts"],"names":[],"mappings":";;;;;;AAAA,uDAAuD;AACvD,oDAAiC;AAEjC,mCAA+B;AAC/B,2DAA+E;AAC/E,2DAA+E;AAI/E,sDAAkF;AAElF,gDAU0B;AAC1B,2DAAmD;AACnD,6DAAgG;AAsLhG;;;;GAIG;AACH,MAAa,QAAS,SAAQ,gBAAY;IAmCjB;IAlCrB;;OAEG;IACM,MAAM,CAAiB;IAEhC,sBAAsB;IACb,OAAO,CAAgB;IA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CAAA;IAC9B,CAAC;IAEO,QAAQ,GAAG,IAAA,0BAAe,EAAC,KAAK,IAAI,EAAE;QAC1C,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAA;QACzB,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAChD,CAAC,CAAC,CAAA;IAEF;;;;;OAKG;IACH,KAAK,CAAC,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAA;IAC9B,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK;QACP,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAA;QACtB,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAA;QAE5B,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAA;QACzB,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAA;QAE9B,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;QACrB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;IACzB,CAAC;IAED;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,IAAI,CACN,OAAmC,EACnC,MAAuB;QAEvB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;QAE9D,+DAA+D;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;IACpD,CAAC;IAED;;;;OAIG;IACH,OAAO,CAAC,OAA+B;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAA;IAC5B,CAAC;CACJ;AA9LD,4BA8LC","sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport EventEmitter from 'events'\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 { IMtStorageProvider } from '../storage/provider.js'\nimport { StorageManager, StorageManagerExtraOptions } from '../storage/storage.js'\nimport { MustEqual } from '../types/index.js'\nimport {\n asyncResettable,\n DcOptions,\n defaultProductionDc,\n defaultProductionIpv6Dc,\n defaultTestDc,\n defaultTestIpv6Dc,\n ICryptoProvider,\n Logger,\n LogManager,\n} from '../utils/index.js'\nimport { ConfigManager } from './config-manager.js'\nimport { NetworkManager, NetworkManagerExtraParams, RpcCallOptions } from './network-manager.js'\nimport { PersistentConnectionParams } from './persistent-connection.js'\nimport { ReconnectionStrategy } from './reconnection.js'\nimport { SessionConnection } from './session-connection.js'\nimport { TransportFactory } from './transports/index.js'\n\n/** Options for {@link MtClient} */\nexport interface MtClientOptions {\n /**\n * API ID from my.telegram.org\n */\n apiId: number\n /**\n * API hash from my.telegram.org\n */\n apiHash: string\n\n /**\n * Storage to use for this client.\n */\n storage: IMtStorageProvider\n\n /** Additional options for the storage manager */\n storageOptions?: StorageManagerExtraOptions\n\n /**\n * Cryptography provider to allow delegating\n * crypto to native addon, worker, etc.\n */\n crypto: ICryptoProvider\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?: 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 * Logger instance for the client.\n * If not passed, a new one will be created.\n */\n logger?: Logger\n\n /**\n * Set logging level for the client.\n * Shorthand for `client.log.level = level`.\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 MTProto client implementation, only doing the bare minimum\n * to make RPC calls and receive low-level updates, as well as providing\n * some APIs to manage that.\n */\nexport class MtClient extends EventEmitter {\n /**\n * Crypto provider taken from {@link MtClientOptions.crypto}\n */\n readonly crypto: ICryptoProvider\n\n /** Storage manager */\n readonly storage: StorageManager\n\n /**\n * \"Test mode\" taken from {@link MtClientOptions.testMode}\n */\n protected readonly _testMode: boolean\n\n /**\n * Primary DCs taken from {@link MtClientOptions.defaultDcs},\n * loaded from session or changed by other means (like redirecting).\n */\n _defaultDcs: 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 readonly _config = new ConfigManager(() => this.call({ _: 'help.getConfig' }))\n\n private _emitError?: (err: unknown, connection?: SessionConnection) => void\n\n readonly log: Logger\n readonly network: NetworkManager\n\n constructor(readonly params: MtClientOptions) {\n super()\n\n this.log = params.logger ?? new LogManager()\n\n if (params.logLevel !== undefined) {\n this.log.mgr.level = params.logLevel\n }\n\n this.crypto = params.crypto\n this._testMode = Boolean(params.testMode)\n\n let dc = params.defaultDcs\n\n if (!dc) {\n if (params.testMode) {\n dc = params.useIpv6 ? defaultTestIpv6Dc : defaultTestDc\n } else {\n dc = params.useIpv6 ? defaultProductionIpv6Dc : defaultProductionDc\n }\n }\n\n this._defaultDcs = dc\n this._niceStacks = params.niceStacks ?? true\n\n this._layer = params.overrideLayer ?? tl.LAYER\n this._readerMap = params.readerMap ?? defaultReaderMap\n this._writerMap = params.writerMap ?? defaultWriterMap\n\n this.storage = new StorageManager({\n provider: params.storage,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n ...params.storageOptions,\n })\n\n this.network = new NetworkManager(\n {\n apiId: params.apiId,\n crypto: this.crypto,\n disableUpdates: params.disableUpdates ?? false,\n initConnectionOptions: params.initConnectionOptions,\n layer: this._layer,\n log: this.log,\n readerMap: this._readerMap,\n writerMap: this._writerMap,\n reconnectionStrategy: params.reconnectionStrategy,\n storage: this.storage,\n testMode: Boolean(params.testMode),\n transport: params.transport,\n emitError: this.emitError.bind(this),\n floodSleepThreshold: params.floodSleepThreshold ?? 10000,\n maxRetryCount: params.maxRetryCount ?? 5,\n isPremium: false,\n useIpv6: Boolean(params.useIpv6),\n enableErrorReporting: params.enableErrorReporting ?? false,\n onUsable: () => this.emit('usable'),\n onConnecting: () => this.emit('connecting'),\n onNetworkChanged: (connected) => this.emit('networkChanged', connected),\n onUpdate: (upd) => this.emit('update', upd),\n ...params.network,\n },\n this._config,\n )\n }\n\n emitError(err: unknown, connection?: SessionConnection): void {\n if (this._emitError) {\n this._emitError(err, connection)\n } else {\n this.log.error('unhandled error:', err)\n }\n }\n\n private _prepare = asyncResettable(async () => {\n await this.crypto.initialize?.()\n await this.storage.load()\n\n const primaryDc = await this.storage.dcs.fetch()\n if (primaryDc !== null) this._defaultDcs = primaryDc\n })\n\n /**\n * **ADVANCED**\n *\n * Do all the preparations, but don't connect just yet.\n * Useful when you want to do some preparations before\n * connecting, like setting up session.\n *\n * Call {@link connect} to actually connect.\n */\n prepare() {\n return this._prepare.run()\n }\n\n private _connect = asyncResettable(async () => {\n await this._prepare.run()\n await this.network.connect(this._defaultDcs)\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 return this._connect.run()\n }\n\n /**\n * Close all connections and finalize the client.\n */\n async close(): Promise<void> {\n this._config.destroy()\n await this.network.destroy()\n\n await this.storage.save()\n await this.storage.destroy?.()\n\n this._prepare.reset()\n this._connect.reset()\n }\n\n /**\n * Make an RPC call.\n *\n * The connection must have been {@link connect}-ed\n * before calling this method.\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 const stack = this._niceStacks ? new Error().stack : undefined\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return this.network.call(message, params, stack)\n }\n\n /**\n * Register an error handler for the client\n *\n * @param handler Error handler.\n */\n onError(handler: (err: unknown) => void): void {\n this.emitError = handler\n }\n}\n"]}
|
|
@@ -175,6 +175,7 @@ class SessionConnection extends persistent_connection_js_1.PersistentConnection
|
|
|
175
175
|
this._session.resetAuthKey();
|
|
176
176
|
this._resetSession();
|
|
177
177
|
this.emit('key-change', null);
|
|
178
|
+
this.emit('error', error);
|
|
178
179
|
return;
|
|
179
180
|
}
|
|
180
181
|
this.log.error('transport error %d', error.code);
|