teleproto 1.214.0

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.
Files changed (222) hide show
  1. package/CryptoFile.d.ts +2 -0
  2. package/CryptoFile.js +37 -0
  3. package/Helpers.d.ts +150 -0
  4. package/Helpers.js +477 -0
  5. package/LICENSE +23 -0
  6. package/Password.d.ts +14 -0
  7. package/Password.js +270 -0
  8. package/README.md +98 -0
  9. package/Utils.d.ts +227 -0
  10. package/Utils.js +1247 -0
  11. package/Version.d.ts +1 -0
  12. package/Version.js +4 -0
  13. package/client/2fa.d.ts +48 -0
  14. package/client/2fa.js +108 -0
  15. package/client/TelegramClient.d.ts +1043 -0
  16. package/client/TelegramClient.js +1181 -0
  17. package/client/account.d.ts +0 -0
  18. package/client/account.js +1 -0
  19. package/client/auth.d.ts +92 -0
  20. package/client/auth.js +388 -0
  21. package/client/bots.d.ts +6 -0
  22. package/client/bots.js +23 -0
  23. package/client/buttons.d.ts +4 -0
  24. package/client/buttons.js +86 -0
  25. package/client/chats.d.ts +45 -0
  26. package/client/chats.js +350 -0
  27. package/client/dialogs.d.ts +52 -0
  28. package/client/dialogs.js +174 -0
  29. package/client/downloads.d.ts +156 -0
  30. package/client/downloads.js +614 -0
  31. package/client/fs.d.ts +1 -0
  32. package/client/fs.js +17 -0
  33. package/client/index.d.ts +15 -0
  34. package/client/index.js +64 -0
  35. package/client/messageParse.d.ts +17 -0
  36. package/client/messageParse.js +191 -0
  37. package/client/messages.d.ts +263 -0
  38. package/client/messages.js +813 -0
  39. package/client/os.d.ts +2 -0
  40. package/client/os.js +37 -0
  41. package/client/path.d.ts +2 -0
  42. package/client/path.js +7 -0
  43. package/client/telegramBaseClient.d.ts +237 -0
  44. package/client/telegramBaseClient.js +368 -0
  45. package/client/updates.d.ts +33 -0
  46. package/client/updates.js +260 -0
  47. package/client/uploads.d.ts +136 -0
  48. package/client/uploads.js +514 -0
  49. package/client/users.d.ts +29 -0
  50. package/client/users.js +490 -0
  51. package/crypto/AuthKey.d.ts +19 -0
  52. package/crypto/AuthKey.js +76 -0
  53. package/crypto/CTR.d.ts +5 -0
  54. package/crypto/CTR.js +16 -0
  55. package/crypto/Factorizator.d.ts +19 -0
  56. package/crypto/Factorizator.js +74 -0
  57. package/crypto/IGE.d.ts +11 -0
  58. package/crypto/IGE.js +115 -0
  59. package/crypto/RSA.d.ts +14 -0
  60. package/crypto/RSA.js +70 -0
  61. package/crypto/converters.d.ts +19 -0
  62. package/crypto/converters.js +52 -0
  63. package/crypto/crypto.d.ts +19 -0
  64. package/crypto/crypto.js +58 -0
  65. package/crypto/words.d.ts +6 -0
  66. package/crypto/words.js +47 -0
  67. package/define.d.ts +77 -0
  68. package/entityCache.d.ts +7 -0
  69. package/entityCache.js +79 -0
  70. package/errors/Common.d.ts +71 -0
  71. package/errors/Common.js +122 -0
  72. package/errors/RPCBaseErrors.d.ts +84 -0
  73. package/errors/RPCBaseErrors.js +134 -0
  74. package/errors/RPCErrorList.d.ts +37 -0
  75. package/errors/RPCErrorList.js +117 -0
  76. package/errors/index.d.ts +11 -0
  77. package/errors/index.js +32 -0
  78. package/events/Album.d.ts +36 -0
  79. package/events/Album.js +104 -0
  80. package/events/CallbackQuery.d.ts +73 -0
  81. package/events/CallbackQuery.js +193 -0
  82. package/events/DeletedMessage.d.ts +45 -0
  83. package/events/DeletedMessage.js +63 -0
  84. package/events/EditedMessage.d.ts +30 -0
  85. package/events/EditedMessage.js +41 -0
  86. package/events/NewMessage.d.ts +89 -0
  87. package/events/NewMessage.js +182 -0
  88. package/events/Raw.d.ts +29 -0
  89. package/events/Raw.js +43 -0
  90. package/events/common.d.ts +66 -0
  91. package/events/common.js +141 -0
  92. package/events/index.d.ts +2 -0
  93. package/events/index.js +8 -0
  94. package/extensions/AsyncQueue.d.ts +10 -0
  95. package/extensions/AsyncQueue.js +32 -0
  96. package/extensions/BinaryReader.d.ts +99 -0
  97. package/extensions/BinaryReader.js +242 -0
  98. package/extensions/BinaryWriter.d.ts +6 -0
  99. package/extensions/BinaryWriter.js +15 -0
  100. package/extensions/Deferred.d.ts +8 -0
  101. package/extensions/Deferred.js +16 -0
  102. package/extensions/Logger.d.ts +54 -0
  103. package/extensions/Logger.js +128 -0
  104. package/extensions/MessagePacker.d.ts +21 -0
  105. package/extensions/MessagePacker.js +154 -0
  106. package/extensions/PendingState.d.ts +12 -0
  107. package/extensions/PendingState.js +29 -0
  108. package/extensions/PromisedNetSockets.d.ts +24 -0
  109. package/extensions/PromisedNetSockets.js +192 -0
  110. package/extensions/PromisedWebSockets.d.ts +18 -0
  111. package/extensions/PromisedWebSockets.js +124 -0
  112. package/extensions/html.d.ts +5 -0
  113. package/extensions/html.js +228 -0
  114. package/extensions/index.d.ts +7 -0
  115. package/extensions/index.js +17 -0
  116. package/extensions/markdown.d.ts +5 -0
  117. package/extensions/markdown.js +76 -0
  118. package/extensions/markdownv2.d.ts +5 -0
  119. package/extensions/markdownv2.js +51 -0
  120. package/extensions/net.d.ts +1 -0
  121. package/extensions/net.js +17 -0
  122. package/extensions/socks.d.ts +1 -0
  123. package/extensions/socks.js +17 -0
  124. package/index.d.ts +14 -0
  125. package/index.js +62 -0
  126. package/inspect.d.ts +1 -0
  127. package/inspect.js +5 -0
  128. package/network/Authenticator.d.ts +12 -0
  129. package/network/Authenticator.js +192 -0
  130. package/network/MTProtoPlainSender.d.ts +19 -0
  131. package/network/MTProtoPlainSender.js +74 -0
  132. package/network/MTProtoSender.d.ts +290 -0
  133. package/network/MTProtoSender.js +873 -0
  134. package/network/MTProtoState.d.ts +102 -0
  135. package/network/MTProtoState.js +267 -0
  136. package/network/RequestState.d.ts +18 -0
  137. package/network/RequestState.js +35 -0
  138. package/network/connection/Connection.d.ts +69 -0
  139. package/network/connection/Connection.js +162 -0
  140. package/network/connection/TCPAbridged.d.ts +19 -0
  141. package/network/connection/TCPAbridged.js +58 -0
  142. package/network/connection/TCPFull.d.ts +16 -0
  143. package/network/connection/TCPFull.js +61 -0
  144. package/network/connection/TCPMTProxy.d.ts +49 -0
  145. package/network/connection/TCPMTProxy.js +121 -0
  146. package/network/connection/TCPObfuscated.d.ts +18 -0
  147. package/network/connection/TCPObfuscated.js +78 -0
  148. package/network/connection/index.d.ts +4 -0
  149. package/network/connection/index.js +11 -0
  150. package/network/index.d.ts +11 -0
  151. package/network/index.js +23 -0
  152. package/package.json +50 -0
  153. package/requestIter.d.ts +24 -0
  154. package/requestIter.js +109 -0
  155. package/sessions/Abstract.d.ts +103 -0
  156. package/sessions/Abstract.js +6 -0
  157. package/sessions/Memory.d.ts +38 -0
  158. package/sessions/Memory.js +272 -0
  159. package/sessions/StoreSession.d.ts +14 -0
  160. package/sessions/StoreSession.js +77 -0
  161. package/sessions/StringSession.d.ts +32 -0
  162. package/sessions/StringSession.js +116 -0
  163. package/sessions/index.d.ts +4 -0
  164. package/sessions/index.js +11 -0
  165. package/sessions/localStorage.d.ts +1 -0
  166. package/sessions/localStorage.js +4 -0
  167. package/tl/AllTLObjects.d.ts +3 -0
  168. package/tl/AllTLObjects.js +17 -0
  169. package/tl/MTProtoRequest.d.ts +18 -0
  170. package/tl/MTProtoRequest.js +38 -0
  171. package/tl/api.d.ts +32488 -0
  172. package/tl/api.js +507 -0
  173. package/tl/apiTl.d.ts +2 -0
  174. package/tl/apiTl.js +2209 -0
  175. package/tl/core/GZIPPacked.d.ts +15 -0
  176. package/tl/core/GZIPPacked.js +51 -0
  177. package/tl/core/MessageContainer.d.ts +12 -0
  178. package/tl/core/MessageContainer.js +42 -0
  179. package/tl/core/RPCResult.d.ts +14 -0
  180. package/tl/core/RPCResult.js +32 -0
  181. package/tl/core/TLMessage.d.ts +10 -0
  182. package/tl/core/TLMessage.js +14 -0
  183. package/tl/core/index.d.ts +6 -0
  184. package/tl/core/index.js +16 -0
  185. package/tl/custom/button.d.ts +24 -0
  186. package/tl/custom/button.js +78 -0
  187. package/tl/custom/chatGetter.d.ts +29 -0
  188. package/tl/custom/chatGetter.js +116 -0
  189. package/tl/custom/dialog.d.ts +30 -0
  190. package/tl/custom/dialog.js +40 -0
  191. package/tl/custom/draft.d.ts +21 -0
  192. package/tl/custom/draft.js +48 -0
  193. package/tl/custom/file.d.ts +21 -0
  194. package/tl/custom/file.js +68 -0
  195. package/tl/custom/forward.d.ts +15 -0
  196. package/tl/custom/forward.js +47 -0
  197. package/tl/custom/index.d.ts +1 -0
  198. package/tl/custom/index.js +5 -0
  199. package/tl/custom/inlineResult.d.ts +32 -0
  200. package/tl/custom/inlineResult.js +87 -0
  201. package/tl/custom/inlineResults.d.ts +20 -0
  202. package/tl/custom/inlineResults.js +26 -0
  203. package/tl/custom/message.d.ts +427 -0
  204. package/tl/custom/message.js +716 -0
  205. package/tl/custom/messageButton.d.ts +54 -0
  206. package/tl/custom/messageButton.js +152 -0
  207. package/tl/custom/senderGetter.d.ts +28 -0
  208. package/tl/custom/senderGetter.js +55 -0
  209. package/tl/generateModule.d.ts +1 -0
  210. package/tl/generateModule.js +17 -0
  211. package/tl/generationHelpers.d.ts +11 -0
  212. package/tl/generationHelpers.js +289 -0
  213. package/tl/index.d.ts +3 -0
  214. package/tl/index.js +10 -0
  215. package/tl/patched/index.d.ts +2 -0
  216. package/tl/patched/index.js +76 -0
  217. package/tl/schemaTl.d.ts +2 -0
  218. package/tl/schemaTl.js +64 -0
  219. package/tl/types-generator/generate.d.ts +1 -0
  220. package/tl/types-generator/generate.js +84 -0
  221. package/tl/types-generator/template.d.ts +6 -0
  222. package/tl/types-generator/template.js +257 -0
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.patchAll = patchAll;
4
+ const api_1 = require("../api");
5
+ const message_1 = require("../custom/message");
6
+ function getGetter(obj, prop) {
7
+ while (obj) {
8
+ let getter = Object.getOwnPropertyDescriptor(obj, prop);
9
+ if (getter && getter.get) {
10
+ return getter.get;
11
+ }
12
+ obj = Object.getPrototypeOf(obj);
13
+ }
14
+ }
15
+ function getSetter(obj, prop) {
16
+ while (obj) {
17
+ let getter = Object.getOwnPropertyDescriptor(obj, prop);
18
+ if (getter && getter.set) {
19
+ return getter.set;
20
+ }
21
+ obj = Object.getPrototypeOf(obj);
22
+ }
23
+ }
24
+ const getInstanceMethods = (obj) => {
25
+ let keys = {
26
+ methods: new Set(),
27
+ setters: new Set(),
28
+ getters: new Set(),
29
+ };
30
+ let topObject = obj;
31
+ const mapAllMethods = (property) => {
32
+ const getter = getGetter(topObject, property);
33
+ const setter = getSetter(topObject, property);
34
+ if (getter) {
35
+ keys["getters"].add(property);
36
+ }
37
+ else if (setter) {
38
+ keys["setters"].add(property);
39
+ }
40
+ else {
41
+ if (!(property == "constructor")) {
42
+ keys["methods"].add(property);
43
+ }
44
+ }
45
+ };
46
+ do {
47
+ Object.getOwnPropertyNames(obj).map(mapAllMethods);
48
+ // walk-up the prototype chain
49
+ obj = Object.getPrototypeOf(obj);
50
+ } while (
51
+ // not the the Object prototype methods (hasOwnProperty, etc...)
52
+ obj &&
53
+ Object.getPrototypeOf(obj));
54
+ return keys;
55
+ };
56
+ function patchClass(clazz) {
57
+ const { getters, setters, methods } = getInstanceMethods(message_1.CustomMessage.prototype);
58
+ for (const getter of getters) {
59
+ Object.defineProperty(clazz.prototype, getter, {
60
+ get: getGetter(message_1.CustomMessage.prototype, getter),
61
+ });
62
+ }
63
+ for (const setter of setters) {
64
+ Object.defineProperty(clazz.prototype, setter, {
65
+ set: getSetter(message_1.CustomMessage.prototype, setter),
66
+ });
67
+ }
68
+ for (const method of methods) {
69
+ clazz.prototype[method] = message_1.CustomMessage.prototype[method];
70
+ }
71
+ }
72
+ function patchAll() {
73
+ patchClass(api_1.Api.Message);
74
+ patchClass(api_1.Api.MessageService);
75
+ patchClass(api_1.Api.MessageEmpty);
76
+ }
@@ -0,0 +1,2 @@
1
+ declare const _exports: string;
2
+ export = _exports;
package/tl/schemaTl.js ADDED
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ module.exports = `
3
+ resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector<long> = ResPQ;
4
+ p_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;
5
+ p_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;
6
+ p_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;
7
+ p_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;
8
+ bind_auth_key_inner#75a3f765 nonce:long temp_auth_key_id:long perm_auth_key_id:long temp_session_id:long expires_at:int = BindAuthKeyInner;
9
+ server_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;
10
+ server_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;
11
+ server_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;
12
+ client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;
13
+ dh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;
14
+ dh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;
15
+ dh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;
16
+ destroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;
17
+ destroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;
18
+ destroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;
19
+ ---functions---
20
+ req_pq#60469778 nonce:int128 = ResPQ;
21
+ req_pq_multi#be7e8ef1 nonce:int128 = ResPQ;
22
+ req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;
23
+ set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;
24
+ destroy_auth_key#d1435160 = DestroyAuthKeyRes;
25
+ ---types---
26
+ msgs_ack#62d6b459 msg_ids:Vector<long> = MsgsAck;
27
+ bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;
28
+ bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;
29
+ msgs_state_req#da69fb52 msg_ids:Vector<long> = MsgsStateReq;
30
+ msgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;
31
+ msgs_all_info#8cc0d131 msg_ids:Vector<long> info:string = MsgsAllInfo;
32
+ msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
33
+ msg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
34
+ msg_resend_req#7d861a08 msg_ids:Vector<long> = MsgResendReq;
35
+ rpc_error#2144ca19 error_code:int error_message:string = RpcError;
36
+ rpc_answer_unknown#5e2ad36e = RpcDropAnswer;
37
+ rpc_answer_dropped_running#cd78e586 = RpcDropAnswer;
38
+ rpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;
39
+ future_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;
40
+ future_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts;
41
+ pong#347773c5 msg_id:long ping_id:long = Pong;
42
+ destroy_session_ok#e22045fc session_id:long = DestroySessionRes;
43
+ destroy_session_none#62d350c9 session_id:long = DestroySessionRes;
44
+ new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;
45
+ http_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;
46
+ ipPort#d433ad73 ipv4:int port:int = IpPort;
47
+ ipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;
48
+ accessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector<IpPort> = AccessPointRule;
49
+ help.configSimple#5a592a6c date:int expires:int rules:vector<AccessPointRule> = help.ConfigSimple;
50
+ tlsClientHello blocks:vector<TlsBlock> = TlsClientHello;
51
+ tlsBlockString data:string = TlsBlock;
52
+ tlsBlockRandom length:int = TlsBlock;
53
+ tlsBlockZero length:int = TlsBlock;
54
+ tlsBlockDomain = TlsBlock;
55
+ tlsBlockGrease seed:int = TlsBlock;
56
+ tlsBlockPublicKey = TlsBlock;
57
+ tlsBlockScope entries:Vector<TlsBlock> = TlsBlock;
58
+ ---functions---
59
+ rpc_drop_answer#58e4a740 req_msg_id:long = RpcDropAnswer;
60
+ get_future_salts#b921bd04 num:int = FutureSalts;
61
+ ping#7abe77ec ping_id:long = Pong;
62
+ ping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;
63
+ destroy_session#e7512126 session_id:long = DestroySessionRes;
64
+ `;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ const path = require("path");
3
+ const fs = require("fs");
4
+ const { parseTl } = require("../generationHelpers");
5
+ const templateFn = require("./template");
6
+ const INPUT_FILE = path.resolve(__dirname, "../static/api.tl");
7
+ const SCHEMA_FILE = path.resolve(__dirname, "../static/schema.tl");
8
+ const OUTPUT_FILE = path.resolve(__dirname, "../api.d.ts");
9
+ const peersToPatch = [
10
+ "InputPeer",
11
+ "Peer",
12
+ "InputUser",
13
+ "User",
14
+ "UserFull",
15
+ "Chat",
16
+ "ChatFull",
17
+ "InputChannel",
18
+ ];
19
+ function patchMethods(methods) {
20
+ for (const method of methods) {
21
+ for (const arg in method["argsConfig"]) {
22
+ if (peersToPatch.includes(method["argsConfig"][arg]["type"])) {
23
+ method["argsConfig"][arg]["type"] = "EntityLike";
24
+ }
25
+ else if (method["argsConfig"][arg]["type"] &&
26
+ arg.toLowerCase().includes("msgid")) {
27
+ if (method["argsConfig"][arg]["type"] !== "long") {
28
+ method["argsConfig"][arg]["type"] = "MessageIDLike";
29
+ }
30
+ }
31
+ }
32
+ }
33
+ }
34
+ function main() {
35
+ const tlContent = fs.readFileSync(INPUT_FILE, "utf-8");
36
+ const apiConfig = extractParams(tlContent);
37
+ const schemeContent = fs.readFileSync(SCHEMA_FILE, "utf-8");
38
+ const schemeConfig = extractParams(schemeContent);
39
+ const types = [...apiConfig.types, ...schemeConfig.types];
40
+ const functions = [...apiConfig.functions, ...schemeConfig.functions];
41
+ const constructors = [
42
+ ...apiConfig.constructors,
43
+ ...schemeConfig.constructors,
44
+ ];
45
+ // patching custom types
46
+ patchMethods(functions);
47
+ const generated = templateFn({
48
+ types: types,
49
+ functions: functions,
50
+ constructors: constructors,
51
+ });
52
+ fs.writeFileSync(OUTPUT_FILE, generated);
53
+ }
54
+ function extractParams(fileContent) {
55
+ const defInterator = parseTl(fileContent, 109);
56
+ const types = {};
57
+ const constructors = [];
58
+ const functions = [];
59
+ for (const def of defInterator) {
60
+ if (def.isFunction) {
61
+ functions.push(def);
62
+ }
63
+ else {
64
+ if (!types[def.result]) {
65
+ const [namespace, name] = def.result.includes(".")
66
+ ? def.result.split(".")
67
+ : [undefined, def.result];
68
+ types[def.result] = {
69
+ namespace,
70
+ name,
71
+ constructors: [],
72
+ };
73
+ }
74
+ types[def.result].constructors.push(def.namespace ? `${def.namespace}.${def.name}` : def.name);
75
+ constructors.push(def);
76
+ }
77
+ }
78
+ return {
79
+ types: Object.values(types),
80
+ constructors,
81
+ functions,
82
+ };
83
+ }
84
+ main();
@@ -0,0 +1,6 @@
1
+ declare function _exports({ types, constructors, functions }: {
2
+ types: any;
3
+ constructors: any;
4
+ functions: any;
5
+ }): string;
6
+ export = _exports;
@@ -0,0 +1,257 @@
1
+ "use strict";
2
+ // Not sure what they are for.
3
+ const WEIRD_TYPES = new Set(["Bool", "X", "Type"]);
4
+ module.exports = ({ types, constructors, functions }) => {
5
+ function groupByKey(collection, key) {
6
+ return collection.reduce((byKey, member) => {
7
+ const keyValue = member[key] || "_";
8
+ if (!byKey[keyValue]) {
9
+ byKey[keyValue] = [member];
10
+ }
11
+ else {
12
+ byKey[keyValue].push(member);
13
+ }
14
+ return byKey;
15
+ }, {});
16
+ }
17
+ function getClassNameWithNameSpace(name, namespace) {
18
+ return namespace
19
+ ? namespace.toLowerCase() + "." + upperFirst(name)
20
+ : upperFirst(name);
21
+ }
22
+ function renderTypes(types, indent) {
23
+ return types
24
+ .map(({ name, constructors }) => `
25
+ ${!constructors.length ? "// " : ""}export type Type${upperFirst(name)} = ${constructors.map((name) => name).join(" | ")};
26
+ `.trim())
27
+ .join(`\n${indent}`);
28
+ }
29
+ function renderConstructors(constructors, indent) {
30
+ return constructors
31
+ .map((args) => {
32
+ // console.log(args);
33
+ const { name, namespace, argsConfig, constructorId, subclassOfId, } = args;
34
+ if (name === "Message") {
35
+ return `export class Message extends CustomMessage {
36
+ ${indent}CONSTRUCTOR_ID: ${constructorId};
37
+ ${indent}SUBCLASS_OF_ID: ${subclassOfId};
38
+ ${indent}classType: "request";
39
+ ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
40
+ ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
41
+ }`;
42
+ }
43
+ else if (name === "MessageService") {
44
+ return `export class MessageService extends CustomMessage {
45
+ ${indent}CONSTRUCTOR_ID: ${constructorId};
46
+ ${indent}SUBCLASS_OF_ID: ${subclassOfId};
47
+ ${indent}classType: "request";
48
+ ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
49
+ ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
50
+ }`;
51
+ }
52
+ const argKeys = Object.keys(argsConfig);
53
+ // console.log(constructorId);
54
+ if (!argKeys.length) {
55
+ return `export class ${upperFirst(name)} extends VirtualClass<void> {
56
+ ${indent}CONSTRUCTOR_ID: ${constructorId};
57
+ ${indent}SUBCLASS_OF_ID: ${subclassOfId};
58
+ ${indent}classType: "constructor";
59
+ ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
60
+ ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
61
+ }`;
62
+ }
63
+ const hasRequiredArgs = argKeys.some((argName) => !argsConfig[argName].flagIndicator &&
64
+ !argsConfig[argName].isFlag);
65
+ return `
66
+ export class ${upperFirst(name)} extends VirtualClass<{
67
+ ${indent} ${Object.keys(argsConfig)
68
+ .map((argName) => `
69
+ ${renderArg(argName, argsConfig[argName])};
70
+ `.trim())
71
+ .join(`\n${indent} `)}
72
+ ${indent}}${!hasRequiredArgs ? "" : ""}> {
73
+ ${indent}CONSTRUCTOR_ID: ${constructorId};
74
+ ${indent}SUBCLASS_OF_ID: ${subclassOfId};
75
+ ${indent}classType: "constructor";
76
+ ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
77
+ ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
78
+ ${indent} ${Object.keys(argsConfig)
79
+ .map((argName) => `
80
+ ${renderArg(argName, argsConfig[argName])};
81
+ `.trim())
82
+ .join(`\n${indent} `)}
83
+ ${indent}}`.trim();
84
+ })
85
+ .join(`\n${indent}`);
86
+ }
87
+ function renderRequests(requests, indent) {
88
+ return requests
89
+ .map((args) => {
90
+ const { name, argsConfig, result, constructorId, namespace, subclassOfId, } = args;
91
+ const argKeys = Object.keys(argsConfig);
92
+ if (!argKeys.length) {
93
+ return `export class ${upperFirst(name)} extends Request<void, ${renderResult(result)}> {
94
+ ${indent}CONSTRUCTOR_ID: ${constructorId};
95
+ ${indent}SUBCLASS_OF_ID: ${subclassOfId};
96
+ ${indent}classType: "request";
97
+ ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
98
+ ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
99
+ }`;
100
+ }
101
+ const hasRequiredArgs = argKeys.some((argName) => !argsConfig[argName].flagIndicator &&
102
+ !argsConfig[argName].isFlag);
103
+ return `
104
+ export class ${upperFirst(name)} extends Request<Partial<{
105
+ ${indent} ${argKeys
106
+ .map((argName) => `
107
+ ${renderArg(argName, argsConfig[argName])};
108
+ `.trim())
109
+ .join(`\n${indent} `)}
110
+ ${indent}}${!hasRequiredArgs ? "" : ""}>, ${renderResult(result)}> {
111
+ ${indent}CONSTRUCTOR_ID: ${constructorId};
112
+ ${indent}SUBCLASS_OF_ID: ${subclassOfId};
113
+ ${indent}classType: "request";
114
+ ${indent}className: "${getClassNameWithNameSpace(name, namespace)}";
115
+ ${indent}static fromReader(reader: Reader): ${upperFirst(name)};
116
+ ${indent} ${argKeys
117
+ .map((argName) => `
118
+
119
+ ${renderArg(argName, argsConfig[argName])};
120
+ `.trim())
121
+ .join(`\n${indent} `)}
122
+ ${indent}}`.trim();
123
+ })
124
+ .join(`\n${indent}`);
125
+ }
126
+ function renderResult(result) {
127
+ const vectorMatch = result.match(/[Vv]ector<([\w\d.]+)>/);
128
+ const isVector = Boolean(vectorMatch);
129
+ const scalarValue = isVector ? vectorMatch[1] : result;
130
+ const isTlType = Boolean(scalarValue.match(/^[A-Z]/)) || scalarValue.includes(".");
131
+ return renderValueType(scalarValue, isVector, isTlType);
132
+ }
133
+ function renderArg(argName, argConfig) {
134
+ const { isVector, isFlag, skipConstructorId, flagIndicator, type } = argConfig;
135
+ const valueType = renderValueType(type, isVector, !skipConstructorId);
136
+ return `${flagIndicator ? "// " : ""}${argName}${isFlag || (argName === "randomId" && type === "long" && !isVector)
137
+ ? "?"
138
+ : ""}: ${valueType}`;
139
+ }
140
+ function renderValueType(type, isVector, isTlType) {
141
+ if (WEIRD_TYPES.has(type)) {
142
+ return isVector ? `${type}[]` : type;
143
+ }
144
+ let resType;
145
+ if (typeof type === "string" && isTlType) {
146
+ resType = renderTypeName(type);
147
+ }
148
+ else {
149
+ resType = type;
150
+ }
151
+ if (resType === "true") {
152
+ resType = "boolean";
153
+ }
154
+ if (isVector) {
155
+ resType = `${resType}[]`;
156
+ }
157
+ return resType;
158
+ }
159
+ function renderTypeName(typeName) {
160
+ return typeName.includes(".")
161
+ ? typeName.replace(".", ".Type")
162
+ : `Api.Type${typeName}`;
163
+ }
164
+ function upperFirst(str) {
165
+ return `${str[0].toUpperCase()}${str.slice(1)}`;
166
+ }
167
+ function lowerFirst(str) {
168
+ return `${str[0].toLowerCase()}${str.slice(1)}`;
169
+ }
170
+ const typesByNs = groupByKey(types, "namespace");
171
+ const constructorsByNs = groupByKey(constructors, "namespace");
172
+ const requestsByNs = groupByKey(functions, "namespace");
173
+ // language=TypeScript
174
+ return `
175
+ // This file is autogenerated. All changes will be overwritten.
176
+ import { BigInteger } from 'big-integer';
177
+ import {EntityLike,MessageIDLike} from "../define";
178
+ import { CustomMessage } from "./custom/message";
179
+
180
+
181
+ export namespace Api {
182
+ type AnyLiteral = Record<string, any> | void;
183
+ type Reader = any; // To be defined.
184
+ type Client = any; // To be defined.
185
+ type Utils = any; // To be defined.
186
+ type X = unknown;
187
+ type Type = unknown;
188
+ type Bool = boolean;
189
+ type int = number;
190
+ type double = number;
191
+ type float = number;
192
+ type int128 = BigInteger;
193
+ type int256 = BigInteger;
194
+ type long = BigInteger;
195
+ type bytes = Buffer;
196
+ class VirtualClass<Args extends AnyLiteral> {
197
+ static CONSTRUCTOR_ID: number;
198
+ static SUBCLASS_OF_ID: number;
199
+ static className: string;
200
+ static classType: 'constructor' | 'request';
201
+ static serializeBytes(data: Buffer | string): Buffer;
202
+ static serializeDate(date: Date | number): Buffer;
203
+ getBytes():Buffer;
204
+ CONSTRUCTOR_ID: number;
205
+ SUBCLASS_OF_ID: number;
206
+ className: string;
207
+ classType: 'constructor' | 'request';
208
+ constructor(args: Args);
209
+ originalArgs: Args;
210
+ toJSON(): Args;
211
+ }
212
+ class Request<Args, Response> extends VirtualClass<Partial<Args>> {
213
+ static readResult(reader: Reader): Buffer;
214
+ resolve(client: Client, utils: Utils): Promise<void>;
215
+ __response: Response;
216
+ }
217
+ ${renderConstructors(constructorsByNs._, " ")}
218
+ ${renderRequests(requestsByNs._, " ")}
219
+ // namespaces
220
+ ${Object.keys(constructorsByNs)
221
+ .map((namespace) => namespace !== "_"
222
+ ? `
223
+ export namespace ${namespace} {
224
+ ${renderConstructors(constructorsByNs[namespace], " ")}
225
+ }`
226
+ : "")
227
+ .join("\n")}
228
+ ${Object.keys(typesByNs)
229
+ .map((namespace) => namespace !== "_"
230
+ ? `
231
+ export namespace ${namespace} {
232
+ ${renderTypes(typesByNs[namespace], " ")}
233
+ }`
234
+ : "")
235
+ .join("\n")}
236
+ ${Object.keys(requestsByNs)
237
+ .map((namespace) => namespace !== "_"
238
+ ? `
239
+ export namespace ${namespace} {
240
+ ${renderRequests(requestsByNs[namespace], " ")}
241
+ }`
242
+ : "")
243
+ .join("\n")}
244
+ // Types
245
+ export type TypeEntityLike = EntityLike;
246
+ ${renderTypes(typesByNs._, " ")}
247
+ // All requests
248
+ export type AnyRequest = ${requestsByNs._.map(({ name }) => upperFirst(name)).join(" | ")}
249
+ | ${Object.keys(requestsByNs)
250
+ .filter((ns) => ns !== "_")
251
+ .map((ns) => requestsByNs[ns]
252
+ .map(({ name }) => `${ns}.${upperFirst(name)}`)
253
+ .join(" | "))
254
+ .join("\n | ")};
255
+ }
256
+ `;
257
+ };