build: preparing for publish, moved to strict typescript, fixed some stuff

This commit is contained in:
teidesu 2021-07-30 17:40:50 +03:00
parent 1cf9929e3f
commit a8d3543e64
42 changed files with 139 additions and 150 deletions

View file

@ -3478,14 +3478,14 @@ export class TelegramClient extends BaseTelegramClient {
protected _parseModes: Record<string, IMessageEntityParser> protected _parseModes: Record<string, IMessageEntityParser>
protected _defaultParseMode: string | null protected _defaultParseMode: string | null
protected _updLock: AsyncLock protected _updLock: AsyncLock
protected _pts: number protected _pts?: number
protected _date: number protected _date?: number
protected _seq: number protected _seq?: number
protected _oldPts: number protected _oldPts?: number
protected _oldDate: number protected _oldDate?: number
protected _oldSeq: number protected _oldSeq?: number
protected _selfChanged: boolean protected _selfChanged: boolean
protected _catchUpChannels: boolean protected _catchUpChannels?: boolean
protected _cpts: Record<number, number> protected _cpts: Record<number, number>
protected _cptsMod: Record<number, number> protected _cptsMod: Record<number, number>
constructor(opts: BaseTelegramClient.Options) { constructor(opts: BaseTelegramClient.Options) {

View file

@ -27,20 +27,20 @@ interface UpdatesState {
// accessing storage every time might be expensive, // accessing storage every time might be expensive,
// so store everything here, and load & save // so store everything here, and load & save
// every time session is loaded & saved. // every time session is loaded & saved.
_pts: number _pts?: number
_date: number _date?: number
_seq: number _seq?: number
// old values of the updates state (i.e. as in DB) // old values of the updates state (i.e. as in DB)
// used to avoid redundant storage calls // used to avoid redundant storage calls
_oldPts: number _oldPts?: number
_oldDate: number _oldDate?: number
_oldSeq: number _oldSeq?: number
_selfChanged: boolean _selfChanged: boolean
// whether to catch up channels from the locally stored pts // whether to catch up channels from the locally stored pts
// usually set in start() method based on `catchUp` param // usually set in start() method based on `catchUp` param
_catchUpChannels: boolean _catchUpChannels?: boolean
_cpts: Record<number, number> _cpts: Record<number, number>
_cptsMod: Record<number, number> _cptsMod: Record<number, number>
@ -129,9 +129,9 @@ export async function _saveStorage(
if (this._oldPts === undefined || this._oldPts !== this._pts) if (this._oldPts === undefined || this._oldPts !== this._pts)
await this.storage.setUpdatesPts(this._pts) await this.storage.setUpdatesPts(this._pts)
if (this._oldDate === undefined || this._oldDate !== this._date) if (this._oldDate === undefined || this._oldDate !== this._date)
await this.storage.setUpdatesDate(this._date) await this.storage.setUpdatesDate(this._date!)
if (this._oldSeq === undefined || this._oldSeq !== this._seq) if (this._oldSeq === undefined || this._oldSeq !== this._seq)
await this.storage.setUpdatesSeq(this._seq) await this.storage.setUpdatesSeq(this._seq!)
// update old* values // update old* values
this._oldPts = this._pts this._oldPts = this._pts
@ -399,8 +399,8 @@ async function _loadDifference(
for (;;) { for (;;) {
const diff = await this.call({ const diff = await this.call({
_: 'updates.getDifference', _: 'updates.getDifference',
pts: this._pts, pts: this._pts!,
date: this._date, date: this._date!,
qts: 0, qts: 0,
}) })
@ -631,7 +631,7 @@ export function _handleUpdate(
: update.seq : update.seq
if (seqStart !== 0) { if (seqStart !== 0) {
// https://t.me/tdlibchat/5843 // https://t.me/tdlibchat/5843
const nextLocalSeq = this._seq + 1 const nextLocalSeq = this._seq! + 1
debug( debug(
'received %s (seq_start=%d, seq_end=%d)', 'received %s (seq_start=%d, seq_end=%d)',
@ -680,7 +680,7 @@ export function _handleUpdate(
if (pts !== undefined && ptsCount !== undefined) { if (pts !== undefined && ptsCount !== undefined) {
let nextLocalPts: number | null = null let nextLocalPts: number | null = null
if (channelId === undefined) if (channelId === undefined)
nextLocalPts = this._pts + ptsCount nextLocalPts = this._pts! + ptsCount
else if (channelId in this._cpts) else if (channelId in this._cpts)
nextLocalPts = this._cpts[channelId] + ptsCount nextLocalPts = this._cpts[channelId] + ptsCount
else if (this._catchUpChannels) { else if (this._catchUpChannels) {
@ -770,7 +770,7 @@ export function _handleUpdate(
case 'updateShortMessage': { case 'updateShortMessage': {
if (noDispatch) return if (noDispatch) return
const nextLocalPts = this._pts + update.ptsCount const nextLocalPts = this._pts! + update.ptsCount
if (nextLocalPts > update.pts) if (nextLocalPts > update.pts)
// "the update was already applied, and must be ignored" // "the update was already applied, and must be ignored"
return return
@ -818,7 +818,7 @@ export function _handleUpdate(
case 'updateShortChatMessage': { case 'updateShortChatMessage': {
if (noDispatch) return if (noDispatch) return
const nextLocalPts = this._pts + update.ptsCount const nextLocalPts = this._pts! + update.ptsCount
if (nextLocalPts > update.pts) if (nextLocalPts > update.pts)
// "the update was already applied, and must be ignored" // "the update was already applied, and must be ignored"
return return
@ -867,7 +867,7 @@ export function _handleUpdate(
// only store the new pts and date values // only store the new pts and date values
// we never need to dispatch this // we never need to dispatch this
const nextLocalPts = this._pts + update.ptsCount const nextLocalPts = this._pts! + update.ptsCount
if (nextLocalPts > update.pts) if (nextLocalPts > update.pts)
// "the update was already applied, and must be ignored" // "the update was already applied, and must be ignored"
return return

View file

@ -32,12 +32,12 @@ interface QueuedHandler<T> {
* and synchronize them manually. * and synchronize them manually.
*/ */
export class Conversation { export class Conversation {
private _inputPeer: tl.TypeInputPeer private _inputPeer!: tl.TypeInputPeer
private _chatId: number private _chatId!: number
private _started = false private _started = false
private _lastMessage: number private _lastMessage!: number
private _lastReceivedMessage: number private _lastReceivedMessage!: number
private _queuedNewMessage = new Queue<QueuedHandler<Message>>() private _queuedNewMessage = new Queue<QueuedHandler<Message>>()
private _pendingNewMessages = new Queue<Message>() private _pendingNewMessages = new Queue<Message>()

View file

@ -50,6 +50,9 @@ export class MtqtTypeAssertionError extends MtqtError {
super( super(
`Type assertion error at ${context}: expected ${expected}, but got ${actual}` `Type assertion error at ${context}: expected ${expected}, but got ${actual}`
) )
this.context = context
this.expected = expected
this.actual = actual
} }
} }

View file

@ -10,7 +10,6 @@ import { tdFileId } from '@mtqt/file-id'
export class Audio extends RawDocument { export class Audio extends RawDocument {
readonly type = 'audio' as const readonly type = 'audio' as const
readonly doc: tl.RawDocument
readonly attr: tl.RawDocumentAttributeAudio readonly attr: tl.RawDocumentAttributeAudio
protected _fileIdType(): tdFileId.FileType { protected _fileIdType(): tdFileId.FileType {

View file

@ -14,16 +14,6 @@ export class Photo extends FileLocation {
/** Raw TL object */ /** Raw TL object */
readonly raw: tl.RawPhoto readonly raw: tl.RawPhoto
/**
* Photo size in bytes
*/
readonly fileSize: number
/**
* DC where the photo is stored
*/
readonly dcId: number
/** Biggest available photo width */ /** Biggest available photo width */
readonly width: number readonly width: number

View file

@ -31,16 +31,6 @@ export class Thumbnail extends FileLocation {
static readonly THUMB_STRIP = 'i' static readonly THUMB_STRIP = 'i'
static readonly THUMB_OUTLINE = 'j' static readonly THUMB_OUTLINE = 'j'
/**
* Thumbnail size in bytes
*/
readonly fileSize: number
/**
* DC where the thumbnail is stored
*/
readonly dcId: number
readonly raw: tl.TypePhotoSize readonly raw: tl.TypePhotoSize
/** /**
@ -177,7 +167,7 @@ export class Thumbnail extends FileLocation {
if (this._media._ === 'stickerSet') { if (this._media._ === 'stickerSet') {
this._fileId = toFileId({ this._fileId = toFileId({
type: td.FileType.Thumbnail, type: td.FileType.Thumbnail,
dcId: this.dcId, dcId: this.dcId!,
fileReference: null, fileReference: null,
location: { location: {
_: 'photo', _: 'photo',
@ -197,7 +187,7 @@ export class Thumbnail extends FileLocation {
this._media._ === 'photo' this._media._ === 'photo'
? td.FileType.Photo ? td.FileType.Photo
: td.FileType.Thumbnail, : td.FileType.Thumbnail,
dcId: this.dcId, dcId: this.dcId!,
fileReference: this._media.fileReference, fileReference: this._media.fileReference,
location: { location: {
_: 'photo', _: 'photo',

View file

@ -39,7 +39,7 @@ export class Venue {
this.raw = raw this.raw = raw
} }
private _location: Location private _location?: Location
/** /**
* Geolocation of the venue * Geolocation of the venue
*/ */

View file

@ -11,7 +11,6 @@ import { decodeWaveform } from '../../utils/voice-utils'
export class Voice extends RawDocument { export class Voice extends RawDocument {
readonly type = 'voice' as const readonly type = 'voice' as const
readonly doc: tl.RawDocument
readonly attr: tl.RawDocumentAttributeAudio readonly attr: tl.RawDocumentAttributeAudio
protected _fileIdType(): tdFileId.FileType { protected _fileIdType(): tdFileId.FileType {

View file

@ -68,26 +68,26 @@ export class MessageEntity {
/** /**
* Underlying raw TL object * Underlying raw TL object
*/ */
readonly raw: tl.TypeMessageEntity readonly raw!: tl.TypeMessageEntity
/** /**
* Type of the entity. See {@link MessageEntity.Type} for a list of possible values * Type of the entity. See {@link MessageEntity.Type} for a list of possible values
*/ */
readonly type: MessageEntity.Type readonly type!: MessageEntity.Type
/** /**
* Offset in UTF-16 code units to the start of the entity. * Offset in UTF-16 code units to the start of the entity.
* *
* Since JS strings are UTF-16, you can use this as-is * Since JS strings are UTF-16, you can use this as-is
*/ */
readonly offset: number readonly offset!: number
/** /**
* Length of the entity in UTF-16 code units. * Length of the entity in UTF-16 code units.
* *
* Since JS strings are UTF-16, you can use this as-is * Since JS strings are UTF-16, you can use this as-is
*/ */
readonly length: number readonly length!: number
/** /**
* When `type=text_link`, contains the URL that would be opened if user taps on the text * When `type=text_link`, contains the URL that would be opened if user taps on the text

View file

@ -363,7 +363,7 @@ export class Message {
return this.raw.mentioned! return this.raw.mentioned!
} }
private _viaBot: User | null private _viaBot?: User | null
/** /**
* If this message is generated from an inline query, * If this message is generated from an inline query,
* information about the bot which generated it * information about the bot which generated it

View file

@ -30,27 +30,27 @@ import { tl } from '@mtqt/tl'
* - `Pinned`: Search for pinned messages * - `Pinned`: Search for pinned messages
*/ */
export const SearchFilters = { export const SearchFilters = {
Empty: { _: 'inputMessagesFilterEmpty' } as tl.TypeMessagesFilter, Empty: { _: 'inputMessagesFilterEmpty' } as const,
Photo: { _: 'inputMessagesFilterPhotos' } as tl.TypeMessagesFilter, Photo: { _: 'inputMessagesFilterPhotos' } as const,
Video: { _: 'inputMessagesFilterVideo' } as tl.TypeMessagesFilter, Video: { _: 'inputMessagesFilterVideo' } as const,
PhotoAndVideo: { PhotoAndVideo: {
_: 'inputMessagesFilterPhotoVideo', _: 'inputMessagesFilterPhotoVideo',
} as tl.TypeMessagesFilter, } as const,
Document: { _: 'inputMessagesFilterDocument' } as tl.TypeMessagesFilter, Document: { _: 'inputMessagesFilterDocument' } as const,
Url: { _: 'inputMessagesFilterUrl' } as tl.TypeMessagesFilter, Url: { _: 'inputMessagesFilterUrl' } as const,
Gif: { _: 'inputMessagesFilterGif' } as tl.TypeMessagesFilter, Gif: { _: 'inputMessagesFilterGif' } as const,
Voice: { _: 'inputMessagesFilterVoice' } as tl.TypeMessagesFilter, Voice: { _: 'inputMessagesFilterVoice' } as const,
Audio: { _: 'inputMessagesFilterMusic' } as tl.TypeMessagesFilter, Audio: { _: 'inputMessagesFilterMusic' } as const,
ChatPhotoChange: { ChatPhotoChange: {
_: 'inputMessagesFilterChatPhotos', _: 'inputMessagesFilterChatPhotos',
} as tl.TypeMessagesFilter, } as const,
Call: { _: 'inputMessagesFilterPhoneCalls' } as tl.TypeMessagesFilter, Call: { _: 'inputMessagesFilterPhoneCalls' } as const,
Round: { _: 'inputMessagesFilterRoundVideo' } as tl.TypeMessagesFilter, Round: { _: 'inputMessagesFilterRoundVideo' } as const,
RoundAndVoice: { RoundAndVoice: {
_: 'inputMessagesFilterRoundVoice', _: 'inputMessagesFilterRoundVoice',
} as tl.TypeMessagesFilter, } as const,
MyMention: { _: 'inputMessagesFilterMyMentions' } as tl.TypeMessagesFilter, MyMention: { _: 'inputMessagesFilterMyMentions' } as const,
Location: { _: 'inputMessagesFilterGeo' } as tl.TypeMessagesFilter, Location: { _: 'inputMessagesFilterGeo' } as const,
Contact: { _: 'inputMessagesFilterContacts' } as tl.TypeMessagesFilter, Contact: { _: 'inputMessagesFilterContacts' } as const,
Pinned: { _: 'inputMessagesFilterPinned' } as tl.TypeMessagesFilter, Pinned: { _: 'inputMessagesFilterPinned' } as const,
} as const } as const

View file

@ -148,7 +148,7 @@ export class ChatPhoto {
return this._smallFile return this._smallFile
} }
private _bigFile: ChatPhotoSize private _bigFile?: ChatPhotoSize
/** Chat photo file location in big resolution (640x640) */ /** Chat photo file location in big resolution (640x640) */
get big(): ChatPhotoSize { get big(): ChatPhotoSize {
if (!this._bigFile) { if (!this._bigFile) {

View file

@ -33,7 +33,7 @@ export class PollUpdate {
return this.raw.pollId return this.raw.pollId
} }
private _poll: Poll private _poll?: Poll
/** /**
* The poll. * The poll.
* *

View file

@ -113,7 +113,7 @@ export class UserTypingUpdate {
} }
/** /**
* Fetch the chat where the update has happenned * Fetch the chat where the update has happened
*/ */
getChat(): Promise<Chat> { getChat(): Promise<Chat> {
return this.client.getChat(this.chatId) return this.client.getChat(this.chatId)

View file

@ -30,7 +30,7 @@ function getAllGettersNames(obj: object): string[] {
} }
const bufferToJsonOriginal = (Buffer as any).toJSON const bufferToJsonOriginal = (Buffer as any).toJSON
const bufferToJsonInspect = function () { return this.toString('base64') } const bufferToJsonInspect = function (this: Buffer) { return this.toString('base64') }
/** /**
* Small helper function that adds `toJSON` and `util.custom.inspect` * Small helper function that adds `toJSON` and `util.custom.inspect`

View file

@ -235,7 +235,7 @@ export class BaseTelegramClient extends EventEmitter {
private _niceStacks: boolean private _niceStacks: boolean
readonly _layer: number readonly _layer: number
private _keepAliveInterval: NodeJS.Timeout private _keepAliveInterval?: NodeJS.Timeout
private _lastRequestTime = 0 private _lastRequestTime = 0
private _floodWaitedRequests: Record<string, number> = {} private _floodWaitedRequests: Record<string, number> = {}
@ -255,7 +255,7 @@ export class BaseTelegramClient extends EventEmitter {
* *
* Methods for downloading/uploading files may create additional connections as needed. * Methods for downloading/uploading files may create additional connections as needed.
*/ */
primaryConnection: TelegramConnection primaryConnection!: TelegramConnection
private _importFrom?: string private _importFrom?: string

View file

@ -25,7 +25,7 @@ export interface PersistentConnectionParams {
*/ */
export abstract class PersistentConnection extends EventEmitter { export abstract class PersistentConnection extends EventEmitter {
readonly params: PersistentConnectionParams readonly params: PersistentConnectionParams
private _transport: ITelegramTransport private _transport!: ITelegramTransport
private _sendOnceConnected: Buffer[] = [] private _sendOnceConnected: Buffer[] = []

View file

@ -14,7 +14,7 @@ export type ReconnectionStrategy<T> = (
* default reconnection strategy: first - immediate reconnection, * default reconnection strategy: first - immediate reconnection,
* then 1s with linear increase up to 5s (with 1s step) * then 1s with linear increase up to 5s (with 1s step)
*/ */
export const defaultReconnectionStrategy: ReconnectionStrategy<never> = ( export const defaultReconnectionStrategy: ReconnectionStrategy<any> = (
params, params,
lastError, lastError,
consequentFails, consequentFails,

View file

@ -75,7 +75,7 @@ interface PendingMessage {
// TODO: error handling basically everywhere, most importantly (de-)serialization errors // TODO: error handling basically everywhere, most importantly (de-)serialization errors
// noinspection JSUnusedLocalSymbols // noinspection JSUnusedLocalSymbols
export class TelegramConnection extends PersistentConnection { export class TelegramConnection extends PersistentConnection {
readonly params: TelegramConnectionParams readonly params!: TelegramConnectionParams
private readonly _mtproto: MtprotoSession private readonly _mtproto: MtprotoSession

View file

@ -19,7 +19,7 @@ export abstract class BaseTcpTransport
protected _socket: Socket | null = null protected _socket: Socket | null = null
abstract _packetCodec: IPacketCodec abstract _packetCodec: IPacketCodec
protected _crypto: ICryptoProvider protected _crypto!: ICryptoProvider
packetCodecInitialized = false packetCodecInitialized = false

View file

@ -40,7 +40,7 @@ export abstract class BaseWebSocketTransport
private _currentDc: tl.RawDcOption | null = null private _currentDc: tl.RawDcOption | null = null
private _state: TransportState = TransportState.Idle private _state: TransportState = TransportState.Idle
private _socket: WebSocket | null = null private _socket: WebSocket | null = null
private _crypto: ICryptoProvider private _crypto!: ICryptoProvider
abstract _packetCodec: IPacketCodec abstract _packetCodec: IPacketCodec
packetCodecInitialized = false packetCodecInitialized = false

View file

@ -3,7 +3,7 @@ import { IPacketCodec } from './abstract'
import { ICryptoProvider } from '../../utils/crypto' import { ICryptoProvider } from '../../utils/crypto'
export abstract class WrappedCodec extends EventEmitter { export abstract class WrappedCodec extends EventEmitter {
protected _crypto: ICryptoProvider protected _crypto!: ICryptoProvider
protected _inner: IPacketCodec protected _inner: IPacketCodec
constructor(inner: IPacketCodec) { constructor(inner: IPacketCodec) {

View file

@ -15,7 +15,7 @@ export class JsonFileStorage extends JsonMemoryStorage {
private readonly _safe: boolean private readonly _safe: boolean
private readonly _cleanup: boolean private readonly _cleanup: boolean
private readonly _unsubscribe: () => void private readonly _unsubscribe?: () => void
constructor( constructor(
filename: string, filename: string,
@ -114,7 +114,7 @@ export class JsonFileStorage extends JsonMemoryStorage {
destroy(): void { destroy(): void {
if (this._cleanup) { if (this._cleanup) {
this._unsubscribe() this._unsubscribe!()
} }
} }
} }

View file

@ -35,8 +35,8 @@ export class JsonMemoryStorage extends MemoryStorage {
return Object.entries(value) return Object.entries(value)
.filter((it) => it[1] !== null) .filter((it) => it[1] !== null)
.map( .map(
([dcId, key]: [string, Buffer]) => ([dcId, key]) =>
dcId + ',' + key.toString('base64') dcId + ',' + (key as Buffer).toString('base64')
) )
.join('|') .join('|')
} }

View file

@ -52,12 +52,12 @@ interface MemorySessionState {
const USERNAME_TTL = 86400000 // 24 hours const USERNAME_TTL = 86400000 // 24 hours
export class MemoryStorage implements ITelegramStorage /*, IStateStorage */ { export class MemoryStorage implements ITelegramStorage /*, IStateStorage */ {
protected _state: MemorySessionState protected _state!: MemorySessionState
private _cachedInputPeers: LruMap<number, tl.TypeInputPeer> = new LruMap(100) private _cachedInputPeers: LruMap<number, tl.TypeInputPeer> = new LruMap(100)
private _cachedFull: LruMap<number, tl.TypeUser | tl.TypeChat> private _cachedFull: LruMap<number, tl.TypeUser | tl.TypeChat>
private _vacuumTimeout: NodeJS.Timeout private _vacuumTimeout?: NodeJS.Timeout
private _vacuumInterval: number private _vacuumInterval: number
constructor(params?: { constructor(params?: {
@ -96,7 +96,7 @@ export class MemoryStorage implements ITelegramStorage /*, IStateStorage */ {
} }
destroy(): void { destroy(): void {
clearInterval(this._vacuumTimeout) clearInterval(this._vacuumTimeout!)
} }
reset(): void { reset(): void {

View file

@ -57,14 +57,14 @@ export class Dispatcher<State = never, SceneName extends string = string> {
private _client?: TelegramClient private _client?: TelegramClient
private _parent?: Dispatcher<any> private _parent?: Dispatcher<any>
private _children: Dispatcher<any>[] = [] private _children: Dispatcher<any, any>[] = []
private _scenes: Record<string, Dispatcher<any, SceneName>> private _scenes?: Record<string, Dispatcher<any, SceneName>>
private _scene?: SceneName private _scene?: SceneName
private _sceneScoped?: boolean private _sceneScoped?: boolean
private _storage: State extends never ? undefined : IStateStorage private _storage?: State extends never ? undefined : IStateStorage
private _stateKeyDelegate: State extends never private _stateKeyDelegate?: State extends never
? undefined ? undefined
: StateKeyDelegate : StateKeyDelegate
@ -437,7 +437,7 @@ export class Dispatcher<State = never, SceneName extends string = string> {
'Cannot use ToScene without entering a scene' 'Cannot use ToScene without entering a scene'
) )
return this._scenes[ return this._scenes![
scene scene
]._dispatchUpdateNowImpl( ]._dispatchUpdateNowImpl(
update, update,
@ -643,7 +643,7 @@ export class Dispatcher<State = never, SceneName extends string = string> {
return this._parent ?? null return this._parent ?? null
} }
private _prepareChild(child: Dispatcher<any>): void { private _prepareChild(child: Dispatcher<any, any>): void {
if (child._client) { if (child._client) {
throw new MtqtArgumentError( throw new MtqtArgumentError(
'Provided dispatcher is ' + 'Provided dispatcher is ' +
@ -756,7 +756,7 @@ export class Dispatcher<State = never, SceneName extends string = string> {
* *
* @param child Other dispatcher * @param child Other dispatcher
*/ */
removeChild(child: Dispatcher): void { removeChild(child: Dispatcher<any, any>): void {
const idx = this._children.indexOf(child) const idx = this._children.indexOf(child)
if (idx > -1) { if (idx > -1) {
child._unparent() child._unparent()
@ -812,17 +812,19 @@ export class Dispatcher<State = never, SceneName extends string = string> {
}) })
if (other._scenes) { if (other._scenes) {
if (!this._scenes) this._scenes = {}
Object.keys(other._scenes).forEach((key) => { Object.keys(other._scenes).forEach((key) => {
other._scenes[key]._unparent() other._scenes![key]._unparent()
if (key in this._scenes) { if (key in this._scenes!) {
// will be overwritten // will be overwritten
delete this._scenes[key] delete this._scenes![key]
} }
this.addScene( this.addScene(
key as any, key as any,
other._scenes[key] as any, other._scenes![key] as any,
other._scenes[key]._sceneScoped as any other._scenes![key]._sceneScoped as any
) )
}) })
} }
@ -851,11 +853,11 @@ export class Dispatcher<State = never, SceneName extends string = string> {
dp._groups[idx] = {} as any dp._groups[idx] = {} as any
Object.keys(this._groups[idx]).forEach( Object.keys(this._groups[idx]).forEach((type) => {
(type: UpdateHandler['name']) => { dp._groups[idx][type as UpdateHandler['name']] = [
dp._groups[idx][type] = [...this._groups[idx][type]] ...this._groups[idx][type as UpdateHandler['name']],
} ]
) })
}) })
dp._groupsOrder = [...this._groupsOrder] dp._groupsOrder = [...this._groupsOrder]
@ -871,11 +873,11 @@ export class Dispatcher<State = never, SceneName extends string = string> {
if (this._scenes) { if (this._scenes) {
Object.keys(this._scenes).forEach((key) => { Object.keys(this._scenes).forEach((key) => {
const scene = this._scenes[key].clone(true) const scene = this._scenes![key].clone(true)
dp.addScene( dp.addScene(
key as any, key as any,
scene as any, scene as any,
this._scenes[key]._sceneScoped as any this._scenes![key]._sceneScoped as any
) )
}) })
} }
@ -1004,16 +1006,19 @@ export class Dispatcher<State = never, SceneName extends string = string> {
group?: number group?: number
): void { ): void {
if (typeof handler === 'number') { if (typeof handler === 'number') {
this.addUpdateHandler({ this.addUpdateHandler(
name, {
callback: filter name,
}, handler) callback: filter,
},
handler
)
} else { } else {
this.addUpdateHandler( this.addUpdateHandler(
{ {
name, name,
callback: handler, callback: handler,
check: filter check: filter,
}, },
group group
) )
@ -1026,10 +1031,7 @@ export class Dispatcher<State = never, SceneName extends string = string> {
* @param handler Raw update handler * @param handler Raw update handler
* @param group Handler group index * @param group Handler group index
*/ */
onRawUpdate( onRawUpdate(handler: RawUpdateHandler['callback'], group?: number): void
handler: RawUpdateHandler['callback'],
group?: number
): void
/** /**
* Register a raw update handler without any filters * Register a raw update handler without any filters

View file

@ -253,12 +253,12 @@ export namespace filters {
* *
* @param fns Filters to combine * @param fns Filters to combine
*/ */
export function every<Filters extends UpdateFilter<T, any>[], T>( export function every<Filters extends UpdateFilter<any, any>[]>(
...fns: Filters ...fns: Filters
): UpdateFilter< ): UpdateFilter<
ExtractBase<Filters[0]>, UnionToIntersection<ExtractBase<Filters[number]>>,
UnionToIntersection< UnionToIntersection<
ExtractMod<ExtractBase<Filters[0]>, Filters[number]> ExtractMod<ExtractBase<Filters[number]>, Filters[number]>
> >
> { > {
if (fns.length === 2) return and(fns[0], fns[1]) if (fns.length === 2) return and(fns[0], fns[1])
@ -301,11 +301,11 @@ export namespace filters {
* *
* @param fns Filters to combine * @param fns Filters to combine
*/ */
export function some<Filters extends UpdateFilter<T, any>[], T>( export function some<Filters extends UpdateFilter<any, any>[]>(
...fns: Filters ...fns: Filters
): UpdateFilter< ): UpdateFilter<
ExtractBase<Filters[0]>, UnionToIntersection<ExtractBase<Filters[number]>>,
ExtractMod<ExtractBase<Filters[0]>, Filters[number]> ExtractMod<ExtractBase<Filters[number]>, Filters[number]>
> { > {
if (fns.length === 2) return or(fns[0], fns[1]) if (fns.length === 2) return or(fns[0], fns[1])
@ -1034,7 +1034,9 @@ export namespace filters {
params: MaybeArray<string | RegExp> params: MaybeArray<string | RegExp>
): UpdateFilter<Message, { command: string[] }> => { ): UpdateFilter<Message, { command: string[] }> => {
if (!Array.isArray(params)) { if (!Array.isArray(params)) {
return and(start, (msg: Message & { command: string[] }) => { return and(start, (_msg: Message) => {
const msg = _msg as Message & { command: string[] }
if (msg.command.length !== 2) return false if (msg.command.length !== 2) return false
const p = msg.command[1] const p = msg.command[1]
@ -1048,7 +1050,9 @@ export namespace filters {
}) })
} }
return and(start, (msg: Message & { command: string[] }) => { return and(start, (_msg: Message) => {
const msg = _msg as Message & { command: string[] }
if (msg.command.length !== 2) return false if (msg.command.length !== 2) return false
const p = msg.command[1] const p = msg.command[1]

View file

@ -19,7 +19,7 @@ export class RateLimitError extends MtqtError {
*/ */
export class UpdateState<State, SceneName extends string = string> { export class UpdateState<State, SceneName extends string = string> {
private _key: string private _key: string
private _localKey: string private _localKey!: string
private _storage: IStateStorage private _storage: IStateStorage

View file

@ -7,9 +7,9 @@
"./src" "./src"
], ],
"typedocOptions": { "typedocOptions": {
"name": "@mtqt/client", "name": "@mtqt/dispatcher",
"includeVersion": true, "includeVersion": true,
"out": "../../docs/packages/client", "out": "../../docs/packages/dispatcher",
"listInvalidSymbolLinks": true, "listInvalidSymbolLinks": true,
"excludePrivate": true, "excludePrivate": true,
"entryPoints": [ "entryPoints": [

View file

@ -2,8 +2,8 @@ import {
IntermediatePacketCodec, IntermediatePacketCodec,
BaseTcpTransport, BaseTcpTransport,
TransportState, TransportState,
tl
} from '@mtqt/core' } from '@mtqt/core'
import { tl } from '@mtqt/tl'
import { connect as connectTcp } from 'net' import { connect as connectTcp } from 'net'
import { connect as connectTls, SecureContextOptions } from 'tls' import { connect as connectTls, SecureContextOptions } from 'tls'

View file

@ -1,6 +1,5 @@
import { TelegramClient, User } from '@mtqt/client' import { TelegramClient, User } from '@mtqt/client'
import { BaseTelegramClient } from '@mtqt/core' import { BaseTelegramClient } from '@mtqt/core'
import type { NodeNativeCryptoProvider } from '@mtqt/crypto-node'
import { HtmlMessageEntityParser } from '@mtqt/html-parser' import { HtmlMessageEntityParser } from '@mtqt/html-parser'
import { MarkdownMessageEntityParser } from '@mtqt/markdown-parser' import { MarkdownMessageEntityParser } from '@mtqt/markdown-parser'
import { SqliteStorage } from '@mtqt/sqlite' import { SqliteStorage } from '@mtqt/sqlite'
@ -12,7 +11,7 @@ export * from '@mtqt/html-parser'
export * from '@mtqt/markdown-parser' export * from '@mtqt/markdown-parser'
export { SqliteStorage } export { SqliteStorage }
let nativeCrypto: typeof NodeNativeCryptoProvider | null let nativeCrypto: any
try { try {
nativeCrypto = require('@mtqt/crypto-node').NodeNativeCryptoProvider nativeCrypto = require('@mtqt/crypto-node').NodeNativeCryptoProvider
} catch (e) {} } catch (e) {}
@ -52,7 +51,7 @@ export namespace NodeTelegramClient {
export class NodeTelegramClient extends TelegramClient { export class NodeTelegramClient extends TelegramClient {
constructor(opts: NodeTelegramClient.Options) { constructor(opts: NodeTelegramClient.Options) {
super({ super({
crypto: nativeCrypto ? () => new nativeCrypto!() : undefined, crypto: nativeCrypto ? () => new nativeCrypto() : undefined,
...opts, ...opts,
storage: storage:
typeof opts.storage === 'string' typeof opts.storage === 'string'

View file

@ -12,6 +12,7 @@
"build": "tsc" "build": "tsc"
}, },
"dependencies": { "dependencies": {
"@mtqt/core": "^1.0.0",
"@mtqt/client": "^1.0.0", "@mtqt/client": "^1.0.0",
"@mtqt/sqlite": "^1.0.0", "@mtqt/sqlite": "^1.0.0",
"@mtqt/markdown-parser": "^1.0.0", "@mtqt/markdown-parser": "^1.0.0",

View file

@ -13,7 +13,7 @@
"listInvalidSymbolLinks": true, "listInvalidSymbolLinks": true,
"excludePrivate": true, "excludePrivate": true,
"entryPoints": [ "entryPoints": [
"./src/index.ts" "./index.ts"
] ]
} }
} }

View file

@ -2,8 +2,8 @@ import {
IntermediatePacketCodec, IntermediatePacketCodec,
BaseTcpTransport, BaseTcpTransport,
TransportState, TransportState,
tl
} from '@mtqt/core' } from '@mtqt/core'
import { tl } from '@mtqt/tl'
import { connect } from 'net' import { connect } from 'net'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // @ts-ignore

View file

@ -161,8 +161,8 @@ const EMPTY_BUFFER = Buffer.alloc(0)
* Uses `better-sqlite3` library * Uses `better-sqlite3` library
*/ */
export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ { export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ {
private _db: sqlite3.Database private _db!: sqlite3.Database
private _statements: Record<keyof typeof STATEMENTS, sqlite3.Statement> private _statements!: Record<keyof typeof STATEMENTS, sqlite3.Statement>
private readonly _filename: string private readonly _filename: string
private _pending: [sqlite3.Statement, any[]][] = [] private _pending: [sqlite3.Statement, any[]][] = []
@ -178,7 +178,7 @@ export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ {
private _saveUnimportantLater: () => void private _saveUnimportantLater: () => void
private _vacuumTimeout: NodeJS.Timeout private _vacuumTimeout?: NodeJS.Timeout
private _vacuumInterval: number private _vacuumInterval: number
/** /**
@ -343,8 +343,8 @@ export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ {
} }
} }
private _runMany: (stmts: [sqlite3.Statement, any[]][]) => void private _runMany!: (stmts: [sqlite3.Statement, any[]][]) => void
private _updateManyPeers: (updates: any[]) => void private _updateManyPeers!: (updates: any[]) => void
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
private _upgradeDatabase(from: number): void { private _upgradeDatabase(from: number): void {
@ -430,7 +430,7 @@ export class SqliteStorage implements ITelegramStorage /*, IStateStorage */ {
destroy(): void { destroy(): void {
this._db.close() this._db.close()
clearInterval(this._vacuumTimeout) clearInterval(this._vacuumTimeout!)
} }
reset(): void { reset(): void {

View file

@ -13,7 +13,7 @@
"listInvalidSymbolLinks": true, "listInvalidSymbolLinks": true,
"excludePrivate": true, "excludePrivate": true,
"entryPoints": [ "entryPoints": [
"./src/index.ts" "./index.ts"
] ]
} }
} }

View file

@ -57,7 +57,8 @@ export interface ITlBinaryWriter {
export type TlBinaryWriterFunction = ( export type TlBinaryWriterFunction = (
this: ITlBinaryWriter, this: ITlBinaryWriter,
obj: unknown obj: unknown,
bare?: boolean
) => void ) => void
/** /**

View file

@ -16,7 +16,6 @@
"big-integer": "^1.6.48" "big-integer": "^1.6.48"
}, },
"devDependencies": { "devDependencies": {
"@mtqt/core": "^1.0.0",
"cheerio": "^1.0.0-rc.5", "cheerio": "^1.0.0-rc.5",
"eager-async-pool": "^1.0.0", "eager-async-pool": "^1.0.0",
"csv-parser": "^3.0.0", "csv-parser": "^3.0.0",

View file

@ -1,10 +1,10 @@
// generates fingerprints for public keys. // generates fingerprints for public keys.
// since they are rarely changed, not included in `generate-code` npm script // since they are rarely changed, not included in `generate-code` npm script
// keys can still be added at runtime, this is just an optimization // keys can still be added at runtime, this is just an optimization
const { parsePublicKey } = require('@mtqt/core/dist/utils/crypto/keys') const { parsePublicKey } = require('../../core/dist/utils/crypto/keys')
const { const {
NodeCryptoProvider, NodeCryptoProvider,
} = require('@mtqt/core/dist/utils/crypto/node-crypto') } = require('../../core/dist/utils/crypto/node-crypto')
const { createWriter } = require('./common') const { createWriter } = require('./common')
// https://github.com/DrKLO/Telegram/blob/a724d96e9c008b609fe188d122aa2922e40de5fc/TMessagesProj/jni/tgnet/Handshake.cpp#L356-L436 // https://github.com/DrKLO/Telegram/blob/a724d96e9c008b609fe188d122aa2922e40de5fc/TMessagesProj/jni/tgnet/Handshake.cpp#L356-L436

View file

@ -21,6 +21,7 @@ import { BigInteger } from 'big-integer';
* - you can use \`{ _: 'error', ... }\` to create needed types * - you can use \`{ _: 'error', ... }\` to create needed types
* - to check if something is of some type, check \`_\` property of an object * - to check if something is of some type, check \`_\` property of an object
* - to check if something is of some union, use \`isAny*()\` functions * - to check if something is of some union, use \`isAny*()\` functions
* @hidden
*/ */
export declare namespace tl { export declare namespace tl {
/** /**

View file

@ -9,8 +9,9 @@
"baseUrl": ".", "baseUrl": ".",
"declaration": true, "declaration": true,
"esModuleInterop": true, "esModuleInterop": true,
"strictNullChecks": true, "strict": true,
"noImplicitAny": true, "noImplicitAny": true,
"noImplicitThis": true,
"incremental": true, "incremental": true,
"stripInternal": true "stripInternal": true
}, },