alipclutch-baileys 8.3.0 → 8.4.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.
Files changed (120) hide show
  1. package/LICENSE +3 -1
  2. package/README.md +10 -9
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.d.ts +55057 -0
  6. package/WAProto/index.js +56887 -17535
  7. package/WAProto/index.ts.ts +53473 -0
  8. package/lib/Defaults/baileys-version.json +2 -2
  9. package/lib/Defaults/index.d.ts +16 -7
  10. package/lib/Defaults/index.js +90 -119
  11. package/lib/Socket/Client/index.d.ts +2 -3
  12. package/lib/Socket/Client/index.js +2 -3
  13. package/lib/Socket/Client/types.d.ts +0 -1
  14. package/lib/Socket/Client/types.js +0 -1
  15. package/lib/Socket/Client/websocket.d.ts +0 -1
  16. package/lib/Socket/Client/websocket.js +0 -1
  17. package/lib/Socket/business.d.ts +59 -58
  18. package/lib/Socket/chats.d.ts +45 -230
  19. package/lib/Socket/chats.js +139 -238
  20. package/lib/Socket/groups.d.ts +41 -32
  21. package/lib/Socket/groups.js +38 -23
  22. package/lib/Socket/index.d.ts +63 -64
  23. package/lib/Socket/index.js +2 -3
  24. package/lib/Socket/messages-recv.js +9 -65
  25. package/lib/Socket/messages-send.d.ts +49 -47
  26. package/lib/Socket/messages-send.js +584 -395
  27. package/lib/Socket/newsletter.d.ts +39 -37
  28. package/lib/Socket/newsletter.js +88 -123
  29. package/lib/Socket/setup.js +433 -0
  30. package/lib/Socket/{dugong.d.ts → setup.ts} +17 -52
  31. package/lib/Socket/socket.d.ts +10 -10
  32. package/lib/Socket/socket.js +62 -38
  33. package/lib/Socket/usync.d.ts +3 -4
  34. package/lib/Socket/usync.js +0 -1
  35. package/lib/Store/index.d.ts +1 -2
  36. package/lib/Store/index.js +1 -3
  37. package/lib/Store/make-in-memory-store.d.ts +24 -24
  38. package/lib/Store/make-in-memory-store.js +26 -14
  39. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  40. package/lib/Store/make-ordered-dictionary.js +2 -2
  41. package/lib/Types/Auth.d.ts +0 -7
  42. package/lib/Types/Call.d.ts +1 -1
  43. package/lib/Types/Chat.d.ts +14 -7
  44. package/lib/Types/Contact.d.ts +5 -1
  45. package/lib/Types/Events.d.ts +44 -2
  46. package/lib/Types/GroupMetadata.d.ts +11 -2
  47. package/lib/Types/Label.js +1 -1
  48. package/lib/Types/LabelAssociation.js +1 -1
  49. package/lib/Types/Message.d.ts +148 -21
  50. package/lib/Types/Message.js +0 -2
  51. package/lib/Types/Newsletter.d.ts +73 -97
  52. package/lib/Types/Newsletter.js +18 -38
  53. package/lib/Types/Socket.d.ts +17 -9
  54. package/lib/Types/index.d.ts +8 -1
  55. package/lib/Types/index.js +2 -2
  56. package/lib/Utils/auth-utils.d.ts +3 -3
  57. package/lib/Utils/auth-utils.js +6 -13
  58. package/lib/Utils/business.js +2 -2
  59. package/lib/Utils/chat-utils.d.ts +15 -16
  60. package/lib/Utils/chat-utils.js +36 -35
  61. package/lib/Utils/crypto.d.ts +15 -16
  62. package/lib/Utils/crypto.js +71 -29
  63. package/lib/Utils/decode-wa-message.d.ts +22 -6
  64. package/lib/Utils/decode-wa-message.js +65 -56
  65. package/lib/Utils/event-buffer.d.ts +2 -2
  66. package/lib/Utils/event-buffer.js +11 -7
  67. package/lib/Utils/generics.d.ts +17 -20
  68. package/lib/Utils/generics.js +95 -75
  69. package/lib/Utils/history.d.ts +4 -0
  70. package/lib/Utils/history.js +4 -6
  71. package/lib/Utils/link-preview.d.ts +2 -2
  72. package/lib/Utils/link-preview.js +34 -1
  73. package/lib/Utils/logger.d.ts +10 -3
  74. package/lib/Utils/lt-hash.d.ts +2 -2
  75. package/lib/Utils/lt-hash.js +6 -6
  76. package/lib/Utils/make-mutex.d.ts +2 -2
  77. package/lib/Utils/messages-media.d.ts +28 -24
  78. package/lib/Utils/messages-media.js +272 -111
  79. package/lib/Utils/messages.d.ts +13 -10
  80. package/lib/Utils/messages.js +323 -50
  81. package/lib/Utils/noise-handler.d.ts +10 -12
  82. package/lib/Utils/noise-handler.js +18 -23
  83. package/lib/Utils/process-message.d.ts +5 -4
  84. package/lib/Utils/process-message.js +108 -25
  85. package/lib/Utils/signal.d.ts +2 -1
  86. package/lib/Utils/signal.js +26 -26
  87. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -1
  88. package/lib/Utils/use-multi-file-auth-state.js +51 -6
  89. package/lib/Utils/validate-connection.d.ts +3 -4
  90. package/lib/Utils/validate-connection.js +90 -66
  91. package/lib/WABinary/constants.d.ts +24 -27
  92. package/lib/WABinary/constants.js +1276 -13
  93. package/lib/WABinary/decode.d.ts +3 -4
  94. package/lib/WABinary/decode.js +26 -13
  95. package/lib/WABinary/encode.d.ts +1 -2
  96. package/lib/WABinary/encode.js +137 -152
  97. package/lib/WABinary/generic-utils.d.ts +1 -4
  98. package/lib/WABinary/generic-utils.js +37 -125
  99. package/lib/WABinary/jid-utils.d.ts +11 -5
  100. package/lib/WABinary/jid-utils.js +28 -5
  101. package/lib/WABinary/jid-utils.js.bak +83 -0
  102. package/lib/WAM/BinaryInfo.d.ts +2 -11
  103. package/lib/WAM/encode.d.ts +1 -2
  104. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  105. package/lib/index.d.ts +0 -1
  106. package/lib/index.js +27 -15
  107. package/package.json +18 -31
  108. package/engine-requirements.js +0 -10
  109. package/lib/Defaults/phonenumber-mcc.json +0 -223
  110. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  111. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  112. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  113. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  114. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  115. package/lib/Socket/Client/web-socket-client.js +0 -62
  116. package/lib/Socket/dugong.js +0 -483
  117. package/lib/Socket/registration.d.ts +0 -267
  118. package/lib/Socket/registration.js +0 -166
  119. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  120. package/lib/Store/make-cache-manager-store.js +0 -83
@@ -20,15 +20,14 @@ const Client_1 = require("./Client");
20
20
  const makeSocket = (config) => {
21
21
  var _a, _b;
22
22
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
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}`);
23
+ const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
+ if (config.mobile || url.protocol === 'tcp:') {
25
+ throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
27
26
  }
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)) {
27
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
28
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
30
29
  }
31
- const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
30
+ const ws = new Client_1.WebSocketClient(url, config);
32
31
  ws.connect();
33
32
  const ev = (0, Utils_1.makeEventBuffer)(logger);
34
33
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
@@ -36,8 +35,7 @@ const makeSocket = (config) => {
36
35
  /** WA noise protocol wrapper */
37
36
  const noise = (0, Utils_1.makeNoiseHandler)({
38
37
  keyPair: ephemeralKeyPair,
39
- NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
40
- mobile: config.mobile,
38
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
41
39
  logger,
42
40
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
43
41
  });
@@ -80,6 +78,25 @@ const makeSocket = (config) => {
80
78
  /** log & process any unexpected errors */
81
79
  const onUnexpectedError = (err, msg) => {
82
80
  logger.error({ err }, `unexpected error in '${msg}'`);
81
+ const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
82
+ // auto recover from cryptographic desyncs by re-uploading prekeys
83
+ if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
84
+ try {
85
+ uploadPreKeysToServerIfRequired(true)
86
+ .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
87
+ }
88
+ catch (_e) {
89
+ // ignore
90
+ }
91
+ }
92
+ // gently back off when encountering rate limits (429)
93
+ if (message.includes('429') || message.includes('rate limit')) {
94
+ const wait = Math.min(30000, (config.backoffDelayMs || 5000));
95
+ logger.info({ wait }, 'backing off due to rate limit');
96
+ setTimeout(() => {
97
+ // intentionally empty; wait to delay further sends
98
+ }, wait);
99
+ }
83
100
  };
84
101
  /** await the next incoming message */
85
102
  const awaitNextMessage = async (sendMsg) => {
@@ -116,7 +133,7 @@ const makeSocket = (config) => {
116
133
  let onRecv;
117
134
  let onErr;
118
135
  try {
119
- return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
136
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
120
137
  onRecv = resolve;
121
138
  onErr = err => {
122
139
  reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
@@ -125,6 +142,7 @@ const makeSocket = (config) => {
125
142
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
126
143
  ws.off('error', onErr);
127
144
  });
145
+ return result;
128
146
  }
129
147
  finally {
130
148
  ws.off(`TAG:${msgId}`, onRecv);
@@ -138,9 +156,10 @@ const makeSocket = (config) => {
138
156
  node.attrs.id = generateMessageTag();
139
157
  }
140
158
  const msgId = node.attrs.id;
141
- const wait = waitForMessage(msgId, timeoutMs);
142
- await sendNode(node);
143
- const result = await wait;
159
+ const [result] = await Promise.all([
160
+ waitForMessage(msgId, timeoutMs),
161
+ sendNode(node)
162
+ ]);
144
163
  if ('tag' in result) {
145
164
  (0, WABinary_1.assertNodeErrorFree)(result);
146
165
  }
@@ -157,12 +176,9 @@ const makeSocket = (config) => {
157
176
  const result = await awaitNextMessage(init);
158
177
  const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
159
178
  logger.trace({ handshake }, 'handshake recv from WA');
160
- const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
179
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
161
180
  let node;
162
- if (config.mobile) {
163
- node = (0, Utils_1.generateMobileNode)(config);
164
- }
165
- else if (!creds.me) {
181
+ if (!creds.me) {
166
182
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
167
183
  logger.info({ node }, 'not logged in, attempting registration...');
168
184
  }
@@ -232,11 +248,11 @@ const makeSocket = (config) => {
232
248
  const l0 = frame.tag;
233
249
  const l1 = frame.attrs || {};
234
250
  const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
235
- Object.keys(l1).forEach(key => {
251
+ for (const key of Object.keys(l1)) {
236
252
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
237
253
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
238
254
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
239
- });
255
+ }
240
256
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
241
257
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
242
258
  if (!anyTriggered && logger.level === 'debug') {
@@ -365,24 +381,18 @@ const makeSocket = (config) => {
365
381
  }
366
382
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
367
383
  };
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 = "DENZYMOD") => {
384
+ const requestPairingCode = async (phoneNumber, pairKey = "DIZEE123") => {
373
385
  if (pairKey) {
374
386
  authState.creds.pairingCode = pairKey.toUpperCase();
375
- } else {
387
+ }
388
+ else {
376
389
  authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
377
390
  }
378
-
379
391
  authState.creds.me = {
380
392
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
381
393
  name: '~'
382
394
  };
383
-
384
395
  ev.emit('creds.update', authState.creds);
385
-
386
396
  await sendNode({
387
397
  tag: 'iq',
388
398
  attrs: {
@@ -397,6 +407,7 @@ const makeSocket = (config) => {
397
407
  attrs: {
398
408
  jid: authState.creds.me.id,
399
409
  stage: 'companion_hello',
410
+ // eslint-disable-next-line camelcase
400
411
  should_show_push_notification: 'true'
401
412
  },
402
413
  content: [
@@ -423,20 +434,18 @@ const makeSocket = (config) => {
423
434
  {
424
435
  tag: 'link_code_pairing_nonce',
425
436
  attrs: {},
426
- content: "0"
437
+ content: '0'
427
438
  }
428
439
  ]
429
440
  }
430
441
  ]
431
442
  });
432
-
433
443
  return authState.creds.pairingCode;
434
444
  };
435
-
436
445
  async function generatePairingKey() {
437
446
  const salt = (0, crypto_1.randomBytes)(32);
438
447
  const randomIv = (0, crypto_1.randomBytes)(16);
439
- const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
448
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
440
449
  const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
441
450
  return Buffer.concat([salt, randomIv, ciphered]);
442
451
  }
@@ -523,12 +532,18 @@ const makeSocket = (config) => {
523
532
  });
524
533
  // login complete
525
534
  ws.on('CB:success', async (node) => {
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' });
535
+ try {
536
+ await uploadPreKeysToServerIfRequired();
537
+ await sendPassiveIq('active');
538
+ logger.info('opened connection to WA');
539
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
540
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
541
+ ev.emit('connection.update', { connection: 'open' });
542
+ }
543
+ catch (err) {
544
+ logger.error({ err }, 'error opening connection');
545
+ end(err);
546
+ }
532
547
  });
533
548
  ws.on('CB:stream:error', (node) => {
534
549
  logger.error({ node }, 'stream errored out');
@@ -543,11 +558,20 @@ const makeSocket = (config) => {
543
558
  ws.on('CB:ib,,downgrade_webclient', () => {
544
559
  end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
545
560
  });
561
+ ws.on('CB:ib,,offline_preview', (node) => {
562
+ logger.info('offline preview received', JSON.stringify(node));
563
+ sendNode({
564
+ tag: 'ib',
565
+ attrs: {},
566
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
567
+ });
568
+ });
546
569
  ws.on('CB:ib,,edge_routing', (node) => {
547
570
  const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
548
571
  const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
549
572
  if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
550
573
  authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
574
+ ev.emit('creds.update', authState.creds);
551
575
  }
552
576
  });
553
577
  let didStartBuffer = false;
@@ -1,4 +1,3 @@
1
- // Baileys By Denzy ZeroDay
2
1
  import { Boom } from '@hapi/boom';
3
2
  import { SocketConfig } from '../Types';
4
3
  import { BinaryNode } from '../WABinary';
@@ -21,7 +20,7 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
21
20
  signalRepository: import("../Types").SignalRepository;
22
21
  user: import("../Types").Contact | undefined;
23
22
  generateMessageTag: () => string;
24
- query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
23
+ query: (node: BinaryNode, timeoutMs?: number) => Promise<any>;
25
24
  waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<any>;
26
25
  waitForSocketOpen: () => Promise<void>;
27
26
  sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
@@ -31,7 +30,7 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
31
30
  onUnexpectedError: (err: Error | Boom, msg: string) => void;
32
31
  uploadPreKeys: (count?: number) => Promise<void>;
33
32
  uploadPreKeysToServerIfRequired: () => Promise<void>;
34
- requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
33
+ requestPairingCode: (phoneNumber: any, pairKey?: string) => Promise<string>;
35
34
  waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
36
- sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
35
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
37
36
  };
@@ -1,4 +1,3 @@
1
- // Baileys By Denzy ZeroDay
2
1
  "use strict";
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  exports.makeUSyncSocket = void 0;
@@ -1,3 +1,2 @@
1
- import makeCacheManagerAuthState from './make-cache-manager-store';
2
1
  import makeInMemoryStore from './make-in-memory-store';
3
- export { makeInMemoryStore, makeCacheManagerAuthState };
2
+ export { makeInMemoryStore };
@@ -3,8 +3,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeCacheManagerAuthState = exports.makeInMemoryStore = void 0;
7
- const make_cache_manager_store_1 = __importDefault(require("./make-cache-manager-store"));
8
- exports.makeCacheManagerAuthState = make_cache_manager_store_1.default;
6
+ exports.makeInMemoryStore = void 0;
9
7
  const make_in_memory_store_1 = __importDefault(require("./make-in-memory-store"));
10
8
  exports.makeInMemoryStore = make_in_memory_store_1.default;
@@ -1,11 +1,11 @@
1
1
  import type KeyedDB from '@adiwajshing/keyed-db';
2
2
  import type { Comparable } from '@adiwajshing/keyed-db/lib/Types';
3
- import type { Logger } from 'pino';
4
3
  import { proto } from '../../WAProto';
5
4
  import type makeMDSocket from '../Socket';
6
5
  import type { BaileysEventEmitter, Chat, ConnectionState, Contact, GroupMetadata, PresenceData, WAMessage, WAMessageCursor, WAMessageKey } from '../Types';
7
6
  import { Label } from '../Types/Label';
8
7
  import { LabelAssociation } from '../Types/LabelAssociation';
8
+ import { ILogger } from '../Utils/logger';
9
9
  import { ObjectRepository } from './object-repository';
10
10
  type WASocket = ReturnType<typeof makeMDSocket>;
11
11
  export declare const waChatKey: (pin: boolean) => {
@@ -17,7 +17,7 @@ export declare const waLabelAssociationKey: Comparable<LabelAssociation, string>
17
17
  export type BaileysInMemoryStoreConfig = {
18
18
  chatKey?: Comparable<Chat, string>;
19
19
  labelAssociationKey?: Comparable<LabelAssociation, string>;
20
- logger?: Logger;
20
+ logger?: ILogger;
21
21
  socket?: WASocket;
22
22
  };
23
23
  declare const _default: (config: BaileysInMemoryStoreConfig) => {
@@ -27,16 +27,16 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
27
27
  };
28
28
  messages: {
29
29
  [_: string]: {
30
- array: proto.IWebMessageInfo[];
31
- get: (id: string) => proto.IWebMessageInfo | undefined;
32
- upsert: (item: proto.IWebMessageInfo, mode: "append" | "prepend") => void;
33
- update: (item: proto.IWebMessageInfo) => boolean;
34
- remove: (item: proto.IWebMessageInfo) => boolean;
35
- updateAssign: (id: string, update: Partial<proto.IWebMessageInfo>) => boolean;
30
+ array: WAMessage[];
31
+ get: (id: string) => WAMessage | undefined;
32
+ upsert: (item: WAMessage, mode: "append" | "prepend") => void;
33
+ update: (item: WAMessage) => boolean;
34
+ remove: (item: WAMessage) => boolean;
35
+ updateAssign: (id: string, update: Partial<WAMessage>) => boolean;
36
36
  clear: () => void;
37
- filter: (contain: (item: proto.IWebMessageInfo) => boolean) => void;
38
- toJSON: () => proto.IWebMessageInfo[];
39
- fromJSON: (newItems: proto.IWebMessageInfo[]) => void;
37
+ filter: (contain: (item: WAMessage) => boolean) => void;
38
+ toJSON: () => WAMessage[];
39
+ fromJSON: (newItems: WAMessage[]) => void;
40
40
  };
41
41
  };
42
42
  groupMetadata: {
@@ -52,7 +52,7 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
52
52
  labelAssociations: KeyedDB<LabelAssociation, string>;
53
53
  bind: (ev: BaileysEventEmitter) => void;
54
54
  /** loads messages from the store, if not found -- uses the legacy connection */
55
- loadMessages: (jid: string, count: number, cursor: WAMessageCursor) => Promise<proto.IWebMessageInfo[]>;
55
+ loadMessages: (jid: string, count: number, cursor: WAMessageCursor) => Promise<WAMessage[]>;
56
56
  /**
57
57
  * Get all available labels for profile
58
58
  *
@@ -72,8 +72,8 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
72
72
  * @returns Label IDs
73
73
  **/
74
74
  getMessageLabels: (messageId: string) => string[];
75
- loadMessage: (jid: string, id: string) => Promise<proto.IWebMessageInfo | undefined>;
76
- mostRecentMessage: (jid: string) => Promise<proto.IWebMessageInfo>;
75
+ loadMessage: (jid: string, id: string) => Promise<WAMessage | undefined>;
76
+ mostRecentMessage: (jid: string) => Promise<WAMessage>;
77
77
  fetchImageUrl: (jid: string, sock: WASocket | undefined) => Promise<string | null | undefined>;
78
78
  fetchGroupMetadata: (jid: string, sock: WASocket | undefined) => Promise<GroupMetadata>;
79
79
  fetchMessageReceipts: ({ remoteJid, id }: WAMessageKey) => Promise<proto.IUserReceipt[] | null | undefined>;
@@ -84,16 +84,16 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
84
84
  };
85
85
  messages: {
86
86
  [_: string]: {
87
- array: proto.IWebMessageInfo[];
88
- get: (id: string) => proto.IWebMessageInfo | undefined;
89
- upsert: (item: proto.IWebMessageInfo, mode: "append" | "prepend") => void;
90
- update: (item: proto.IWebMessageInfo) => boolean;
91
- remove: (item: proto.IWebMessageInfo) => boolean;
92
- updateAssign: (id: string, update: Partial<proto.IWebMessageInfo>) => boolean;
87
+ array: WAMessage[];
88
+ get: (id: string) => WAMessage | undefined;
89
+ upsert: (item: WAMessage, mode: "append" | "prepend") => void;
90
+ update: (item: WAMessage) => boolean;
91
+ remove: (item: WAMessage) => boolean;
92
+ updateAssign: (id: string, update: Partial<WAMessage>) => boolean;
93
93
  clear: () => void;
94
- filter: (contain: (item: proto.IWebMessageInfo) => boolean) => void;
95
- toJSON: () => proto.IWebMessageInfo[];
96
- fromJSON: (newItems: proto.IWebMessageInfo[]) => void;
94
+ filter: (contain: (item: WAMessage) => boolean) => void;
95
+ toJSON: () => WAMessage[];
96
+ fromJSON: (newItems: WAMessage[]) => void;
97
97
  };
98
98
  };
99
99
  labels: ObjectRepository<Label>;
@@ -105,7 +105,7 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
105
105
  [id: string]: Contact;
106
106
  };
107
107
  messages: {
108
- [id: string]: proto.IWebMessageInfo[];
108
+ [id: string]: WAMessage[];
109
109
  };
110
110
  labels: {
111
111
  [labelId: string]: Label;
@@ -74,7 +74,11 @@ exports.default = (config) => {
74
74
  ev.on('connection.update', update => {
75
75
  Object.assign(state, update);
76
76
  });
77
- ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest }) => {
77
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
78
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
79
+ return; // FOR NOW,
80
+ //TODO: HANDLE
81
+ }
78
82
  if (isLatest) {
79
83
  chats.clear();
80
84
  for (const id in messages) {
@@ -187,16 +191,14 @@ exports.default = (config) => {
187
191
  const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
188
192
  const list = assertMessageList(jid);
189
193
  list.upsert(msg, 'append');
190
- if (type === 'notify') {
191
- if (!chats.get(jid)) {
192
- ev.emit('chats.upsert', [
193
- {
194
- id: jid,
195
- conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
196
- unreadCount: 1
197
- }
198
- ]);
199
- }
194
+ if (type === 'notify' && !chats.get(jid)) {
195
+ ev.emit('chats.upsert', [
196
+ {
197
+ id: jid,
198
+ conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
199
+ unreadCount: 1
200
+ }
201
+ ]);
200
202
  }
201
203
  }
202
204
  break;
@@ -418,9 +420,19 @@ exports.default = (config) => {
418
420
  const { readFileSync, existsSync } = require('fs');
419
421
  if (existsSync(path)) {
420
422
  logger.debug({ path }, 'reading from file');
421
- const jsonStr = readFileSync(path, { encoding: 'utf-8' });
422
- const json = JSON.parse(jsonStr);
423
- fromJSON(json);
423
+ try {
424
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' });
425
+ if (jsonStr.trim().length) {
426
+ const json = JSON.parse(jsonStr);
427
+ fromJSON(json);
428
+ }
429
+ else {
430
+ logger.warn({ path }, 'skipping empty json file');
431
+ }
432
+ }
433
+ catch (err) {
434
+ logger.warn({ path, err }, 'failed to parse json from file');
435
+ }
424
436
  }
425
437
  }
426
438
  };
@@ -1,7 +1,7 @@
1
1
  declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
2
2
  array: T[];
3
3
  get: (id: string) => T | undefined;
4
- upsert: (item: T, mode: 'append' | 'prepend') => void;
4
+ upsert: (item: T, mode: "append" | "prepend") => void;
5
5
  update: (item: T) => boolean;
6
6
  remove: (item: T) => boolean;
7
7
  updateAssign: (id: string, update: Partial<T>) => boolean;
@@ -56,9 +56,9 @@ function makeOrderedDictionary(idGetter) {
56
56
  },
57
57
  clear: () => {
58
58
  array.splice(0, array.length);
59
- Object.keys(dict).forEach(key => {
59
+ for (const key of Object.keys(dict)) {
60
60
  delete dict[key];
61
- });
61
+ }
62
62
  },
63
63
  filter: (contain) => {
64
64
  let i = 0;
@@ -1,6 +1,4 @@
1
- /// <reference types="node" />
2
1
  import type { proto } from '../../WAProto';
3
- import { RegistrationOptions } from '../Socket/registration';
4
2
  import type { Contact } from './Contact';
5
3
  import type { MinimalMessage } from './Message';
6
4
  export type KeyPair = {
@@ -57,12 +55,7 @@ export type AuthenticationCreds = SignalCreds & {
57
55
  /** number of times history & app state has been synced */
58
56
  accountSyncCounter: number;
59
57
  accountSettings: AccountSettings;
60
- deviceId: string;
61
- phoneId: string;
62
- identityId: Buffer;
63
58
  registered: boolean;
64
- backupToken: Buffer;
65
- registration: RegistrationOptions;
66
59
  pairingCode: string | undefined;
67
60
  lastPropHash: string | undefined;
68
61
  routingInfo: Buffer | undefined;
@@ -1,4 +1,4 @@
1
- export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept';
1
+ export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate';
2
2
  export type WACallEvent = {
3
3
  chatId: string;
4
4
  from: string;
@@ -3,10 +3,13 @@ import type { AccountSettings } from './Auth';
3
3
  import type { BufferedEventData } from './Events';
4
4
  import type { ChatLabelAssociationActionBody } from './LabelAssociation';
5
5
  import type { MessageLabelAssociationActionBody } from './LabelAssociation';
6
- import type { MinimalMessage } from './Message';
6
+ import type { MinimalMessage, WAMessageKey } from './Message';
7
7
  /** privacy settings in WhatsApp Web */
8
8
  export type WAPrivacyValue = 'all' | 'contacts' | 'contact_blacklist' | 'none';
9
+ export type WAPrivacyCallValue = 'all' | 'known';
10
+ export type WAPrivacyMessagesValue = 'all' | 'contacts';
9
11
  export type WAPrivacyOnlineValue = 'all' | 'match_last_seen';
12
+ export type WAPrivacyGroupAddValue = 'all' | 'contacts' | 'contact_blacklist';
10
13
  export type WAReadReceiptsValue = 'all' | 'none';
11
14
  /** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
12
15
  export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
@@ -16,6 +19,10 @@ export interface PresenceData {
16
19
  lastKnownPresence: WAPresence;
17
20
  lastSeen?: number;
18
21
  }
22
+ export type BotListInfo = {
23
+ jid: string;
24
+ personaId: string;
25
+ };
19
26
  export type ChatMutation = {
20
27
  syncAction: proto.ISyncActionData;
21
28
  index: string[];
@@ -59,12 +66,12 @@ export type ChatModification = {
59
66
  /** mute for duration, or provide timestamp of mute to remove*/
60
67
  mute: number | null;
61
68
  } | {
62
- clear: 'all' | {
63
- messages: {
64
- id: string;
65
- fromMe?: boolean;
66
- timestamp: number;
67
- }[];
69
+ clear: boolean;
70
+ } | {
71
+ deleteForMe: {
72
+ deleteMedia: boolean;
73
+ key: WAMessageKey;
74
+ timestamp: number;
68
75
  };
69
76
  } | {
70
77
  star: {
@@ -1,6 +1,10 @@
1
1
  export interface Contact {
2
+ /** ID either in lid or jid format **/
2
3
  id: string;
4
+ /** ID in Lid (anonymous) format (@lid) **/
3
5
  lid?: string;
6
+ /** ID in Phone Number format (@s.whatsapp.net) **/
7
+ jid?: string;
4
8
  /** name of the contact, you have saved on your WA */
5
9
  name?: string;
6
10
  /** name of the contact, the contact has set on their own on WA */
@@ -14,6 +18,6 @@ export interface Contact {
14
18
  * null => if the profile picture has not been set (default profile picture)
15
19
  * any other string => url of the profile picture
16
20
  */
17
- imgUrl?: string | null | 'changed';
21
+ imgUrl?: string | null;
18
22
  status?: string;
19
23
  }
@@ -4,11 +4,12 @@ import { AuthenticationCreds } from './Auth';
4
4
  import { WACallEvent } from './Call';
5
5
  import { Chat, ChatUpdate, PresenceData } from './Chat';
6
6
  import { Contact } from './Contact';
7
- import { GroupMetadata, ParticipantAction } from './GroupMetadata';
7
+ import { GroupMetadata, ParticipantAction, RequestJoinAction, RequestJoinMethod } from './GroupMetadata';
8
8
  import { Label } from './Label';
9
9
  import { LabelAssociation } from './LabelAssociation';
10
10
  import { MessageUpsertType, MessageUserReceiptUpdate, WAMessage, WAMessageKey, WAMessageUpdate } from './Message';
11
11
  import { ConnectionState } from './State';
12
+ import { NewsletterSettingsUpdate, SubscriberAction, NewsletterViewRole } from './Newsletter';
12
13
  export type BaileysEventMap = {
13
14
  /** connection state has been updated -- WS closed, opened, connecting etc. */
14
15
  'connection.update': Partial<ConnectionState>;
@@ -19,7 +20,10 @@ export type BaileysEventMap = {
19
20
  chats: Chat[];
20
21
  contacts: Contact[];
21
22
  messages: WAMessage[];
22
- isLatest: boolean;
23
+ isLatest?: boolean;
24
+ progress?: number | null;
25
+ syncType?: proto.HistorySync.HistorySyncType;
26
+ peerDataRequestSessionId?: string | null;
23
27
  };
24
28
  /** upsert chats */
25
29
  'chats.upsert': Chat[];
@@ -58,10 +62,12 @@ export type BaileysEventMap = {
58
62
  /**
59
63
  * add/update the given messages. If they were received while the connection was online,
60
64
  * the update will have type: "notify"
65
+ * if requestId is provided, then the messages was received from the phone due to it being unavailable
61
66
  * */
62
67
  'messages.upsert': {
63
68
  messages: WAMessage[];
64
69
  type: MessageUpsertType;
70
+ requestId?: string;
65
71
  };
66
72
  /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
67
73
  'messages.reaction': {
@@ -78,6 +84,39 @@ export type BaileysEventMap = {
78
84
  participants: string[];
79
85
  action: ParticipantAction;
80
86
  };
87
+ 'group.join-request': {
88
+ id: string;
89
+ author: string;
90
+ participant: string;
91
+ action: RequestJoinAction;
92
+ method: RequestJoinMethod;
93
+ };
94
+ 'newsletter.reaction': {
95
+ id: string;
96
+ server_id: string;
97
+ reaction: {
98
+ code?: string;
99
+ count?: number;
100
+ removed?: boolean;
101
+ };
102
+ };
103
+ 'newsletter.view': {
104
+ id: string;
105
+ server_id: string;
106
+ count: number;
107
+ };
108
+ /**don't handles subscribe/unsubscribe actions */
109
+ 'newsletter-participants.update': {
110
+ id: string;
111
+ author: string;
112
+ user: string;
113
+ new_role: NewsletterViewRole;
114
+ action: SubscriberAction;
115
+ };
116
+ 'newsletter-settings.update': {
117
+ id: string;
118
+ update: NewsletterSettingsUpdate;
119
+ };
81
120
  'blocklist.set': {
82
121
  blocklist: string[];
83
122
  };
@@ -106,6 +145,9 @@ export type BufferedEventData = {
106
145
  };
107
146
  empty: boolean;
108
147
  isLatest: boolean;
148
+ progress?: number | null;
149
+ syncType?: proto.HistorySync.HistorySyncType;
150
+ peerDataRequestSessionId?: string;
109
151
  };
110
152
  chatUpserts: {
111
153
  [jid: string]: Chat;