@denzy-official/baileys 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/WAProto/index.d.ts +55058 -0
  2. package/WAProto/index.js +169662 -0
  3. package/WAProto/index.ts.ts +53474 -0
  4. package/lib/Defaults/index.d.ts +52 -0
  5. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  6. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  7. package/lib/Signal/Group/group_cipher.d.ts +18 -0
  8. package/lib/Signal/Group/index.d.ts +12 -0
  9. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  10. package/lib/Signal/Group/queue-job.d.ts +2 -0
  11. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  13. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  14. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  15. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  16. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  17. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  18. package/lib/Signal/libsignal.d.ts +4 -0
  19. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  20. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  21. package/lib/Socket/Client/index.d.ts +3 -0
  22. package/lib/Socket/Client/index.js +3 -3
  23. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  24. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  25. package/lib/Socket/Client/types.d.ts +17 -0
  26. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  27. package/lib/Socket/Client/web-socket-client.js +62 -0
  28. package/lib/Socket/Client/websocket.d.ts +14 -0
  29. package/lib/Socket/business.d.ts +171 -0
  30. package/lib/Socket/business.js +0 -1
  31. package/lib/Socket/chats.d.ts +267 -0
  32. package/lib/Socket/chats.js +238 -140
  33. package/lib/Socket/dugong.d.ts +254 -0
  34. package/lib/Socket/dugong.js +343 -335
  35. package/lib/Socket/groups.d.ts +115 -0
  36. package/lib/Socket/groups.js +23 -39
  37. package/lib/Socket/index.d.ts +173 -0
  38. package/lib/Socket/index.js +3 -3
  39. package/lib/Socket/messages-recv.d.ts +161 -0
  40. package/lib/Socket/messages-recv.js +65 -10
  41. package/lib/Socket/messages-send.d.ts +149 -0
  42. package/lib/Socket/messages-send.js +392 -412
  43. package/lib/Socket/newsletter.d.ts +134 -0
  44. package/lib/Socket/newsletter.js +124 -72
  45. package/lib/Socket/registration.d.ts +267 -0
  46. package/lib/Socket/registration.js +166 -0
  47. package/lib/Socket/socket.d.ts +43 -0
  48. package/lib/Socket/socket.js +38 -63
  49. package/lib/Socket/usync.d.ts +36 -0
  50. package/lib/Socket/usync.js +0 -1
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/make-in-memory-store.d.ts +119 -0
  53. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  54. package/lib/Store/object-repository.d.ts +11 -0
  55. package/lib/Types/Auth.d.ts +104 -0
  56. package/lib/Types/Call.d.ts +14 -0
  57. package/lib/Types/Chat.d.ts +110 -0
  58. package/lib/Types/Contact.d.ts +24 -0
  59. package/lib/Types/Events.d.ts +200 -0
  60. package/lib/Types/GroupMetadata.d.ts +65 -0
  61. package/lib/Types/Label.d.ts +36 -0
  62. package/lib/Types/LabelAssociation.d.ts +30 -0
  63. package/lib/Types/Message.d.ts +401 -0
  64. package/lib/Types/Newsletter.d.ts +80 -0
  65. package/lib/Types/Product.d.ts +78 -0
  66. package/lib/Types/Signal.d.ts +57 -0
  67. package/lib/Types/Socket.d.ts +119 -0
  68. package/lib/Types/State.d.ts +27 -0
  69. package/lib/Types/USync.d.ts +25 -0
  70. package/lib/Types/index.d.ts +65 -0
  71. package/lib/Utils/auth-utils.d.ts +18 -0
  72. package/lib/Utils/auth-utils.js +13 -8
  73. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  74. package/lib/Utils/baileys-event-stream.js +0 -1
  75. package/lib/Utils/business.d.ts +22 -0
  76. package/lib/Utils/business.js +2 -3
  77. package/lib/Utils/chat-utils.d.ts +71 -0
  78. package/lib/Utils/chat-utils.js +35 -37
  79. package/lib/Utils/crypto.d.ts +41 -0
  80. package/lib/Utils/crypto.js +29 -72
  81. package/lib/Utils/decode-wa-message.d.ts +19 -0
  82. package/lib/Utils/decode-wa-message.js +56 -66
  83. package/lib/Utils/event-buffer.d.ts +35 -0
  84. package/lib/Utils/event-buffer.js +7 -12
  85. package/lib/Utils/generics.d.ts +92 -0
  86. package/lib/Utils/generics.js +75 -96
  87. package/lib/Utils/history.d.ts +15 -0
  88. package/lib/Utils/history.js +6 -5
  89. package/lib/Utils/index.d.ts +17 -0
  90. package/lib/Utils/index.js +0 -1
  91. package/lib/Utils/link-preview.d.ts +21 -0
  92. package/lib/Utils/link-preview.js +1 -34
  93. package/lib/Utils/logger.d.ts +4 -0
  94. package/lib/Utils/lt-hash.d.ts +12 -0
  95. package/lib/Utils/lt-hash.js +6 -6
  96. package/lib/Utils/make-mutex.d.ts +7 -0
  97. package/lib/Utils/messages-media.d.ts +116 -0
  98. package/lib/Utils/messages-media.js +235 -296
  99. package/lib/Utils/messages.d.ts +77 -0
  100. package/lib/Utils/messages.js +60 -304
  101. package/lib/Utils/noise-handler.d.ts +21 -0
  102. package/lib/Utils/noise-handler.js +23 -18
  103. package/lib/Utils/process-message.d.ts +41 -0
  104. package/lib/Utils/process-message.js +25 -89
  105. package/lib/Utils/signal.d.ts +32 -0
  106. package/lib/Utils/signal.js +26 -26
  107. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  108. package/lib/Utils/use-multi-file-auth-state.js +6 -51
  109. package/lib/Utils/validate-connection.d.ts +11 -0
  110. package/lib/Utils/validate-connection.js +52 -20
  111. package/lib/WABinary/constants.d.ts +28 -0
  112. package/lib/WABinary/decode.d.ts +7 -0
  113. package/lib/WABinary/encode.d.ts +3 -0
  114. package/lib/WABinary/generic-utils.d.ts +15 -0
  115. package/lib/WABinary/index.d.ts +6 -0
  116. package/lib/WABinary/jid-utils.d.ts +37 -0
  117. package/lib/WABinary/types.d.ts +19 -0
  118. package/lib/WAM/BinaryInfo.d.ts +9 -0
  119. package/lib/WAM/constants.d.ts +39 -0
  120. package/lib/WAM/encode.d.ts +3 -0
  121. package/lib/WAM/index.d.ts +4 -0
  122. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  123. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  124. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  125. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  126. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  127. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  128. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  129. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  130. package/lib/WAUSync/USyncUser.d.ts +12 -0
  131. package/lib/WAUSync/index.d.ts +3 -0
  132. package/package.json +1 -1
@@ -1,4 +1,3 @@
1
- // baileys by denzy
2
1
  "use strict";
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  exports.makeSocket = void 0;
@@ -21,14 +20,15 @@ const Client_1 = require("./Client");
21
20
  const makeSocket = (config) => {
22
21
  var _a, _b;
23
22
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
24
- const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
25
- if (config.mobile || url.protocol === 'tcp:') {
26
- throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
23
+ let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
+ config.mobile = config.mobile || url.protocol === 'tcp:';
25
+ if (config.mobile && url.protocol !== 'tcp:') {
26
+ url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
27
27
  }
28
- if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
28
+ if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
29
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
30
30
  }
31
- const ws = new Client_1.WebSocketClient(url, config);
31
+ const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
32
32
  ws.connect();
33
33
  const ev = (0, Utils_1.makeEventBuffer)(logger);
34
34
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
@@ -36,7 +36,8 @@ const makeSocket = (config) => {
36
36
  /** WA noise protocol wrapper */
37
37
  const noise = (0, Utils_1.makeNoiseHandler)({
38
38
  keyPair: ephemeralKeyPair,
39
- NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
39
+ NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
40
+ mobile: config.mobile,
40
41
  logger,
41
42
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
42
43
  });
@@ -79,25 +80,6 @@ const makeSocket = (config) => {
79
80
  /** log & process any unexpected errors */
80
81
  const onUnexpectedError = (err, msg) => {
81
82
  logger.error({ err }, `unexpected error in '${msg}'`);
82
- const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
83
- // auto recover from cryptographic desyncs by re-uploading prekeys
84
- if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
85
- try {
86
- uploadPreKeysToServerIfRequired(true)
87
- .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
88
- }
89
- catch (_e) {
90
- // ignore
91
- }
92
- }
93
- // gently back off when encountering rate limits (429)
94
- if (message.includes('429') || message.includes('rate limit')) {
95
- const wait = Math.min(30000, (config.backoffDelayMs || 5000));
96
- logger.info({ wait }, 'backing off due to rate limit');
97
- setTimeout(() => {
98
- // intentionally empty; wait to delay further sends
99
- }, wait);
100
- }
101
83
  };
102
84
  /** await the next incoming message */
103
85
  const awaitNextMessage = async (sendMsg) => {
@@ -134,7 +116,7 @@ const makeSocket = (config) => {
134
116
  let onRecv;
135
117
  let onErr;
136
118
  try {
137
- const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
119
+ return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
138
120
  onRecv = resolve;
139
121
  onErr = err => {
140
122
  reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
@@ -143,7 +125,6 @@ const makeSocket = (config) => {
143
125
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
144
126
  ws.off('error', onErr);
145
127
  });
146
- return result;
147
128
  }
148
129
  finally {
149
130
  ws.off(`TAG:${msgId}`, onRecv);
@@ -157,10 +138,9 @@ const makeSocket = (config) => {
157
138
  node.attrs.id = generateMessageTag();
158
139
  }
159
140
  const msgId = node.attrs.id;
160
- const [result] = await Promise.all([
161
- waitForMessage(msgId, timeoutMs),
162
- sendNode(node)
163
- ]);
141
+ const wait = waitForMessage(msgId, timeoutMs);
142
+ await sendNode(node);
143
+ const result = await wait;
164
144
  if ('tag' in result) {
165
145
  (0, WABinary_1.assertNodeErrorFree)(result);
166
146
  }
@@ -177,9 +157,12 @@ const makeSocket = (config) => {
177
157
  const result = await awaitNextMessage(init);
178
158
  const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
179
159
  logger.trace({ handshake }, 'handshake recv from WA');
180
- const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
160
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
181
161
  let node;
182
- if (!creds.me) {
162
+ if (config.mobile) {
163
+ node = (0, Utils_1.generateMobileNode)(config);
164
+ }
165
+ else if (!creds.me) {
183
166
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
184
167
  logger.info({ node }, 'not logged in, attempting registration...');
185
168
  }
@@ -249,11 +232,11 @@ const makeSocket = (config) => {
249
232
  const l0 = frame.tag;
250
233
  const l1 = frame.attrs || {};
251
234
  const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
252
- for (const key of Object.keys(l1)) {
235
+ Object.keys(l1).forEach(key => {
253
236
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
254
237
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
255
238
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
256
- }
239
+ });
257
240
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
258
241
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
259
242
  if (!anyTriggered && logger.level === 'debug') {
@@ -382,18 +365,24 @@ const makeSocket = (config) => {
382
365
  }
383
366
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
384
367
  };
385
- const requestPairingCode = async (phoneNumber, pairKey = "DENZYMOD") => {
368
+ /** This method was created by snowi, and implemented by KyuuRzy */
369
+
370
+ /** hey bro, if you delete this text */
371
+ /** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
372
+ const requestPairingCode = async (phoneNumber, pairKey) => {
386
373
  if (pairKey) {
387
374
  authState.creds.pairingCode = pairKey.toUpperCase();
388
- }
389
- else {
375
+ } else {
390
376
  authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
391
377
  }
378
+
392
379
  authState.creds.me = {
393
380
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
394
381
  name: '~'
395
382
  };
383
+
396
384
  ev.emit('creds.update', authState.creds);
385
+
397
386
  await sendNode({
398
387
  tag: 'iq',
399
388
  attrs: {
@@ -408,7 +397,6 @@ const makeSocket = (config) => {
408
397
  attrs: {
409
398
  jid: authState.creds.me.id,
410
399
  stage: 'companion_hello',
411
- // eslint-disable-next-line camelcase
412
400
  should_show_push_notification: 'true'
413
401
  },
414
402
  content: [
@@ -435,18 +423,20 @@ const makeSocket = (config) => {
435
423
  {
436
424
  tag: 'link_code_pairing_nonce',
437
425
  attrs: {},
438
- content: '0'
426
+ content: "0"
439
427
  }
440
428
  ]
441
429
  }
442
430
  ]
443
431
  });
432
+
444
433
  return authState.creds.pairingCode;
445
434
  };
435
+
446
436
  async function generatePairingKey() {
447
437
  const salt = (0, crypto_1.randomBytes)(32);
448
438
  const randomIv = (0, crypto_1.randomBytes)(16);
449
- const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
439
+ const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
450
440
  const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
451
441
  return Buffer.concat([salt, randomIv, ciphered]);
452
442
  }
@@ -533,18 +523,12 @@ const makeSocket = (config) => {
533
523
  });
534
524
  // login complete
535
525
  ws.on('CB:success', async (node) => {
536
- try {
537
- await uploadPreKeysToServerIfRequired();
538
- await sendPassiveIq('active');
539
- logger.info('opened connection to WA');
540
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
541
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
542
- ev.emit('connection.update', { connection: 'open' });
543
- }
544
- catch (err) {
545
- logger.error({ err }, 'error opening connection');
546
- end(err);
547
- }
526
+ await uploadPreKeysToServerIfRequired();
527
+ await sendPassiveIq('active');
528
+ logger.info('opened connection to WA');
529
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
530
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
531
+ ev.emit('connection.update', { connection: 'open' });
548
532
  });
549
533
  ws.on('CB:stream:error', (node) => {
550
534
  logger.error({ node }, 'stream errored out');
@@ -559,20 +543,11 @@ const makeSocket = (config) => {
559
543
  ws.on('CB:ib,,downgrade_webclient', () => {
560
544
  end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
561
545
  });
562
- ws.on('CB:ib,,offline_preview', (node) => {
563
- logger.info('offline preview received', JSON.stringify(node));
564
- sendNode({
565
- tag: 'ib',
566
- attrs: {},
567
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
568
- });
569
- });
570
546
  ws.on('CB:ib,,edge_routing', (node) => {
571
547
  const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
572
548
  const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
573
549
  if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
574
550
  authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
575
- ev.emit('creds.update', authState.creds);
576
551
  }
577
552
  });
578
553
  let didStartBuffer = false;
@@ -0,0 +1,36 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { SocketConfig } from '../Types';
3
+ import { BinaryNode } from '../WABinary';
4
+ import { USyncQuery } from '../WAUSync';
5
+ export declare const makeUSyncSocket: (config: SocketConfig) => {
6
+ executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
7
+ type: "md";
8
+ ws: import("./Client").WebSocketClient;
9
+ ev: import("../Types").BaileysEventEmitter & {
10
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): (() => void);
11
+ buffer(): void;
12
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
13
+ flush(force?: boolean): boolean;
14
+ isBuffering(): boolean;
15
+ };
16
+ authState: {
17
+ creds: import("../Types").AuthenticationCreds;
18
+ keys: import("../Types").SignalKeyStoreWithTransaction;
19
+ };
20
+ signalRepository: import("../Types").SignalRepository;
21
+ user: import("../Types").Contact | undefined;
22
+ generateMessageTag: () => string;
23
+ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
24
+ waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<any>;
25
+ waitForSocketOpen: () => Promise<void>;
26
+ sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
27
+ sendNode: (frame: BinaryNode) => Promise<void>;
28
+ logout: (msg?: string) => Promise<void>;
29
+ end: (error: Error | undefined) => void;
30
+ onUnexpectedError: (err: Error | Boom, msg: string) => void;
31
+ uploadPreKeys: (count?: number) => Promise<void>;
32
+ uploadPreKeysToServerIfRequired: () => Promise<void>;
33
+ requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
34
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
35
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
36
+ };
@@ -1,4 +1,3 @@
1
- // baileys by denzy
2
1
  "use strict";
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  exports.makeUSyncSocket = void 0;
@@ -0,0 +1,3 @@
1
+ // baileys by denzy
2
+ import makeInMemoryStore from './make-in-memory-store';
3
+ export { makeInMemoryStore };
@@ -0,0 +1,119 @@
1
+ // baileys by denzy
2
+ import type KeyedDB from '@adiwajshing/keyed-db';
3
+ import type { Comparable } from '@adiwajshing/keyed-db/lib/Types';
4
+ import { proto } from '../../WAProto';
5
+ import type makeMDSocket from '../Socket';
6
+ import type { BaileysEventEmitter, Chat, ConnectionState, Contact, GroupMetadata, PresenceData, WAMessage, WAMessageCursor, WAMessageKey } from '../Types';
7
+ import { Label } from '../Types/Label';
8
+ import { LabelAssociation } from '../Types/LabelAssociation';
9
+ import { ILogger } from '../Utils/logger';
10
+ import { ObjectRepository } from './object-repository';
11
+ type WASocket = ReturnType<typeof makeMDSocket>;
12
+ export declare const waChatKey: (pin: boolean) => {
13
+ key: (c: Chat) => string;
14
+ compare: (k1: string, k2: string) => number;
15
+ };
16
+ export declare const waMessageID: (m: WAMessage) => string;
17
+ export declare const waLabelAssociationKey: Comparable<LabelAssociation, string>;
18
+ export type BaileysInMemoryStoreConfig = {
19
+ chatKey?: Comparable<Chat, string>;
20
+ labelAssociationKey?: Comparable<LabelAssociation, string>;
21
+ logger?: ILogger;
22
+ socket?: WASocket;
23
+ };
24
+ declare const _default: (config: BaileysInMemoryStoreConfig) => {
25
+ chats: KeyedDB<Chat, string>;
26
+ contacts: {
27
+ [_: string]: Contact;
28
+ };
29
+ messages: {
30
+ [_: string]: {
31
+ array: WAMessage[];
32
+ get: (id: string) => WAMessage | undefined;
33
+ upsert: (item: WAMessage, mode: "append" | "prepend") => void;
34
+ update: (item: WAMessage) => boolean;
35
+ remove: (item: WAMessage) => boolean;
36
+ updateAssign: (id: string, update: Partial<WAMessage>) => boolean;
37
+ clear: () => void;
38
+ filter: (contain: (item: WAMessage) => boolean) => void;
39
+ toJSON: () => WAMessage[];
40
+ fromJSON: (newItems: WAMessage[]) => void;
41
+ };
42
+ };
43
+ groupMetadata: {
44
+ [_: string]: GroupMetadata;
45
+ };
46
+ state: ConnectionState;
47
+ presences: {
48
+ [id: string]: {
49
+ [participant: string]: PresenceData;
50
+ };
51
+ };
52
+ labels: ObjectRepository<Label>;
53
+ labelAssociations: KeyedDB<LabelAssociation, string>;
54
+ bind: (ev: BaileysEventEmitter) => void;
55
+ /** loads messages from the store, if not found -- uses the legacy connection */
56
+ loadMessages: (jid: string, count: number, cursor: WAMessageCursor) => Promise<WAMessage[]>;
57
+ /**
58
+ * Get all available labels for profile
59
+ *
60
+ * Keep in mind that the list is formed from predefined tags and tags
61
+ * that were "caught" during their editing.
62
+ */
63
+ getLabels: () => ObjectRepository<Label>;
64
+ /**
65
+ * Get labels for chat
66
+ *
67
+ * @returns Label IDs
68
+ **/
69
+ getChatLabels: (chatId: string) => LabelAssociation[];
70
+ /**
71
+ * Get labels for message
72
+ *
73
+ * @returns Label IDs
74
+ **/
75
+ getMessageLabels: (messageId: string) => string[];
76
+ loadMessage: (jid: string, id: string) => Promise<WAMessage | undefined>;
77
+ mostRecentMessage: (jid: string) => Promise<WAMessage>;
78
+ fetchImageUrl: (jid: string, sock: WASocket | undefined) => Promise<string | null | undefined>;
79
+ fetchGroupMetadata: (jid: string, sock: WASocket | undefined) => Promise<GroupMetadata>;
80
+ fetchMessageReceipts: ({ remoteJid, id }: WAMessageKey) => Promise<proto.IUserReceipt[] | null | undefined>;
81
+ toJSON: () => {
82
+ chats: KeyedDB<Chat, string>;
83
+ contacts: {
84
+ [_: string]: Contact;
85
+ };
86
+ messages: {
87
+ [_: string]: {
88
+ array: WAMessage[];
89
+ get: (id: string) => WAMessage | undefined;
90
+ upsert: (item: WAMessage, mode: "append" | "prepend") => void;
91
+ update: (item: WAMessage) => boolean;
92
+ remove: (item: WAMessage) => boolean;
93
+ updateAssign: (id: string, update: Partial<WAMessage>) => boolean;
94
+ clear: () => void;
95
+ filter: (contain: (item: WAMessage) => boolean) => void;
96
+ toJSON: () => WAMessage[];
97
+ fromJSON: (newItems: WAMessage[]) => void;
98
+ };
99
+ };
100
+ labels: ObjectRepository<Label>;
101
+ labelAssociations: KeyedDB<LabelAssociation, string>;
102
+ };
103
+ fromJSON: (json: {
104
+ chats: Chat[];
105
+ contacts: {
106
+ [id: string]: Contact;
107
+ };
108
+ messages: {
109
+ [id: string]: WAMessage[];
110
+ };
111
+ labels: {
112
+ [labelId: string]: Label;
113
+ };
114
+ labelAssociations: LabelAssociation[];
115
+ }) => void;
116
+ writeToFile: (path: string) => void;
117
+ readFromFile: (path: string) => void;
118
+ };
119
+ export default _default;
@@ -0,0 +1,14 @@
1
+ // baileys by denzy
2
+ declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
3
+ array: T[];
4
+ get: (id: string) => T | undefined;
5
+ upsert: (item: T, mode: "append" | "prepend") => void;
6
+ update: (item: T) => boolean;
7
+ remove: (item: T) => boolean;
8
+ updateAssign: (id: string, update: Partial<T>) => boolean;
9
+ clear: () => void;
10
+ filter: (contain: (item: T) => boolean) => void;
11
+ toJSON: () => T[];
12
+ fromJSON: (newItems: T[]) => void;
13
+ };
14
+ export default makeOrderedDictionary;
@@ -0,0 +1,11 @@
1
+ // baileys by denzy
2
+ export declare class ObjectRepository<T extends object> {
3
+ readonly entityMap: Map<string, T>;
4
+ constructor(entities?: Record<string, T>);
5
+ findById(id: string): T | undefined;
6
+ findAll(): T[];
7
+ upsertById(id: string, entity: T): Map<string, T>;
8
+ deleteById(id: string): boolean;
9
+ count(): number;
10
+ toJSON(): T[];
11
+ }
@@ -0,0 +1,104 @@
1
+ // baileys by denzy
2
+ import type { proto } from '../../WAProto';
3
+ import type { Contact } from './Contact';
4
+ import type { MinimalMessage } from './Message';
5
+ export type KeyPair = {
6
+ public: Uint8Array;
7
+ private: Uint8Array;
8
+ };
9
+ export type SignedKeyPair = {
10
+ keyPair: KeyPair;
11
+ signature: Uint8Array;
12
+ keyId: number;
13
+ timestampS?: number;
14
+ };
15
+ export type ProtocolAddress = {
16
+ name: string;
17
+ deviceId: number;
18
+ };
19
+ export type SignalIdentity = {
20
+ identifier: ProtocolAddress;
21
+ identifierKey: Uint8Array;
22
+ };
23
+ export type LTHashState = {
24
+ version: number;
25
+ hash: Buffer;
26
+ indexValueMap: {
27
+ [indexMacBase64: string]: {
28
+ valueMac: Uint8Array | Buffer;
29
+ };
30
+ };
31
+ };
32
+ export type SignalCreds = {
33
+ readonly signedIdentityKey: KeyPair;
34
+ readonly signedPreKey: SignedKeyPair;
35
+ readonly registrationId: number;
36
+ };
37
+ export type AccountSettings = {
38
+ /** unarchive chats when a new message is received */
39
+ unarchiveChats: boolean;
40
+ /** the default mode to start new conversations with */
41
+ defaultDisappearingMode?: Pick<proto.IConversation, 'ephemeralExpiration' | 'ephemeralSettingTimestamp'>;
42
+ };
43
+ export type AuthenticationCreds = SignalCreds & {
44
+ readonly noiseKey: KeyPair;
45
+ readonly pairingEphemeralKeyPair: KeyPair;
46
+ advSecretKey: string;
47
+ me?: Contact;
48
+ account?: proto.IADVSignedDeviceIdentity;
49
+ signalIdentities?: SignalIdentity[];
50
+ myAppStateKeyId?: string;
51
+ firstUnuploadedPreKeyId: number;
52
+ nextPreKeyId: number;
53
+ lastAccountSyncTimestamp?: number;
54
+ platform?: string;
55
+ processedHistoryMessages: MinimalMessage[];
56
+ /** number of times history & app state has been synced */
57
+ accountSyncCounter: number;
58
+ accountSettings: AccountSettings;
59
+ registered: boolean;
60
+ pairingCode: string | undefined;
61
+ lastPropHash: string | undefined;
62
+ routingInfo: Buffer | undefined;
63
+ };
64
+ export type SignalDataTypeMap = {
65
+ 'pre-key': KeyPair;
66
+ 'session': Uint8Array;
67
+ 'sender-key': Uint8Array;
68
+ 'sender-key-memory': {
69
+ [jid: string]: boolean;
70
+ };
71
+ 'app-state-sync-key': proto.Message.IAppStateSyncKeyData;
72
+ 'app-state-sync-version': LTHashState;
73
+ };
74
+ export type SignalDataSet = {
75
+ [T in keyof SignalDataTypeMap]?: {
76
+ [id: string]: SignalDataTypeMap[T] | null;
77
+ };
78
+ };
79
+ type Awaitable<T> = T | Promise<T>;
80
+ export type SignalKeyStore = {
81
+ get<T extends keyof SignalDataTypeMap>(type: T, ids: string[]): Awaitable<{
82
+ [id: string]: SignalDataTypeMap[T];
83
+ }>;
84
+ set(data: SignalDataSet): Awaitable<void>;
85
+ /** clear all the data in the store */
86
+ clear?(): Awaitable<void>;
87
+ };
88
+ export type SignalKeyStoreWithTransaction = SignalKeyStore & {
89
+ isInTransaction: () => boolean;
90
+ transaction<T>(exec: () => Promise<T>): Promise<T>;
91
+ };
92
+ export type TransactionCapabilityOptions = {
93
+ maxCommitRetries: number;
94
+ delayBetweenTriesMs: number;
95
+ };
96
+ export type SignalAuthState = {
97
+ creds: SignalCreds;
98
+ keys: SignalKeyStore | SignalKeyStoreWithTransaction;
99
+ };
100
+ export type AuthenticationState = {
101
+ creds: AuthenticationCreds;
102
+ keys: SignalKeyStore;
103
+ };
104
+ export {};
@@ -0,0 +1,14 @@
1
+ // baileys by denzy
2
+ export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate';
3
+ export type WACallEvent = {
4
+ chatId: string;
5
+ from: string;
6
+ isGroup?: boolean;
7
+ groupJid?: string;
8
+ id: string;
9
+ date: Date;
10
+ isVideo?: boolean;
11
+ status: WACallUpdateType;
12
+ offline: boolean;
13
+ latencyMs?: number;
14
+ };
@@ -0,0 +1,110 @@
1
+ // baileys by denzy
2
+ import type { proto } from '../../WAProto';
3
+ import type { AccountSettings } from './Auth';
4
+ import type { BufferedEventData } from './Events';
5
+ import type { ChatLabelAssociationActionBody } from './LabelAssociation';
6
+ import type { MessageLabelAssociationActionBody } from './LabelAssociation';
7
+ import type { MinimalMessage, WAMessageKey } from './Message';
8
+ /** privacy settings in WhatsApp Web */
9
+ export type WAPrivacyValue = 'all' | 'contacts' | 'contact_blacklist' | 'none';
10
+ export type WAPrivacyCallValue = 'all' | 'known';
11
+ export type WAPrivacyMessagesValue = 'all' | 'contacts';
12
+ export type WAPrivacyOnlineValue = 'all' | 'match_last_seen';
13
+ export type WAPrivacyGroupAddValue = 'all' | 'contacts' | 'contact_blacklist';
14
+ export type WAReadReceiptsValue = 'all' | 'none';
15
+ /** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
16
+ export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
17
+ export declare const ALL_WA_PATCH_NAMES: readonly ["critical_block", "critical_unblock_low", "regular_high", "regular_low", "regular"];
18
+ export type WAPatchName = typeof ALL_WA_PATCH_NAMES[number];
19
+ export interface PresenceData {
20
+ lastKnownPresence: WAPresence;
21
+ lastSeen?: number;
22
+ }
23
+ export type BotListInfo = {
24
+ jid: string;
25
+ personaId: string;
26
+ };
27
+ export type ChatMutation = {
28
+ syncAction: proto.ISyncActionData;
29
+ index: string[];
30
+ };
31
+ export type WAPatchCreate = {
32
+ syncAction: proto.ISyncActionValue;
33
+ index: string[];
34
+ type: WAPatchName;
35
+ apiVersion: number;
36
+ operation: proto.SyncdMutation.SyncdOperation;
37
+ };
38
+ export type Chat = proto.IConversation & {
39
+ /** unix timestamp of when the last message was received in the chat */
40
+ lastMessageRecvTimestamp?: number;
41
+ };
42
+ export type ChatUpdate = Partial<Chat & {
43
+ /**
44
+ * if specified in the update,
45
+ * the EV buffer will check if the condition gets fulfilled before applying the update
46
+ * Right now, used to determine when to release an app state sync event
47
+ *
48
+ * @returns true, if the update should be applied;
49
+ * false if it can be discarded;
50
+ * undefined if the condition is not yet fulfilled
51
+ * */
52
+ conditional: (bufferedData: BufferedEventData) => boolean | undefined;
53
+ }>;
54
+ /**
55
+ * the last messages in a chat, sorted reverse-chronologically. That is, the latest message should be first in the chat
56
+ * for MD modifications, the last message in the array (i.e. the earlist message) must be the last message recv in the chat
57
+ * */
58
+ export type LastMessageList = MinimalMessage[] | proto.SyncActionValue.ISyncActionMessageRange;
59
+ export type ChatModification = {
60
+ archive: boolean;
61
+ lastMessages: LastMessageList;
62
+ } | {
63
+ pushNameSetting: string;
64
+ } | {
65
+ pin: boolean;
66
+ } | {
67
+ /** mute for duration, or provide timestamp of mute to remove*/
68
+ mute: number | null;
69
+ } | {
70
+ clear: boolean;
71
+ } | {
72
+ deleteForMe: {
73
+ deleteMedia: boolean;
74
+ key: WAMessageKey;
75
+ timestamp: number;
76
+ };
77
+ } | {
78
+ star: {
79
+ messages: {
80
+ id: string;
81
+ fromMe?: boolean;
82
+ }[];
83
+ star: boolean;
84
+ };
85
+ } | {
86
+ markRead: boolean;
87
+ lastMessages: LastMessageList;
88
+ } | {
89
+ delete: true;
90
+ lastMessages: LastMessageList;
91
+ } | {
92
+ addChatLabel: ChatLabelAssociationActionBody;
93
+ } | {
94
+ removeChatLabel: ChatLabelAssociationActionBody;
95
+ } | {
96
+ addMessageLabel: MessageLabelAssociationActionBody;
97
+ } | {
98
+ removeMessageLabel: MessageLabelAssociationActionBody;
99
+ };
100
+ export type InitialReceivedChatsState = {
101
+ [jid: string]: {
102
+ /** the last message received from the other party */
103
+ lastMsgRecvTimestamp?: number;
104
+ /** the absolute last message in the chat */
105
+ lastMsgTimestamp: number;
106
+ };
107
+ };
108
+ export type InitialAppStateSyncOptions = {
109
+ accountSettings: AccountSettings;
110
+ };
@@ -0,0 +1,24 @@
1
+ // baileys by denzy
2
+ export interface Contact {
3
+ /** ID either in lid or jid format **/
4
+ id: string;
5
+ /** ID in Lid (anonymous) format (@lid) **/
6
+ lid?: string;
7
+ /** ID in Phone Number format (@s.whatsapp.net) **/
8
+ jid?: string;
9
+ /** name of the contact, you have saved on your WA */
10
+ name?: string;
11
+ /** name of the contact, the contact has set on their own on WA */
12
+ notify?: string;
13
+ /** I have no idea */
14
+ verifiedName?: string;
15
+ /**
16
+ * Url of the profile picture of the contact
17
+ *
18
+ * 'changed' => if the profile picture has changed
19
+ * null => if the profile picture has not been set (default profile picture)
20
+ * any other string => url of the profile picture
21
+ */
22
+ imgUrl?: string | null;
23
+ status?: string;
24
+ }