@mtcute/test 0.1.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/LICENSE +8 -0
- package/README.md +5 -0
- package/cjs/client.d.ts +43 -0
- package/cjs/client.js +217 -0
- package/cjs/client.js.map +1 -0
- package/cjs/index.d.ts +5 -0
- package/cjs/index.js +22 -0
- package/cjs/index.js.map +1 -0
- package/cjs/package.json +3 -0
- package/cjs/schema.d.ts +1 -0
- package/cjs/schema.js +32 -0
- package/cjs/schema.js.map +1 -0
- package/cjs/storage.d.ts +50 -0
- package/cjs/storage.js +58 -0
- package/cjs/storage.js.map +1 -0
- package/cjs/stub.d.ts +2 -0
- package/cjs/stub.js +71 -0
- package/cjs/stub.js.map +1 -0
- package/cjs/transport.d.ts +30 -0
- package/cjs/transport.js +52 -0
- package/cjs/transport.js.map +1 -0
- package/cjs/types.d.ts +8 -0
- package/cjs/types.js +3 -0
- package/cjs/types.js.map +1 -0
- package/cjs/utils.d.ts +2 -0
- package/cjs/utils.js +18 -0
- package/cjs/utils.js.map +1 -0
- package/esm/client.d.ts +43 -0
- package/esm/client.js +213 -0
- package/esm/client.js.map +1 -0
- package/esm/index.d.ts +5 -0
- package/esm/index.js +6 -0
- package/esm/index.js.map +1 -0
- package/esm/schema.d.ts +1 -0
- package/esm/schema.js +28 -0
- package/esm/schema.js.map +1 -0
- package/esm/storage.d.ts +50 -0
- package/esm/storage.js +54 -0
- package/esm/storage.js.map +1 -0
- package/esm/stub.d.ts +2 -0
- package/esm/stub.js +64 -0
- package/esm/stub.js.map +1 -0
- package/esm/transport.d.ts +30 -0
- package/esm/transport.js +45 -0
- package/esm/transport.js.map +1 -0
- package/esm/types.d.ts +8 -0
- package/esm/types.js +2 -0
- package/esm/types.js.map +1 -0
- package/esm/utils.d.ts +2 -0
- package/esm/utils.js +14 -0
- package/esm/utils.js.map +1 -0
- package/package.json +24 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Copyright 2023 Alina Sireneva
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
8
|
+
|
package/README.md
ADDED
package/cjs/client.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { BaseTelegramClient, BaseTelegramClientOptions, MaybeAsync, MustEqual, RpcCallOptions, tl } from '@mtcute/core';
|
|
2
|
+
import { InputResponder } from './types.js';
|
|
3
|
+
interface MessageBox {
|
|
4
|
+
pts: number;
|
|
5
|
+
lastMessageId: number;
|
|
6
|
+
}
|
|
7
|
+
type InputPeerId = number | tl.TypePeer | false | undefined;
|
|
8
|
+
export declare class StubTelegramClient extends BaseTelegramClient {
|
|
9
|
+
constructor(params?: Partial<BaseTelegramClientOptions>);
|
|
10
|
+
readonly _knownChats: Map<number, tl.TypeChat>;
|
|
11
|
+
readonly _knownUsers: Map<number, tl.TypeUser>;
|
|
12
|
+
_selfId: number;
|
|
13
|
+
registerChat(chat: tl.TypeChat | tl.TypeChat[]): void;
|
|
14
|
+
registerUser(user: tl.TypeUser | tl.TypeUser[]): void;
|
|
15
|
+
getPeers(ids: InputPeerId[]): {
|
|
16
|
+
users: tl.TypeUser[];
|
|
17
|
+
chats: tl.TypeChat[];
|
|
18
|
+
};
|
|
19
|
+
private _onRawMessage?;
|
|
20
|
+
onRawMessage(fn: (data: Uint8Array) => void): void;
|
|
21
|
+
private _responders;
|
|
22
|
+
addResponder<T extends tl.RpcMethod['_']>(responders: InputResponder<T>): void;
|
|
23
|
+
respondWith<T extends tl.RpcMethod['_']>(method: T, response: tl.RpcCallReturn[T] | ((data: tl.FindByName<tl.RpcMethod, T>) => tl.RpcCallReturn[T])): void;
|
|
24
|
+
call<T extends tl.RpcMethod>(message: MustEqual<T, tl.RpcMethod>, params?: RpcCallOptions): Promise<tl.RpcCallReturn[T['_']]>;
|
|
25
|
+
private _fakeMessageBoxes;
|
|
26
|
+
private _lastQts;
|
|
27
|
+
private _lastDate;
|
|
28
|
+
private _lastSeq;
|
|
29
|
+
getMessageBox(chatId?: number): MessageBox;
|
|
30
|
+
getNextMessageId(chatId?: number): number;
|
|
31
|
+
getNextPts(chatId?: number, count?: number): number;
|
|
32
|
+
getNextQts(): number;
|
|
33
|
+
getNextDate(): number;
|
|
34
|
+
createStubUpdates(params: {
|
|
35
|
+
updates: tl.TypeUpdate[];
|
|
36
|
+
peers?: (number | tl.TypePeer)[];
|
|
37
|
+
seq?: number;
|
|
38
|
+
seqCount?: number;
|
|
39
|
+
}): tl.TypeUpdates;
|
|
40
|
+
connectAndWait(): Promise<void>;
|
|
41
|
+
with(fn: () => MaybeAsync<void>): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
export {};
|
package/cjs/client.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StubTelegramClient = void 0;
|
|
4
|
+
const core_1 = require("@mtcute/core");
|
|
5
|
+
const storage_js_1 = require("./storage.js");
|
|
6
|
+
const transport_js_1 = require("./transport.js");
|
|
7
|
+
const utils_js_1 = require("./utils.js");
|
|
8
|
+
class StubTelegramClient extends core_1.BaseTelegramClient {
|
|
9
|
+
constructor(params) {
|
|
10
|
+
const storage = new storage_js_1.StubMemoryTelegramStorage({
|
|
11
|
+
hasKeys: true,
|
|
12
|
+
hasTempKeys: true,
|
|
13
|
+
});
|
|
14
|
+
super({
|
|
15
|
+
apiId: 0,
|
|
16
|
+
apiHash: '',
|
|
17
|
+
logLevel: 0,
|
|
18
|
+
storage,
|
|
19
|
+
transport: () => {
|
|
20
|
+
const transport = new transport_js_1.StubTelegramTransport({
|
|
21
|
+
onMessage: (data) => {
|
|
22
|
+
if (!this._onRawMessage) {
|
|
23
|
+
if (this._responders.size) {
|
|
24
|
+
this._emitError(new Error('Unexpected outgoing message'));
|
|
25
|
+
}
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const dcId = transport._currentDc.id;
|
|
29
|
+
const key = storage.getAuthKeyFor(dcId);
|
|
30
|
+
if (key) {
|
|
31
|
+
this._onRawMessage(storage.decryptOutgoingMessage(transport._crypto, data, dcId));
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
return transport;
|
|
36
|
+
},
|
|
37
|
+
...params,
|
|
38
|
+
});
|
|
39
|
+
// some fake peers handling //
|
|
40
|
+
this._knownChats = new Map();
|
|
41
|
+
this._knownUsers = new Map();
|
|
42
|
+
this._selfId = 0;
|
|
43
|
+
// eslint-disable-next-line func-call-spacing
|
|
44
|
+
this._responders = new Map();
|
|
45
|
+
// some fake updates mechanism //
|
|
46
|
+
this._fakeMessageBoxes = new Map();
|
|
47
|
+
this._lastQts = 0;
|
|
48
|
+
this._lastDate = Math.floor(Date.now() / 1000);
|
|
49
|
+
this._lastSeq = 0;
|
|
50
|
+
}
|
|
51
|
+
registerChat(chat) {
|
|
52
|
+
if (Array.isArray(chat)) {
|
|
53
|
+
for (const c of chat) {
|
|
54
|
+
this.registerChat(c);
|
|
55
|
+
}
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
this._knownChats.set(chat.id, chat);
|
|
59
|
+
}
|
|
60
|
+
registerUser(user) {
|
|
61
|
+
if (Array.isArray(user)) {
|
|
62
|
+
for (const u of user) {
|
|
63
|
+
this.registerUser(u);
|
|
64
|
+
}
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
this._knownUsers.set(user.id, user);
|
|
68
|
+
if (user._ === 'user' && user.self) {
|
|
69
|
+
this._selfId = user.id;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
getPeers(ids) {
|
|
73
|
+
const users = [];
|
|
74
|
+
const chats = [];
|
|
75
|
+
for (let id of ids) {
|
|
76
|
+
if (!id)
|
|
77
|
+
continue;
|
|
78
|
+
if (typeof id === 'number') {
|
|
79
|
+
id = (0, utils_js_1.markedIdToPeer)(id);
|
|
80
|
+
}
|
|
81
|
+
switch (id._) {
|
|
82
|
+
case 'peerUser': {
|
|
83
|
+
const user = this._knownUsers.get(id.userId);
|
|
84
|
+
if (!user)
|
|
85
|
+
throw new Error(`Unknown user with ID ${id.userId}`);
|
|
86
|
+
users.push(user);
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
case 'peerChat': {
|
|
90
|
+
const chat = this._knownChats.get(id.chatId);
|
|
91
|
+
if (!chat)
|
|
92
|
+
throw new Error(`Unknown chat with ID ${id.chatId}`);
|
|
93
|
+
chats.push(chat);
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
case 'peerChannel': {
|
|
97
|
+
const chat = this._knownChats.get(id.channelId);
|
|
98
|
+
if (!chat)
|
|
99
|
+
throw new Error(`Unknown channel with ID ${id.channelId}`);
|
|
100
|
+
chats.push(chat);
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { users, chats };
|
|
106
|
+
}
|
|
107
|
+
onRawMessage(fn) {
|
|
108
|
+
this._onRawMessage = fn;
|
|
109
|
+
}
|
|
110
|
+
addResponder(responders) {
|
|
111
|
+
if (Array.isArray(responders)) {
|
|
112
|
+
for (const responder of responders) {
|
|
113
|
+
this.addResponder(responder);
|
|
114
|
+
}
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (typeof responders === 'function') {
|
|
118
|
+
responders = responders(this);
|
|
119
|
+
}
|
|
120
|
+
const [method, responder] = responders;
|
|
121
|
+
this.respondWith(method, responder);
|
|
122
|
+
}
|
|
123
|
+
respondWith(method, response) {
|
|
124
|
+
if (typeof response !== 'function') {
|
|
125
|
+
const res = response;
|
|
126
|
+
response = () => res;
|
|
127
|
+
}
|
|
128
|
+
// eslint-disable-next-line
|
|
129
|
+
this._responders.set(method, response);
|
|
130
|
+
}
|
|
131
|
+
async call(message, params) {
|
|
132
|
+
if (this._responders.has(message._)) {
|
|
133
|
+
// eslint-disable-next-line
|
|
134
|
+
return Promise.resolve(this._responders.get(message._)(message));
|
|
135
|
+
}
|
|
136
|
+
return super.call(message, params);
|
|
137
|
+
}
|
|
138
|
+
getMessageBox(chatId = 0) {
|
|
139
|
+
const state = this._fakeMessageBoxes.get(chatId);
|
|
140
|
+
if (!state) {
|
|
141
|
+
const newState = { pts: 0, lastMessageId: 0 };
|
|
142
|
+
this._fakeMessageBoxes.set(chatId, newState);
|
|
143
|
+
return newState;
|
|
144
|
+
}
|
|
145
|
+
return state;
|
|
146
|
+
}
|
|
147
|
+
getNextMessageId(chatId = 0) {
|
|
148
|
+
const state = this.getMessageBox(chatId);
|
|
149
|
+
const nextId = state.lastMessageId + 1;
|
|
150
|
+
state.lastMessageId = nextId;
|
|
151
|
+
return nextId;
|
|
152
|
+
}
|
|
153
|
+
getNextPts(chatId = 0, count = 1) {
|
|
154
|
+
const state = this.getMessageBox(chatId);
|
|
155
|
+
const nextPts = state.pts + count;
|
|
156
|
+
state.pts = nextPts;
|
|
157
|
+
return nextPts;
|
|
158
|
+
}
|
|
159
|
+
getNextQts() {
|
|
160
|
+
return this._lastQts++;
|
|
161
|
+
}
|
|
162
|
+
getNextDate() {
|
|
163
|
+
return (this._lastDate = Math.floor(Date.now() / 1000));
|
|
164
|
+
}
|
|
165
|
+
createStubUpdates(params) {
|
|
166
|
+
const { peers, updates, seq = 0, seqCount = 1 } = params;
|
|
167
|
+
const { users, chats } = this.getPeers(peers ?? []);
|
|
168
|
+
const seqStart = seq - seqCount + 1;
|
|
169
|
+
if (seq !== 0) {
|
|
170
|
+
this._lastSeq = seq + seqCount;
|
|
171
|
+
}
|
|
172
|
+
if (seqStart !== seq) {
|
|
173
|
+
return {
|
|
174
|
+
_: 'updatesCombined',
|
|
175
|
+
updates,
|
|
176
|
+
users,
|
|
177
|
+
chats,
|
|
178
|
+
date: this.getNextDate(),
|
|
179
|
+
seq,
|
|
180
|
+
seqStart,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
_: 'updates',
|
|
185
|
+
updates,
|
|
186
|
+
users,
|
|
187
|
+
chats,
|
|
188
|
+
date: this.getNextDate(),
|
|
189
|
+
seq,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
// helpers //
|
|
193
|
+
async connectAndWait() {
|
|
194
|
+
await this.connect();
|
|
195
|
+
await new Promise((resolve) => this.once('usable', resolve));
|
|
196
|
+
}
|
|
197
|
+
async with(fn) {
|
|
198
|
+
await this.connectAndWait();
|
|
199
|
+
let error;
|
|
200
|
+
this.onError((err) => {
|
|
201
|
+
error = err;
|
|
202
|
+
});
|
|
203
|
+
try {
|
|
204
|
+
await fn();
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
error = e;
|
|
208
|
+
}
|
|
209
|
+
await this.close();
|
|
210
|
+
if (error) {
|
|
211
|
+
// eslint-disable-next-line @typescript-eslint/no-throw-literal
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
exports.StubTelegramClient = StubTelegramClient;
|
|
217
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";;;AAAA,uCAAuH;AAEvH,6CAAwD;AACxD,iDAAsD;AAEtD,yCAA2C;AAS3C,MAAa,kBAAmB,SAAQ,yBAAkB;IACtD,YAAY,MAA2C;QACnD,MAAM,OAAO,GAAG,IAAI,sCAAyB,CAAC;YAC1C,OAAO,EAAE,IAAI;YACb,WAAW,EAAE,IAAI;SACpB,CAAC,CAAA;QAEF,KAAK,CAAC;YACF,KAAK,EAAE,CAAC;YACR,OAAO,EAAE,EAAE;YACX,QAAQ,EAAE,CAAC;YACX,OAAO;YACP,SAAS,EAAE,GAAG,EAAE;gBACZ,MAAM,SAAS,GAAG,IAAI,oCAAqB,CAAC;oBACxC,SAAS,EAAE,CAAC,IAAI,EAAE,EAAE;wBAChB,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE;4BACrB,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;gCACvB,IAAI,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC,CAAA;6BAC5D;4BAED,OAAM;yBACT;wBAED,MAAM,IAAI,GAAG,SAAS,CAAC,UAAW,CAAC,EAAE,CAAA;wBACrC,MAAM,GAAG,GAAG,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;wBAEvC,IAAI,GAAG,EAAE;4BACL,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,sBAAsB,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;yBACpF;oBACL,CAAC;iBACJ,CAAC,CAAA;gBAEF,OAAO,SAAS,CAAA;YACpB,CAAC;YACD,GAAG,MAAM;SACZ,CAAC,CAAA;QAGN,8BAA8B;QAErB,gBAAW,GAAG,IAAI,GAAG,EAAuB,CAAA;QAC5C,gBAAW,GAAG,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AAG,QAAQ,CAAA;SACjC;QAED,IAAI,QAAQ,KAAK,GAAG,EAAE;YAClB,OAAO;gBACH,CAAC,EAAE,iBAAiB;gBACpB,OAAO;gBACP,KAAK;gBACL,KAAK;gBACL,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE;gBACxB,GAAG;gBACH,QAAQ;aACX,CAAA;SACJ;QAED,OAAO;YACH,CAAC,EAAE,SAAS;YACZ,OAAO;YACP,KAAK;YACL,KAAK;YACL,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE;YACxB,GAAG;SACN,CAAA;IACL,CAAC;IAED,aAAa;IAEb,KAAK,CAAC,cAAc;QAChB,MAAM,IAAI,CAAC,OAAO,EAAE,CAAA;QACpB,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAA;IAChE,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,EAA0B;QACjC,MAAM,IAAI,CAAC,cAAc,EAAE,CAAA;QAE3B,IAAI,KAAc,CAAA;QAElB,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YACjB,KAAK,GAAG,GAAG,CAAA;QACf,CAAC,CAAC,CAAA;QAEF,IAAI;YACA,MAAM,EAAE,EAAE,CAAA;SACb;QAAC,OAAO,CAAC,EAAE;YACR,KAAK,GAAG,CAAC,CAAA;SACZ;QAED,MAAM,IAAI,CAAC,KAAK,EAAE,CAAA;QAElB,IAAI,KAAK,EAAE;YACP,+DAA+D;YAC/D,MAAM,KAAK,CAAA;SACd;IACL,CAAC;CACJ;AApRD,gDAoRC","sourcesContent":["import { BaseTelegramClient, BaseTelegramClientOptions, MaybeAsync, MustEqual, RpcCallOptions, tl } from '@mtcute/core'\n\nimport { StubMemoryTelegramStorage } from './storage.js'\nimport { StubTelegramTransport } from './transport.js'\nimport { InputResponder } from './types.js'\nimport { markedIdToPeer } from './utils.js'\n\ninterface MessageBox {\n pts: number\n lastMessageId: number\n}\n\ntype InputPeerId = number | tl.TypePeer | false | undefined\n\nexport class StubTelegramClient extends BaseTelegramClient {\n constructor(params?: Partial<BaseTelegramClientOptions>) {\n const storage = new StubMemoryTelegramStorage({\n hasKeys: true,\n hasTempKeys: true,\n })\n\n super({\n apiId: 0,\n apiHash: '',\n logLevel: 0,\n storage,\n transport: () => {\n const transport = new StubTelegramTransport({\n onMessage: (data) => {\n if (!this._onRawMessage) {\n if (this._responders.size) {\n this._emitError(new Error('Unexpected outgoing message'))\n }\n\n return\n }\n\n const dcId = transport._currentDc!.id\n const key = storage.getAuthKeyFor(dcId)\n\n if (key) {\n this._onRawMessage(storage.decryptOutgoingMessage(transport._crypto, data, dcId))\n }\n },\n })\n\n return transport\n },\n ...params,\n })\n }\n\n // some fake peers handling //\n\n readonly _knownChats = new Map<number, tl.TypeChat>()\n readonly _knownUsers = new Map<number, tl.TypeUser>()\n _selfId = 0\n\n registerChat(chat: tl.TypeChat | tl.TypeChat[]): void {\n if (Array.isArray(chat)) {\n for (const c of chat) {\n this.registerChat(c)\n }\n\n return\n }\n\n this._knownChats.set(chat.id, chat)\n }\n\n registerUser(user: tl.TypeUser | tl.TypeUser[]): void {\n if (Array.isArray(user)) {\n for (const u of user) {\n this.registerUser(u)\n }\n\n return\n }\n\n this._knownUsers.set(user.id, user)\n\n if (user._ === 'user' && user.self) {\n this._selfId = user.id\n }\n }\n\n getPeers(ids: InputPeerId[]) {\n const users: tl.TypeUser[] = []\n const chats: tl.TypeChat[] = []\n\n for (let id of ids) {\n if (!id) continue\n\n if (typeof id === 'number') {\n id = markedIdToPeer(id)\n }\n\n switch (id._) {\n case 'peerUser': {\n const user = this._knownUsers.get(id.userId)\n if (!user) throw new Error(`Unknown user with ID ${id.userId}`)\n\n users.push(user)\n break\n }\n case 'peerChat': {\n const chat = this._knownChats.get(id.chatId)\n if (!chat) throw new Error(`Unknown chat with ID ${id.chatId}`)\n\n chats.push(chat)\n break\n }\n case 'peerChannel': {\n const chat = this._knownChats.get(id.channelId)\n if (!chat) throw new Error(`Unknown channel with ID ${id.channelId}`)\n\n chats.push(chat)\n break\n }\n }\n }\n\n return { users, chats }\n }\n\n // method calls intercepting //\n\n private _onRawMessage?: (data: Uint8Array) => void\n onRawMessage(fn: (data: Uint8Array) => void): void {\n this._onRawMessage = fn\n }\n\n // eslint-disable-next-line func-call-spacing\n private _responders = new Map<string, (data: unknown) => unknown>()\n\n addResponder<T extends tl.RpcMethod['_']>(responders: InputResponder<T>): void {\n if (Array.isArray(responders)) {\n for (const responder of responders) {\n this.addResponder(responder as InputResponder<tl.RpcMethod['_']>)\n }\n\n return\n }\n\n if (typeof responders === 'function') {\n responders = responders(this)\n }\n\n const [method, responder] = responders\n this.respondWith(method, responder)\n }\n\n respondWith<T extends tl.RpcMethod['_']>(\n method: T,\n response: tl.RpcCallReturn[T] | ((data: tl.FindByName<tl.RpcMethod, T>) => tl.RpcCallReturn[T]),\n ) {\n if (typeof response !== 'function') {\n const res = response\n response = () => res\n }\n\n // eslint-disable-next-line\n this._responders.set(method, response as any)\n }\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._responders.has(message._)) {\n // eslint-disable-next-line\n return Promise.resolve(this._responders.get(message._)!(message)) as any\n }\n\n return super.call(message, params)\n }\n\n // some fake updates mechanism //\n\n private _fakeMessageBoxes = new Map<number, MessageBox>()\n private _lastQts = 0\n private _lastDate = Math.floor(Date.now() / 1000)\n private _lastSeq = 0\n\n getMessageBox(chatId = 0): MessageBox {\n const state = this._fakeMessageBoxes.get(chatId)\n\n if (!state) {\n const newState = { pts: 0, lastMessageId: 0 }\n this._fakeMessageBoxes.set(chatId, newState)\n\n return newState\n }\n\n return state\n }\n\n getNextMessageId(chatId = 0) {\n const state = this.getMessageBox(chatId)\n\n const nextId = state.lastMessageId + 1\n state.lastMessageId = nextId\n\n return nextId\n }\n\n getNextPts(chatId = 0, count = 1) {\n const state = this.getMessageBox(chatId)\n\n const nextPts = state.pts + count\n state.pts = nextPts\n\n return nextPts\n }\n\n getNextQts() {\n return this._lastQts++\n }\n\n getNextDate() {\n return (this._lastDate = Math.floor(Date.now() / 1000))\n }\n\n createStubUpdates(params: {\n updates: tl.TypeUpdate[]\n peers?: (number | tl.TypePeer)[]\n seq?: number\n seqCount?: number\n }): tl.TypeUpdates {\n const { peers, updates, seq = 0, seqCount = 1 } = params\n\n const { users, chats } = this.getPeers(peers ?? [])\n\n const seqStart = seq - seqCount + 1\n\n if (seq !== 0) {\n this._lastSeq = seq + seqCount\n }\n\n if (seqStart !== seq) {\n return {\n _: 'updatesCombined',\n updates,\n users,\n chats,\n date: this.getNextDate(),\n seq,\n seqStart,\n }\n }\n\n return {\n _: 'updates',\n updates,\n users,\n chats,\n date: this.getNextDate(),\n seq,\n }\n }\n\n // helpers //\n\n async connectAndWait() {\n await this.connect()\n await new Promise((resolve) => this.once('usable', resolve))\n }\n\n async with(fn: () => MaybeAsync<void>): Promise<void> {\n await this.connectAndWait()\n\n let error: unknown\n\n this.onError((err) => {\n error = err\n })\n\n try {\n await fn()\n } catch (e) {\n error = e\n }\n\n await this.close()\n\n if (error) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw error\n }\n }\n}\n"]}
|
package/cjs/index.d.ts
ADDED
package/cjs/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./client.js"), exports);
|
|
18
|
+
__exportStar(require("./storage.js"), exports);
|
|
19
|
+
__exportStar(require("./stub.js"), exports);
|
|
20
|
+
__exportStar(require("./transport.js"), exports);
|
|
21
|
+
__exportStar(require("./types.js"), exports);
|
|
22
|
+
//# sourceMappingURL=index.js.map
|
package/cjs/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA2B;AAC3B,+CAA4B;AAC5B,4CAAyB;AACzB,iDAA8B;AAC9B,6CAA0B","sourcesContent":["export * from './client.js'\nexport * from './storage.js'\nexport * from './stub.js'\nexport * from './transport.js'\nexport * from './types.js'\n"]}
|
package/cjs/package.json
ADDED
package/cjs/schema.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/cjs/schema.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getEntriesMap = void 0;
|
|
4
|
+
const module_1 = require("module");
|
|
5
|
+
let _cachedEntriesMap = null;
|
|
6
|
+
let _cachedUnionsMap = null;
|
|
7
|
+
/** @internal */
|
|
8
|
+
function getEntriesMap() {
|
|
9
|
+
if (_cachedEntriesMap) {
|
|
10
|
+
return {
|
|
11
|
+
entries: _cachedEntriesMap,
|
|
12
|
+
unions: _cachedUnionsMap,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
const schema = (0, module_1.createRequire)(import.meta.url)('@mtcute/tl/api-schema.json');
|
|
16
|
+
_cachedEntriesMap = new Map();
|
|
17
|
+
_cachedUnionsMap = new Map();
|
|
18
|
+
let entry;
|
|
19
|
+
for (entry of schema.e) {
|
|
20
|
+
_cachedEntriesMap.set(entry.name, entry);
|
|
21
|
+
if (!_cachedUnionsMap.has(entry.type)) {
|
|
22
|
+
_cachedUnionsMap.set(entry.type, []);
|
|
23
|
+
}
|
|
24
|
+
_cachedUnionsMap.get(entry.type).push(entry);
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
entries: _cachedEntriesMap,
|
|
28
|
+
unions: _cachedUnionsMap,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
exports.getEntriesMap = getEntriesMap;
|
|
32
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/schema.ts"],"names":[],"mappings":";;;AAAA,mCAAsC;AAItC,IAAI,iBAAiB,GAAgC,IAAI,CAAA;AACzD,IAAI,gBAAgB,GAAkC,IAAI,CAAA;AAE1D,gBAAgB;AAChB,SAAgB,aAAa;IACzB,IAAI,iBAAiB,EAAE;QACnB,OAAO;YACH,OAAO,EAAE,iBAAiB;YAC1B,MAAM,EAAE,gBAAiB;SAC5B,CAAA;KACJ;IAED,MAAM,MAAM,GAAG,IAAA,sBAAa,EAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,4BAA4B,CAEzE,CAAA;IAED,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAA;IAC7B,gBAAgB,GAAG,IAAI,GAAG,EAAE,CAAA;IAE5B,IAAI,KAAc,CAAA;IAElB,KAAK,KAAK,IAAI,MAAM,CAAC,CAAC,EAAE;QACpB,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QAExC,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;YACnC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,CAAA;SACvC;QACD,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;KAChD;IAED,OAAO;QACH,OAAO,EAAE,iBAAiB;QAC1B,MAAM,EAAE,gBAAgB;KAC3B,CAAA;AACL,CAAC;AA9BD,sCA8BC","sourcesContent":["import { createRequire } from 'module'\n\nimport type { TlEntry } from '@mtcute/tl-utils'\n\nlet _cachedEntriesMap: Map<string, TlEntry> | null = null\nlet _cachedUnionsMap: Map<string, TlEntry[]> | null = null\n\n/** @internal */\nexport function getEntriesMap() {\n if (_cachedEntriesMap) {\n return {\n entries: _cachedEntriesMap,\n unions: _cachedUnionsMap!,\n }\n }\n\n const schema = createRequire(import.meta.url)('@mtcute/tl/api-schema.json') as {\n e: TlEntry[]\n }\n\n _cachedEntriesMap = new Map()\n _cachedUnionsMap = new Map()\n\n let entry: TlEntry\n\n for (entry of schema.e) {\n _cachedEntriesMap.set(entry.name, entry)\n\n if (!_cachedUnionsMap.has(entry.type)) {\n _cachedUnionsMap.set(entry.type, [])\n }\n _cachedUnionsMap.get(entry.type)!.push(entry)\n }\n\n return {\n entries: _cachedEntriesMap,\n unions: _cachedUnionsMap,\n }\n}\n"]}
|
package/cjs/storage.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ITelegramStorage, MemoryStorage } from '@mtcute/core';
|
|
2
|
+
import { ICryptoProvider } from '@mtcute/core/utils.js';
|
|
3
|
+
export declare class StubMemoryTelegramStorage extends MemoryStorage implements ITelegramStorage {
|
|
4
|
+
readonly params: {
|
|
5
|
+
/**
|
|
6
|
+
* IDs of the DCs for which the storage should have auth keys,
|
|
7
|
+
* or `true` to have keys for all DCs
|
|
8
|
+
*
|
|
9
|
+
* @default true
|
|
10
|
+
*/
|
|
11
|
+
hasKeys?: boolean | number[];
|
|
12
|
+
/**
|
|
13
|
+
* IDs of the DCs for which the storage should have temp auth keys,
|
|
14
|
+
* or `true` to have keys for all DCs
|
|
15
|
+
*
|
|
16
|
+
* @default true
|
|
17
|
+
*/
|
|
18
|
+
hasTempKeys?: boolean | number[];
|
|
19
|
+
onLoad?: () => void;
|
|
20
|
+
onSave?: () => void;
|
|
21
|
+
onDestroy?: () => void;
|
|
22
|
+
onReset?: () => void;
|
|
23
|
+
};
|
|
24
|
+
constructor(params?: {
|
|
25
|
+
/**
|
|
26
|
+
* IDs of the DCs for which the storage should have auth keys,
|
|
27
|
+
* or `true` to have keys for all DCs
|
|
28
|
+
*
|
|
29
|
+
* @default true
|
|
30
|
+
*/
|
|
31
|
+
hasKeys?: boolean | number[];
|
|
32
|
+
/**
|
|
33
|
+
* IDs of the DCs for which the storage should have temp auth keys,
|
|
34
|
+
* or `true` to have keys for all DCs
|
|
35
|
+
*
|
|
36
|
+
* @default true
|
|
37
|
+
*/
|
|
38
|
+
hasTempKeys?: boolean | number[];
|
|
39
|
+
onLoad?: () => void;
|
|
40
|
+
onSave?: () => void;
|
|
41
|
+
onDestroy?: () => void;
|
|
42
|
+
onReset?: () => void;
|
|
43
|
+
});
|
|
44
|
+
getAuthKeyFor(dcId: number, tempIndex?: number | undefined): Uint8Array | null;
|
|
45
|
+
load(): void;
|
|
46
|
+
save(): void;
|
|
47
|
+
destroy(): void;
|
|
48
|
+
reset(withKeys?: boolean): void;
|
|
49
|
+
decryptOutgoingMessage(crypto: ICryptoProvider, data: Uint8Array, dcId: number, tempIndex?: number | undefined): Uint8Array;
|
|
50
|
+
}
|
package/cjs/storage.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StubMemoryTelegramStorage = void 0;
|
|
4
|
+
const core_1 = require("@mtcute/core");
|
|
5
|
+
const utils_js_1 = require("@mtcute/core/utils.js");
|
|
6
|
+
class StubMemoryTelegramStorage extends core_1.MemoryStorage {
|
|
7
|
+
constructor(params = {
|
|
8
|
+
hasKeys: true,
|
|
9
|
+
hasTempKeys: true,
|
|
10
|
+
}) {
|
|
11
|
+
super();
|
|
12
|
+
this.params = params;
|
|
13
|
+
}
|
|
14
|
+
getAuthKeyFor(dcId, tempIndex) {
|
|
15
|
+
if (tempIndex === undefined && this.params.hasKeys) {
|
|
16
|
+
if (this.params.hasKeys === true || this.params.hasKeys.includes(dcId)) {
|
|
17
|
+
return new Uint8Array(256);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (tempIndex === undefined && this.params.hasTempKeys) {
|
|
21
|
+
if (this.params.hasTempKeys === true || this.params.hasTempKeys.includes(dcId)) {
|
|
22
|
+
return new Uint8Array(256);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return super.getAuthKeyFor(dcId, tempIndex);
|
|
26
|
+
}
|
|
27
|
+
load() {
|
|
28
|
+
this.params.onLoad?.();
|
|
29
|
+
super.load();
|
|
30
|
+
}
|
|
31
|
+
save() {
|
|
32
|
+
this.params.onSave?.();
|
|
33
|
+
}
|
|
34
|
+
destroy() {
|
|
35
|
+
this.params.onDestroy?.();
|
|
36
|
+
super.destroy();
|
|
37
|
+
}
|
|
38
|
+
reset(withKeys = false) {
|
|
39
|
+
this.params?.onReset?.();
|
|
40
|
+
super.reset(withKeys);
|
|
41
|
+
}
|
|
42
|
+
decryptOutgoingMessage(crypto, data, dcId, tempIndex) {
|
|
43
|
+
const key = this.getAuthKeyFor(dcId, tempIndex);
|
|
44
|
+
if (!key) {
|
|
45
|
+
throw new core_1.MtArgumentError(`No auth key for DC ${dcId}`);
|
|
46
|
+
}
|
|
47
|
+
const messageKey = data.subarray(8, 24);
|
|
48
|
+
const encryptedData = data.subarray(24);
|
|
49
|
+
const ige = (0, utils_js_1.createAesIgeForMessage)(crypto, key, messageKey, true);
|
|
50
|
+
const innerData = ige.decrypt(encryptedData);
|
|
51
|
+
// skipping all checks because who cares
|
|
52
|
+
const dv = new DataView(innerData.buffer, innerData.byteOffset, innerData.byteLength);
|
|
53
|
+
const length = dv.getUint32(28, true);
|
|
54
|
+
return innerData.subarray(32, 32 + length);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
exports.StubMemoryTelegramStorage = StubMemoryTelegramStorage;
|
|
58
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":";;;AAAA,uCAA+E;AAC/E,oDAA+E;AAE/E,MAAa,yBAA0B,SAAQ,oBAAa;IACxD,YACa,SAqBL;QACA,OAAO,EAAE,IAAI;QACb,WAAW,EAAE,IAAI;KACpB;QAED,KAAK,EAAE,CAAA;QA1BE,WAAM,GAAN,MAAM,CAwBd;IAGL,CAAC;IAED,aAAa,CAAC,IAAY,EAAE,SAA8B;QACtD,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;YAChD,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;gBACpE,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAA;aAC7B;SACJ;QAED,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;YACpD,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;gBAC5E,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAA;aAC7B;SACJ;QAED,OAAO,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IAC/C,CA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C,OAAO,SAAS,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,GAAG,MAAM,CAAC,CAAA;IAC9C,CAAC;CACJ;AArFD,8DAqFC","sourcesContent":["import { ITelegramStorage, MemoryStorage, MtArgumentError } from '@mtcute/core'\nimport { createAesIgeForMessage, ICryptoProvider } from '@mtcute/core/utils.js'\n\nexport class StubMemoryTelegramStorage extends MemoryStorage implements ITelegramStorage {\n constructor(\n readonly params: {\n /**\n * IDs of the DCs for which the storage should have auth keys,\n * or `true` to have keys for all DCs\n *\n * @default true\n */\n hasKeys?: boolean | number[]\n\n /**\n * IDs of the DCs for which the storage should have temp auth keys,\n * or `true` to have keys for all DCs\n *\n * @default true\n */\n hasTempKeys?: boolean | number[]\n\n onLoad?: () => void\n onSave?: () => void\n onDestroy?: () => void\n onReset?: () => void\n } = {\n hasKeys: true,\n hasTempKeys: true,\n },\n ) {\n super()\n }\n\n getAuthKeyFor(dcId: number, tempIndex?: number | undefined): Uint8Array | null {\n if (tempIndex === undefined && this.params.hasKeys) {\n if (this.params.hasKeys === true || this.params.hasKeys.includes(dcId)) {\n return new Uint8Array(256)\n }\n }\n\n if (tempIndex === undefined && this.params.hasTempKeys) {\n if (this.params.hasTempKeys === true || this.params.hasTempKeys.includes(dcId)) {\n return new Uint8Array(256)\n }\n }\n\n return super.getAuthKeyFor(dcId, tempIndex)\n }\n\n load(): void {\n this.params.onLoad?.()\n super.load()\n }\n\n save(): void {\n this.params.onSave?.()\n }\n\n destroy(): void {\n this.params.onDestroy?.()\n super.destroy()\n }\n\n reset(withKeys = false): void {\n this.params?.onReset?.()\n super.reset(withKeys)\n }\n\n decryptOutgoingMessage(crypto: ICryptoProvider, data: Uint8Array, dcId: number, tempIndex?: number | undefined) {\n const key = this.getAuthKeyFor(dcId, tempIndex)\n\n if (!key) {\n throw new MtArgumentError(`No auth key for DC ${dcId}`)\n }\n\n const messageKey = data.subarray(8, 24)\n const encryptedData = data.subarray(24)\n\n const ige = createAesIgeForMessage(crypto, key, messageKey, true)\n const innerData = ige.decrypt(encryptedData)\n\n // skipping all checks because who cares\n const dv = new DataView(innerData.buffer, innerData.byteOffset, innerData.byteLength)\n const length = dv.getUint32(28, true)\n\n return innerData.subarray(32, 32 + length)\n }\n}\n"]}
|
package/cjs/stub.d.ts
ADDED
package/cjs/stub.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createStub = void 0;
|
|
7
|
+
const long_1 = __importDefault(require("long"));
|
|
8
|
+
const schema_js_1 = require("./schema.js");
|
|
9
|
+
function getDefaultFor(arg) {
|
|
10
|
+
if (arg.typeModifiers?.isVector || arg.typeModifiers?.isBareVector) {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
if (arg.typeModifiers?.predicate) {
|
|
14
|
+
return arg.type === 'true' ? false : undefined;
|
|
15
|
+
}
|
|
16
|
+
switch (arg.type) {
|
|
17
|
+
case 'int':
|
|
18
|
+
case 'int53':
|
|
19
|
+
case 'double':
|
|
20
|
+
return 0;
|
|
21
|
+
case 'long':
|
|
22
|
+
return long_1.default.ZERO;
|
|
23
|
+
case 'int128':
|
|
24
|
+
return new Uint8Array(16);
|
|
25
|
+
case 'int256':
|
|
26
|
+
return new Uint8Array(32);
|
|
27
|
+
case 'string':
|
|
28
|
+
return '';
|
|
29
|
+
case 'bytes':
|
|
30
|
+
return new Uint8Array(0);
|
|
31
|
+
case 'Bool':
|
|
32
|
+
case 'bool':
|
|
33
|
+
return false;
|
|
34
|
+
default: {
|
|
35
|
+
const union = (0, schema_js_1.getEntriesMap)().unions.get(arg.type);
|
|
36
|
+
if (!union)
|
|
37
|
+
throw new Error(`Unknown type ${arg.type}`);
|
|
38
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
39
|
+
return createStub(union[0].name);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const snakeToCamel = (s) => {
|
|
44
|
+
return s.replace(/(?<!^|_)(_[a-z0-9])/gi, ($1) => {
|
|
45
|
+
return $1.substring(1).toUpperCase();
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
function createStub(name, partial = {}) {
|
|
49
|
+
const { entries } = (0, schema_js_1.getEntriesMap)();
|
|
50
|
+
const entry = entries.get(name);
|
|
51
|
+
if (!entry)
|
|
52
|
+
throw new Error(`Entry ${name} is unknown`);
|
|
53
|
+
const ret = {
|
|
54
|
+
_: name,
|
|
55
|
+
};
|
|
56
|
+
for (const arg of entry.arguments) {
|
|
57
|
+
if (arg.type === '#')
|
|
58
|
+
continue;
|
|
59
|
+
if (arg.name in partial)
|
|
60
|
+
continue;
|
|
61
|
+
ret[snakeToCamel(arg.name)] = getDefaultFor(arg);
|
|
62
|
+
}
|
|
63
|
+
for (const key in partial) {
|
|
64
|
+
// @ts-expect-error partial is not a full object
|
|
65
|
+
ret[key] = partial[key];
|
|
66
|
+
}
|
|
67
|
+
// eslint-disable-next-line
|
|
68
|
+
return ret;
|
|
69
|
+
}
|
|
70
|
+
exports.createStub = createStub;
|
|
71
|
+
//# sourceMappingURL=stub.js.map
|
package/cjs/stub.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stub.js","sourceRoot":"","sources":["../../src/stub.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AAKvB,2CAA2C;AAE3C,SAAS,aAAa,CAAC,GAAe;IAClC,IAAI,GAAG,CAAC,aAAa,EAAE,QAAQ,IAAI,GAAG,CAAC,aAAa,EAAE,YAAY,EAAE;QAChE,OAAO,EAAE,CAAA;KACZ;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,SAAS,EAAE;QAC9B,OAAO,GAAG,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC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AK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IAE/B,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,SAAS,IAAI,aAAa,CAAC,CAAA;IAEvD,MAAM,GAAG,GAA4B;QACjC,CAAC,EAAE,IAAI;KACV,CAAA;IAED,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,SAAS,EAAE;QAC/B,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG;YAAE,SAAQ;QAC9B,IAAI,GAAG,CAAC,IAAI,IAAI,OAAO;YAAE,SAAQ;QAEjC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAA;KACnD;IAED,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;QACvB,gDAAgD;QAChD,GAAG,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;KAC1B;IAED,2BAA2B;IAC3B,OAAO,GAAU,CAAA;AACrB,CAAC;AA3BD,gCA2BC","sourcesContent":["import Long from 'long'\n\nimport { tl } from '@mtcute/tl'\nimport type { TlArgument } from '@mtcute/tl-utils'\n\nimport { getEntriesMap } from './schema.js'\n\nfunction getDefaultFor(arg: TlArgument): unknown {\n if (arg.typeModifiers?.isVector || arg.typeModifiers?.isBareVector) {\n return []\n }\n\n if (arg.typeModifiers?.predicate) {\n return arg.type === 'true' ? false : undefined\n }\n\n switch (arg.type) {\n case 'int':\n case 'int53':\n case 'double':\n return 0\n case 'long':\n return Long.ZERO\n case 'int128':\n return new Uint8Array(16)\n case 'int256':\n return new Uint8Array(32)\n case 'string':\n return ''\n case 'bytes':\n return new Uint8Array(0)\n case 'Bool':\n case 'bool':\n return false\n\n default: {\n const union = getEntriesMap().unions.get(arg.type)\n if (!union) throw new Error(`Unknown type ${arg.type}`)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return createStub<any>(union[0].name)\n }\n }\n}\n\nconst snakeToCamel = (s: string): string => {\n return s.replace(/(?<!^|_)(_[a-z0-9])/gi, ($1) => {\n return $1.substring(1).toUpperCase()\n })\n}\n\nexport function createStub<T extends tl.TlObject['_']>(\n name: T,\n partial: Partial<tl.FindByName<tl.TlObject, T>> = {},\n): tl.FindByName<tl.TlObject, T> {\n const { entries } = getEntriesMap()\n const entry = entries.get(name)\n\n if (!entry) throw new Error(`Entry ${name} is unknown`)\n\n const ret: Record<string, unknown> = {\n _: name,\n }\n\n for (const arg of entry.arguments) {\n if (arg.type === '#') continue\n if (arg.name in partial) continue\n\n ret[snakeToCamel(arg.name)] = getDefaultFor(arg)\n }\n\n for (const key in partial) {\n // @ts-expect-error partial is not a full object\n ret[key] = partial[key]\n }\n\n // eslint-disable-next-line\n return ret as any\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/// <reference types="node" resolution-mode="require"/>
|
|
2
|
+
import EventEmitter from 'events';
|
|
3
|
+
import { ITelegramTransport, TransportState } from '@mtcute/core';
|
|
4
|
+
import { ICryptoProvider, Logger } from '@mtcute/core/utils.js';
|
|
5
|
+
import { tl } from '@mtcute/tl';
|
|
6
|
+
export declare class StubTelegramTransport extends EventEmitter implements ITelegramTransport {
|
|
7
|
+
readonly params: {
|
|
8
|
+
getMtproxyInfo?: () => tl.RawInputClientProxy;
|
|
9
|
+
onConnect?: (dc: tl.RawDcOption, testMode: boolean) => void;
|
|
10
|
+
onClose?: () => void;
|
|
11
|
+
onMessage?: (msg: Uint8Array) => void;
|
|
12
|
+
};
|
|
13
|
+
constructor(params: {
|
|
14
|
+
getMtproxyInfo?: () => tl.RawInputClientProxy;
|
|
15
|
+
onConnect?: (dc: tl.RawDcOption, testMode: boolean) => void;
|
|
16
|
+
onClose?: () => void;
|
|
17
|
+
onMessage?: (msg: Uint8Array) => void;
|
|
18
|
+
});
|
|
19
|
+
_state: TransportState;
|
|
20
|
+
_currentDc: tl.RawDcOption | null;
|
|
21
|
+
_crypto: ICryptoProvider;
|
|
22
|
+
_log: Logger;
|
|
23
|
+
write(data: Uint8Array): void;
|
|
24
|
+
setup(crypto: ICryptoProvider, log: Logger): void;
|
|
25
|
+
state(): TransportState;
|
|
26
|
+
currentDc(): tl.RawDcOption | null;
|
|
27
|
+
connect(dc: tl.RawDcOption, testMode: boolean): void;
|
|
28
|
+
close(): void;
|
|
29
|
+
send(data: Uint8Array): Promise<void>;
|
|
30
|
+
}
|