@vinzsocket/baileys 2.8.9 → 2.8.20

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 (83) hide show
  1. package/lib/Defaults/index.js +75 -73
  2. package/lib/Signal/Group/ciphertext-message.js +9 -9
  3. package/lib/Signal/Group/group-session-builder.js +21 -21
  4. package/lib/Signal/Group/group_cipher.js +79 -81
  5. package/lib/Signal/Group/index.js +2 -2
  6. package/lib/Signal/Group/keyhelper.js +9 -9
  7. package/lib/Signal/Group/queue-job.js +43 -46
  8. package/lib/Signal/Group/sender-chain-key.js +24 -25
  9. package/lib/Signal/Group/sender-key-distribution-message.js +50 -58
  10. package/lib/Signal/Group/sender-key-message.js +55 -60
  11. package/lib/Signal/Group/sender-key-name.js +38 -39
  12. package/lib/Signal/Group/sender-key-record.js +39 -41
  13. package/lib/Signal/Group/sender-key-state.js +85 -89
  14. package/lib/Signal/Group/sender-message-key.js +22 -22
  15. package/lib/Signal/libsignal.js +387 -292
  16. package/lib/Signal/lid-mapping.js +98 -93
  17. package/lib/Socket/Client/types.js +6 -6
  18. package/lib/Socket/Client/websocket.js +44 -44
  19. package/lib/Socket/business.js +350 -365
  20. package/lib/Socket/chats.js +1019 -914
  21. package/lib/Socket/communities.js +454 -376
  22. package/lib/Socket/groups.js +378 -310
  23. package/lib/Socket/index.js +11 -11
  24. package/lib/Socket/messages-recv.js +1355 -1182
  25. package/lib/Socket/messages-send.js +1224 -1081
  26. package/lib/Socket/mex.js +40 -34
  27. package/lib/Socket/newsletter.js +212 -169
  28. package/lib/Socket/socket.js +896 -757
  29. package/lib/Store/index.js +1 -1
  30. package/lib/Store/make-cache-manager-store.js +75 -79
  31. package/lib/Store/make-in-memory-store.js +450 -389
  32. package/lib/Store/make-ordered-dictionary.js +73 -76
  33. package/lib/Store/object-repository.js +24 -22
  34. package/lib/Types/Chat.js +1 -7
  35. package/lib/Types/Label.js +20 -20
  36. package/lib/Types/LabelAssociation.js +2 -2
  37. package/lib/Types/Message.js +2 -2
  38. package/lib/Types/Newsletter.js +24 -24
  39. package/lib/Types/Socket.js +1 -1
  40. package/lib/Types/State.js +8 -8
  41. package/lib/Types/index.js +10 -10
  42. package/lib/Utils/auth-utils.js +408 -401
  43. package/lib/Utils/baileys-event-stream.js +44 -35
  44. package/lib/Utils/business.js +200 -197
  45. package/lib/Utils/chat-utils.js +775 -708
  46. package/lib/Utils/crypto.js +97 -85
  47. package/lib/Utils/decode-wa-message.js +240 -227
  48. package/lib/Utils/event-buffer.js +547 -518
  49. package/lib/Utils/extended-messages.js +250 -203
  50. package/lib/Utils/generics.js +300 -289
  51. package/lib/Utils/history.js +76 -69
  52. package/lib/Utils/lid-resolver.js +47 -42
  53. package/lib/Utils/link-preview.js +75 -65
  54. package/lib/Utils/logger.js +3 -1
  55. package/lib/Utils/lt-hash.js +38 -34
  56. package/lib/Utils/make-mutex.js +32 -34
  57. package/lib/Utils/mention.js +79 -86
  58. package/lib/Utils/message-retry-manager.js +148 -136
  59. package/lib/Utils/messages-media.js +652 -562
  60. package/lib/Utils/messages.js +753 -707
  61. package/lib/Utils/noise-handler.js +156 -135
  62. package/lib/Utils/process-message.js +404 -341
  63. package/lib/Utils/signal.js +180 -118
  64. package/lib/Utils/use-multi-file-auth-state.js +87 -91
  65. package/lib/Utils/validate-connection.js +167 -142
  66. package/lib/WABinary/constants.js +28 -1293
  67. package/lib/WABinary/decode.js +220 -218
  68. package/lib/WABinary/encode.js +199 -201
  69. package/lib/WABinary/generic-utils.js +80 -77
  70. package/lib/WABinary/jid-utils.js +41 -35
  71. package/lib/WAM/BinaryInfo.js +7 -7
  72. package/lib/WAM/constants.js +1 -15241
  73. package/lib/WAM/encode.js +124 -131
  74. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  75. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +51 -47
  76. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -22
  77. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -32
  78. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -19
  79. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -43
  80. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +17 -17
  81. package/lib/WAUSync/USyncQuery.js +82 -84
  82. package/lib/WAUSync/USyncUser.js +20 -20
  83. package/package.json +4 -1
@@ -4,544 +4,573 @@ import { WAMessageStatus } from '../Types/index.js';
4
4
  import { trimUndefined } from './generics.js';
5
5
  import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js';
6
6
  import { isRealMessage, shouldIncrementChatUnread } from './process-message.js';
7
- const BUFFERABLE_EVENT = [
8
- 'messaging-history.set',
9
- 'chats.upsert',
10
- 'chats.update',
11
- 'chats.delete',
12
- 'contacts.upsert',
13
- 'contacts.update',
14
- 'messages.upsert',
15
- 'messages.update',
16
- 'messages.delete',
17
- 'messages.reaction',
18
- 'message-receipt.update',
19
- 'groups.update'
20
- ];
7
+ const BUFFERABLE_EVENT = ['messaging-history.set', 'chats.upsert', 'chats.update', 'chats.delete', 'contacts.upsert', 'contacts.update', 'messages.upsert', 'messages.update', 'messages.delete', 'messages.reaction', 'message-receipt.update', 'groups.update'];
21
8
  const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT);
22
9
  /**
23
10
  * The event buffer logically consolidates different events into a single event
24
11
  * making the data processing more efficient.
25
12
  */
26
- export const makeEventBuffer = (logger) => {
27
- const ev = new EventEmitter();
28
- const historyCache = new Set();
29
- let data = makeBufferData();
30
- let isBuffering = false;
31
- let bufferTimeout = null;
32
- let bufferCount = 0;
33
- const MAX_HISTORY_CACHE_SIZE = 10000; // Limit the history cache size to prevent memory bloat
34
- const BUFFER_TIMEOUT_MS = 30000; // 30 seconds
35
- // take the generic event and fire it as a baileys event
36
- ev.on('event', (map) => {
37
- for (const event in map) {
38
- ev.emit(event, map[event]);
39
- }
40
- });
41
- function buffer() {
42
- if (!isBuffering) {
43
- logger.debug('Event buffer activated');
44
- isBuffering = true;
45
- bufferCount++;
46
- // Auto-flush after a timeout to prevent infinite buffering
47
- if (bufferTimeout) {
48
- clearTimeout(bufferTimeout);
49
- }
50
- bufferTimeout = setTimeout(() => {
51
- if (isBuffering) {
52
- logger.warn('Buffer timeout reached, auto-flushing');
53
- flush();
54
- }
55
- }, BUFFER_TIMEOUT_MS);
56
- }
57
- else {
58
- bufferCount++;
59
- }
13
+ export const makeEventBuffer = logger => {
14
+ const ev = new EventEmitter();
15
+ const historyCache = new Set();
16
+ let data = makeBufferData();
17
+ let isBuffering = false;
18
+ let bufferTimeout = null;
19
+ let bufferCount = 0;
20
+ const MAX_HISTORY_CACHE_SIZE = 10000; // Limit the history cache size to prevent memory bloat
21
+ const BUFFER_TIMEOUT_MS = 30000; // 30 seconds
22
+ // take the generic event and fire it as a baileys event
23
+ ev.on('event', map => {
24
+ for (const event in map) {
25
+ ev.emit(event, map[event]);
60
26
  }
61
- function flush() {
62
- if (!isBuffering) {
63
- return false;
64
- }
65
- logger.debug({ bufferCount }, 'Flushing event buffer');
66
- isBuffering = false;
67
- bufferCount = 0;
68
- // Clear timeout
69
- if (bufferTimeout) {
70
- clearTimeout(bufferTimeout);
71
- bufferTimeout = null;
27
+ });
28
+ function buffer() {
29
+ if (!isBuffering) {
30
+ logger.debug('Event buffer activated');
31
+ isBuffering = true;
32
+ bufferCount++;
33
+ // Auto-flush after a timeout to prevent infinite buffering
34
+ if (bufferTimeout) {
35
+ clearTimeout(bufferTimeout);
36
+ }
37
+ bufferTimeout = setTimeout(() => {
38
+ if (isBuffering) {
39
+ logger.warn('Buffer timeout reached, auto-flushing');
40
+ flush();
72
41
  }
73
- // Clear history cache if it exceeds the max size
74
- if (historyCache.size > MAX_HISTORY_CACHE_SIZE) {
75
- logger.debug({ cacheSize: historyCache.size }, 'Clearing history cache');
76
- historyCache.clear();
77
- }
78
- const newData = makeBufferData();
79
- const chatUpdates = Object.values(data.chatUpdates);
80
- let conditionalChatUpdatesLeft = 0;
81
- for (const update of chatUpdates) {
82
- if (update.conditional) {
83
- conditionalChatUpdatesLeft += 1;
84
- newData.chatUpdates[update.id] = update;
85
- delete data.chatUpdates[update.id];
86
- }
87
- }
88
- const consolidatedData = consolidateEvents(data);
89
- if (Object.keys(consolidatedData).length) {
90
- ev.emit('event', consolidatedData);
91
- }
92
- data = newData;
93
- logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events');
94
- return true;
42
+ }, BUFFER_TIMEOUT_MS);
43
+ } else {
44
+ bufferCount++;
95
45
  }
96
- return {
97
- process(handler) {
98
- const listener = (map) => {
99
- handler(map);
100
- };
101
- ev.on('event', listener);
102
- return () => {
103
- ev.off('event', listener);
104
- };
105
- },
106
- emit(event, evData) {
107
- if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) {
108
- append(data, historyCache, event, evData, logger);
109
- return true;
110
- }
111
- return ev.emit('event', { [event]: evData });
112
- },
113
- isBuffering() {
114
- return isBuffering;
115
- },
116
- buffer,
117
- flush,
118
- createBufferedFunction(work) {
119
- return async (...args) => {
120
- buffer();
121
- try {
122
- const result = await work(...args);
123
- // If this is the only buffer, flush after a small delay
124
- if (bufferCount === 1) {
125
- setTimeout(() => {
126
- if (isBuffering && bufferCount === 1) {
127
- flush();
128
- }
129
- }, 100); // Small delay to allow nested buffers
130
- }
131
- return result;
132
- }
133
- catch (error) {
134
- throw error;
135
- }
136
- finally {
137
- bufferCount = Math.max(0, bufferCount - 1);
138
- if (bufferCount === 0) {
139
- // Auto-flush when no other buffers are active
140
- setTimeout(flush, 100);
141
- }
142
- }
143
- };
144
- },
145
- on: (...args) => ev.on(...args),
146
- off: (...args) => ev.off(...args),
147
- removeAllListeners: (...args) => ev.removeAllListeners(...args)
148
- };
46
+ }
47
+ function flush() {
48
+ if (!isBuffering) {
49
+ return false;
50
+ }
51
+ logger.debug({
52
+ bufferCount
53
+ }, 'Flushing event buffer');
54
+ isBuffering = false;
55
+ bufferCount = 0;
56
+ // Clear timeout
57
+ if (bufferTimeout) {
58
+ clearTimeout(bufferTimeout);
59
+ bufferTimeout = null;
60
+ }
61
+ // Clear history cache if it exceeds the max size
62
+ if (historyCache.size > MAX_HISTORY_CACHE_SIZE) {
63
+ logger.debug({
64
+ cacheSize: historyCache.size
65
+ }, 'Clearing history cache');
66
+ historyCache.clear();
67
+ }
68
+ const newData = makeBufferData();
69
+ const chatUpdates = Object.values(data.chatUpdates);
70
+ let conditionalChatUpdatesLeft = 0;
71
+ for (const update of chatUpdates) {
72
+ if (update.conditional) {
73
+ conditionalChatUpdatesLeft += 1;
74
+ newData.chatUpdates[update.id] = update;
75
+ delete data.chatUpdates[update.id];
76
+ }
77
+ }
78
+ const consolidatedData = consolidateEvents(data);
79
+ if (Object.keys(consolidatedData).length) {
80
+ ev.emit('event', consolidatedData);
81
+ }
82
+ data = newData;
83
+ logger.trace({
84
+ conditionalChatUpdatesLeft
85
+ }, 'released buffered events');
86
+ return true;
87
+ }
88
+ return {
89
+ process(handler) {
90
+ const listener = map => {
91
+ handler(map);
92
+ };
93
+ ev.on('event', listener);
94
+ return () => {
95
+ ev.off('event', listener);
96
+ };
97
+ },
98
+ emit(event, evData) {
99
+ if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) {
100
+ append(data, historyCache, event, evData, logger);
101
+ return true;
102
+ }
103
+ return ev.emit('event', {
104
+ [event]: evData
105
+ });
106
+ },
107
+ isBuffering() {
108
+ return isBuffering;
109
+ },
110
+ buffer,
111
+ flush,
112
+ createBufferedFunction(work) {
113
+ return async (...args) => {
114
+ buffer();
115
+ try {
116
+ const result = await work(...args);
117
+ // If this is the only buffer, flush after a small delay
118
+ if (bufferCount === 1) {
119
+ setTimeout(() => {
120
+ if (isBuffering && bufferCount === 1) {
121
+ flush();
122
+ }
123
+ }, 100); // Small delay to allow nested buffers
124
+ }
125
+ return result;
126
+ } catch (error) {
127
+ throw error;
128
+ } finally {
129
+ bufferCount = Math.max(0, bufferCount - 1);
130
+ if (bufferCount === 0) {
131
+ // Auto-flush when no other buffers are active
132
+ setTimeout(flush, 100);
133
+ }
134
+ }
135
+ };
136
+ },
137
+ on: (...args) => ev.on(...args),
138
+ off: (...args) => ev.off(...args),
139
+ removeAllListeners: (...args) => ev.removeAllListeners(...args)
140
+ };
149
141
  };
150
142
  const makeBufferData = () => {
151
- return {
152
- historySets: {
153
- chats: {},
154
- messages: {},
155
- contacts: {},
156
- isLatest: false,
157
- empty: true
158
- },
159
- chatUpserts: {},
160
- chatUpdates: {},
161
- chatDeletes: new Set(),
162
- contactUpserts: {},
163
- contactUpdates: {},
164
- messageUpserts: {},
165
- messageUpdates: {},
166
- messageReactions: {},
167
- messageDeletes: {},
168
- messageReceipts: {},
169
- groupUpdates: {}
170
- };
143
+ return {
144
+ historySets: {
145
+ chats: {},
146
+ messages: {},
147
+ contacts: {},
148
+ isLatest: false,
149
+ empty: true
150
+ },
151
+ chatUpserts: {},
152
+ chatUpdates: {},
153
+ chatDeletes: new Set(),
154
+ contactUpserts: {},
155
+ contactUpdates: {},
156
+ messageUpserts: {},
157
+ messageUpdates: {},
158
+ messageReactions: {},
159
+ messageDeletes: {},
160
+ messageReceipts: {},
161
+ groupUpdates: {}
162
+ };
171
163
  };
172
- function append(data, historyCache, event,
164
+ function append(data, historyCache, event,
173
165
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
174
166
  eventData, logger) {
175
- switch (event) {
176
- case 'messaging-history.set':
177
- for (const chat of eventData.chats) {
178
- const existingChat = data.historySets.chats[chat.id];
179
- if (existingChat) {
180
- existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
181
- }
182
- if (!existingChat && !historyCache.has(chat.id)) {
183
- data.historySets.chats[chat.id] = chat;
184
- historyCache.add(chat.id);
185
- absorbingChatUpdate(chat);
186
- }
187
- }
188
- for (const contact of eventData.contacts) {
189
- const existingContact = data.historySets.contacts[contact.id];
190
- if (existingContact) {
191
- Object.assign(existingContact, trimUndefined(contact));
192
- }
193
- else {
194
- const historyContactId = `c:${contact.id}`;
195
- const hasAnyName = contact.notify || contact.name || contact.verifiedName;
196
- if (!historyCache.has(historyContactId) || hasAnyName) {
197
- data.historySets.contacts[contact.id] = contact;
198
- historyCache.add(historyContactId);
199
- }
200
- }
201
- }
202
- for (const message of eventData.messages) {
203
- const key = stringifyMessageKey(message.key);
204
- const existingMsg = data.historySets.messages[key];
205
- if (!existingMsg && !historyCache.has(key)) {
206
- data.historySets.messages[key] = message;
207
- historyCache.add(key);
208
- }
209
- }
210
- data.historySets.empty = false;
211
- data.historySets.syncType = eventData.syncType;
212
- data.historySets.progress = eventData.progress;
213
- data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
214
- data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
215
- break;
216
- case 'chats.upsert':
217
- for (const chat of eventData) {
218
- let upsert = data.chatUpserts[chat.id];
219
- if (!upsert) {
220
- upsert = data.historySets.chats[chat.id];
221
- if (upsert) {
222
- logger.debug({ chatId: chat.id }, 'absorbed chat upsert in chat set');
223
- }
224
- }
225
- if (upsert) {
226
- upsert = concatChats(upsert, chat);
227
- }
228
- else {
229
- upsert = chat;
230
- data.chatUpserts[chat.id] = upsert;
231
- }
232
- absorbingChatUpdate(upsert);
233
- if (data.chatDeletes.has(chat.id)) {
234
- data.chatDeletes.delete(chat.id);
235
- }
236
- }
237
- break;
238
- case 'chats.update':
239
- for (const update of eventData) {
240
- const chatId = update.id;
241
- const conditionMatches = update.conditional ? update.conditional(data) : true;
242
- if (conditionMatches) {
243
- delete update.conditional;
244
- // if there is an existing upsert, merge the update into it
245
- const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
246
- if (upsert) {
247
- concatChats(upsert, update);
248
- }
249
- else {
250
- // merge the update into the existing update
251
- const chatUpdate = data.chatUpdates[chatId] || {};
252
- data.chatUpdates[chatId] = concatChats(chatUpdate, update);
253
- }
254
- }
255
- else if (conditionMatches === undefined) {
256
- // condition yet to be fulfilled
257
- data.chatUpdates[chatId] = update;
258
- }
259
- // otherwise -- condition not met, update is invalid
260
- // if the chat has been updated
261
- // ignore any existing chat delete
262
- if (data.chatDeletes.has(chatId)) {
263
- data.chatDeletes.delete(chatId);
264
- }
265
- }
266
- break;
267
- case 'chats.delete':
268
- for (const chatId of eventData) {
269
- if (!data.chatDeletes.has(chatId)) {
270
- data.chatDeletes.add(chatId);
271
- }
272
- // remove any prior updates & upserts
273
- if (data.chatUpdates[chatId]) {
274
- delete data.chatUpdates[chatId];
275
- }
276
- if (data.chatUpserts[chatId]) {
277
- delete data.chatUpserts[chatId];
278
- }
279
- if (data.historySets.chats[chatId]) {
280
- delete data.historySets.chats[chatId];
281
- }
282
- }
283
- break;
284
- case 'contacts.upsert':
285
- for (const contact of eventData) {
286
- let upsert = data.contactUpserts[contact.id];
287
- if (!upsert) {
288
- upsert = data.historySets.contacts[contact.id];
289
- if (upsert) {
290
- logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set');
291
- }
292
- }
293
- if (upsert) {
294
- upsert = Object.assign(upsert, trimUndefined(contact));
295
- }
296
- else {
297
- upsert = contact;
298
- data.contactUpserts[contact.id] = upsert;
299
- }
300
- if (data.contactUpdates[contact.id]) {
301
- upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
302
- delete data.contactUpdates[contact.id];
303
- }
304
- }
305
- break;
306
- case 'contacts.update':
307
- const contactUpdates = eventData;
308
- for (const update of contactUpdates) {
309
- const id = update.id;
310
- // merge into prior upsert
311
- const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
312
- if (upsert) {
313
- Object.assign(upsert, update);
314
- }
315
- else {
316
- // merge into prior update
317
- const contactUpdate = data.contactUpdates[id] || {};
318
- data.contactUpdates[id] = Object.assign(contactUpdate, update);
319
- }
320
- }
321
- break;
322
- case 'messages.upsert':
323
- const { messages, type } = eventData;
324
- for (const message of messages) {
325
- const key = stringifyMessageKey(message.key);
326
- let existing = data.messageUpserts[key]?.message;
327
- if (!existing) {
328
- existing = data.historySets.messages[key];
329
- if (existing) {
330
- logger.debug({ messageId: key }, 'absorbed message upsert in message set');
331
- }
332
- }
333
- if (existing) {
334
- message.messageTimestamp = existing.messageTimestamp;
335
- }
336
- if (data.messageUpdates[key]) {
337
- logger.debug('absorbed prior message update in message upsert');
338
- Object.assign(message, data.messageUpdates[key].update);
339
- delete data.messageUpdates[key];
340
- }
341
- if (data.historySets.messages[key]) {
342
- data.historySets.messages[key] = message;
343
- }
344
- else {
345
- data.messageUpserts[key] = {
346
- message,
347
- type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
348
- };
349
- }
350
- }
351
- break;
352
- case 'messages.update':
353
- const msgUpdates = eventData;
354
- for (const { key, update } of msgUpdates) {
355
- const keyStr = stringifyMessageKey(key);
356
- const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
357
- if (existing) {
358
- Object.assign(existing, update);
359
- // if the message was received & read by us
360
- // the chat counter must have been incremented
361
- // so we need to decrement it
362
- if (update.status === WAMessageStatus.READ && !key.fromMe) {
363
- decrementChatReadCounterIfMsgDidUnread(existing);
364
- }
365
- }
366
- else {
367
- const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} };
368
- Object.assign(msgUpdate.update, update);
369
- data.messageUpdates[keyStr] = msgUpdate;
370
- }
371
- }
372
- break;
373
- case 'messages.delete':
374
- const deleteData = eventData;
375
- if ('keys' in deleteData) {
376
- const { keys } = deleteData;
377
- for (const key of keys) {
378
- const keyStr = stringifyMessageKey(key);
379
- if (!data.messageDeletes[keyStr]) {
380
- data.messageDeletes[keyStr] = key;
381
- }
382
- if (data.messageUpserts[keyStr]) {
383
- delete data.messageUpserts[keyStr];
384
- }
385
- if (data.messageUpdates[keyStr]) {
386
- delete data.messageUpdates[keyStr];
387
- }
388
- }
389
- }
390
- else {
391
- // TODO: add support
392
- }
393
- break;
394
- case 'messages.reaction':
395
- const reactions = eventData;
396
- for (const { key, reaction } of reactions) {
397
- const keyStr = stringifyMessageKey(key);
398
- const existing = data.messageUpserts[keyStr];
399
- if (existing) {
400
- updateMessageWithReaction(existing.message, reaction);
401
- }
402
- else {
403
- data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
404
- updateMessageWithReaction(data.messageReactions[keyStr], reaction);
405
- }
406
- }
407
- break;
408
- case 'message-receipt.update':
409
- const receipts = eventData;
410
- for (const { key, receipt } of receipts) {
411
- const keyStr = stringifyMessageKey(key);
412
- const existing = data.messageUpserts[keyStr];
413
- if (existing) {
414
- updateMessageWithReceipt(existing.message, receipt);
415
- }
416
- else {
417
- data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
418
- updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
419
- }
420
- }
421
- break;
422
- case 'groups.update':
423
- const groupUpdates = eventData;
424
- for (const update of groupUpdates) {
425
- const id = update.id;
426
- const groupUpdate = data.groupUpdates[id] || {};
427
- if (!data.groupUpdates[id]) {
428
- data.groupUpdates[id] = Object.assign(groupUpdate, update);
429
- }
430
- }
431
- break;
432
- default:
433
- throw new Error(`"${event}" cannot be buffered`);
434
- }
435
- function absorbingChatUpdate(existing) {
436
- const chatId = existing.id;
437
- const update = data.chatUpdates[chatId];
438
- if (update) {
439
- const conditionMatches = update.conditional ? update.conditional(data) : true;
440
- if (conditionMatches) {
441
- delete update.conditional;
442
- logger.debug({ chatId }, 'absorbed chat update in existing chat');
443
- Object.assign(existing, concatChats(update, existing));
444
- delete data.chatUpdates[chatId];
445
- }
446
- else if (conditionMatches === false) {
447
- logger.debug({ chatId }, 'chat update condition fail, removing');
448
- delete data.chatUpdates[chatId];
449
- }
167
+ switch (event) {
168
+ case 'messaging-history.set':
169
+ for (const chat of eventData.chats) {
170
+ const existingChat = data.historySets.chats[chat.id];
171
+ if (existingChat) {
172
+ existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
450
173
  }
451
- }
452
- function decrementChatReadCounterIfMsgDidUnread(message) {
453
- // decrement chat unread counter
454
- // if the message has already been marked read by us
455
- const chatId = message.key.remoteJid;
456
- const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
457
- if (isRealMessage(message, '') &&
458
- shouldIncrementChatUnread(message) &&
459
- typeof chat?.unreadCount === 'number' &&
460
- chat.unreadCount > 0) {
461
- logger.debug({ chatId: chat.id }, 'decrementing chat counter');
462
- chat.unreadCount -= 1;
463
- if (chat.unreadCount === 0) {
464
- delete chat.unreadCount;
465
- }
174
+ if (!existingChat && !historyCache.has(chat.id)) {
175
+ data.historySets.chats[chat.id] = chat;
176
+ historyCache.add(chat.id);
177
+ absorbingChatUpdate(chat);
178
+ }
179
+ }
180
+ for (const contact of eventData.contacts) {
181
+ const existingContact = data.historySets.contacts[contact.id];
182
+ if (existingContact) {
183
+ Object.assign(existingContact, trimUndefined(contact));
184
+ } else {
185
+ const historyContactId = `c:${contact.id}`;
186
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName;
187
+ if (!historyCache.has(historyContactId) || hasAnyName) {
188
+ data.historySets.contacts[contact.id] = contact;
189
+ historyCache.add(historyContactId);
190
+ }
191
+ }
192
+ }
193
+ for (const message of eventData.messages) {
194
+ const key = stringifyMessageKey(message.key);
195
+ const existingMsg = data.historySets.messages[key];
196
+ if (!existingMsg && !historyCache.has(key)) {
197
+ data.historySets.messages[key] = message;
198
+ historyCache.add(key);
199
+ }
200
+ }
201
+ data.historySets.empty = false;
202
+ data.historySets.syncType = eventData.syncType;
203
+ data.historySets.progress = eventData.progress;
204
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
205
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
206
+ break;
207
+ case 'chats.upsert':
208
+ for (const chat of eventData) {
209
+ let upsert = data.chatUpserts[chat.id];
210
+ if (!upsert) {
211
+ upsert = data.historySets.chats[chat.id];
212
+ if (upsert) {
213
+ logger.debug({
214
+ chatId: chat.id
215
+ }, 'absorbed chat upsert in chat set');
216
+ }
217
+ }
218
+ if (upsert) {
219
+ upsert = concatChats(upsert, chat);
220
+ } else {
221
+ upsert = chat;
222
+ data.chatUpserts[chat.id] = upsert;
223
+ }
224
+ absorbingChatUpdate(upsert);
225
+ if (data.chatDeletes.has(chat.id)) {
226
+ data.chatDeletes.delete(chat.id);
227
+ }
228
+ }
229
+ break;
230
+ case 'chats.update':
231
+ for (const update of eventData) {
232
+ const chatId = update.id;
233
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
234
+ if (conditionMatches) {
235
+ delete update.conditional;
236
+ // if there is an existing upsert, merge the update into it
237
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
238
+ if (upsert) {
239
+ concatChats(upsert, update);
240
+ } else {
241
+ // merge the update into the existing update
242
+ const chatUpdate = data.chatUpdates[chatId] || {};
243
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update);
244
+ }
245
+ } else if (conditionMatches === undefined) {
246
+ // condition yet to be fulfilled
247
+ data.chatUpdates[chatId] = update;
248
+ }
249
+ // otherwise -- condition not met, update is invalid
250
+ // if the chat has been updated
251
+ // ignore any existing chat delete
252
+ if (data.chatDeletes.has(chatId)) {
253
+ data.chatDeletes.delete(chatId);
254
+ }
255
+ }
256
+ break;
257
+ case 'chats.delete':
258
+ for (const chatId of eventData) {
259
+ if (!data.chatDeletes.has(chatId)) {
260
+ data.chatDeletes.add(chatId);
261
+ }
262
+ // remove any prior updates & upserts
263
+ if (data.chatUpdates[chatId]) {
264
+ delete data.chatUpdates[chatId];
265
+ }
266
+ if (data.chatUpserts[chatId]) {
267
+ delete data.chatUpserts[chatId];
268
+ }
269
+ if (data.historySets.chats[chatId]) {
270
+ delete data.historySets.chats[chatId];
271
+ }
272
+ }
273
+ break;
274
+ case 'contacts.upsert':
275
+ for (const contact of eventData) {
276
+ let upsert = data.contactUpserts[contact.id];
277
+ if (!upsert) {
278
+ upsert = data.historySets.contacts[contact.id];
279
+ if (upsert) {
280
+ logger.debug({
281
+ contactId: contact.id
282
+ }, 'absorbed contact upsert in contact set');
283
+ }
466
284
  }
285
+ if (upsert) {
286
+ upsert = Object.assign(upsert, trimUndefined(contact));
287
+ } else {
288
+ upsert = contact;
289
+ data.contactUpserts[contact.id] = upsert;
290
+ }
291
+ if (data.contactUpdates[contact.id]) {
292
+ upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
293
+ delete data.contactUpdates[contact.id];
294
+ }
295
+ }
296
+ break;
297
+ case 'contacts.update':
298
+ const contactUpdates = eventData;
299
+ for (const update of contactUpdates) {
300
+ const id = update.id;
301
+ // merge into prior upsert
302
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
303
+ if (upsert) {
304
+ Object.assign(upsert, update);
305
+ } else {
306
+ // merge into prior update
307
+ const contactUpdate = data.contactUpdates[id] || {};
308
+ data.contactUpdates[id] = Object.assign(contactUpdate, update);
309
+ }
310
+ }
311
+ break;
312
+ case 'messages.upsert':
313
+ const {
314
+ messages,
315
+ type
316
+ } = eventData;
317
+ for (const message of messages) {
318
+ const key = stringifyMessageKey(message.key);
319
+ let existing = data.messageUpserts[key]?.message;
320
+ if (!existing) {
321
+ existing = data.historySets.messages[key];
322
+ if (existing) {
323
+ logger.debug({
324
+ messageId: key
325
+ }, 'absorbed message upsert in message set');
326
+ }
327
+ }
328
+ if (existing) {
329
+ message.messageTimestamp = existing.messageTimestamp;
330
+ }
331
+ if (data.messageUpdates[key]) {
332
+ logger.debug('absorbed prior message update in message upsert');
333
+ Object.assign(message, data.messageUpdates[key].update);
334
+ delete data.messageUpdates[key];
335
+ }
336
+ if (data.historySets.messages[key]) {
337
+ data.historySets.messages[key] = message;
338
+ } else {
339
+ data.messageUpserts[key] = {
340
+ message,
341
+ type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
342
+ };
343
+ }
344
+ }
345
+ break;
346
+ case 'messages.update':
347
+ const msgUpdates = eventData;
348
+ for (const {
349
+ key,
350
+ update
351
+ } of msgUpdates) {
352
+ const keyStr = stringifyMessageKey(key);
353
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
354
+ if (existing) {
355
+ Object.assign(existing, update);
356
+ // if the message was received & read by us
357
+ // the chat counter must have been incremented
358
+ // so we need to decrement it
359
+ if (update.status === WAMessageStatus.READ && !key.fromMe) {
360
+ decrementChatReadCounterIfMsgDidUnread(existing);
361
+ }
362
+ } else {
363
+ const msgUpdate = data.messageUpdates[keyStr] || {
364
+ key,
365
+ update: {}
366
+ };
367
+ Object.assign(msgUpdate.update, update);
368
+ data.messageUpdates[keyStr] = msgUpdate;
369
+ }
370
+ }
371
+ break;
372
+ case 'messages.delete':
373
+ const deleteData = eventData;
374
+ if ('keys' in deleteData) {
375
+ const {
376
+ keys
377
+ } = deleteData;
378
+ for (const key of keys) {
379
+ const keyStr = stringifyMessageKey(key);
380
+ if (!data.messageDeletes[keyStr]) {
381
+ data.messageDeletes[keyStr] = key;
382
+ }
383
+ if (data.messageUpserts[keyStr]) {
384
+ delete data.messageUpserts[keyStr];
385
+ }
386
+ if (data.messageUpdates[keyStr]) {
387
+ delete data.messageUpdates[keyStr];
388
+ }
389
+ }
390
+ } else {
391
+ // TODO: add support
392
+ }
393
+ break;
394
+ case 'messages.reaction':
395
+ const reactions = eventData;
396
+ for (const {
397
+ key,
398
+ reaction
399
+ } of reactions) {
400
+ const keyStr = stringifyMessageKey(key);
401
+ const existing = data.messageUpserts[keyStr];
402
+ if (existing) {
403
+ updateMessageWithReaction(existing.message, reaction);
404
+ } else {
405
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || {
406
+ key,
407
+ reactions: []
408
+ };
409
+ updateMessageWithReaction(data.messageReactions[keyStr], reaction);
410
+ }
411
+ }
412
+ break;
413
+ case 'message-receipt.update':
414
+ const receipts = eventData;
415
+ for (const {
416
+ key,
417
+ receipt
418
+ } of receipts) {
419
+ const keyStr = stringifyMessageKey(key);
420
+ const existing = data.messageUpserts[keyStr];
421
+ if (existing) {
422
+ updateMessageWithReceipt(existing.message, receipt);
423
+ } else {
424
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || {
425
+ key,
426
+ userReceipt: []
427
+ };
428
+ updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
429
+ }
430
+ }
431
+ break;
432
+ case 'groups.update':
433
+ const groupUpdates = eventData;
434
+ for (const update of groupUpdates) {
435
+ const id = update.id;
436
+ const groupUpdate = data.groupUpdates[id] || {};
437
+ if (!data.groupUpdates[id]) {
438
+ data.groupUpdates[id] = Object.assign(groupUpdate, update);
439
+ }
440
+ }
441
+ break;
442
+ default:
443
+ throw new Error(`"${event}" cannot be buffered`);
444
+ }
445
+ function absorbingChatUpdate(existing) {
446
+ const chatId = existing.id;
447
+ const update = data.chatUpdates[chatId];
448
+ if (update) {
449
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
450
+ if (conditionMatches) {
451
+ delete update.conditional;
452
+ logger.debug({
453
+ chatId
454
+ }, 'absorbed chat update in existing chat');
455
+ Object.assign(existing, concatChats(update, existing));
456
+ delete data.chatUpdates[chatId];
457
+ } else if (conditionMatches === false) {
458
+ logger.debug({
459
+ chatId
460
+ }, 'chat update condition fail, removing');
461
+ delete data.chatUpdates[chatId];
462
+ }
467
463
  }
464
+ }
465
+ function decrementChatReadCounterIfMsgDidUnread(message) {
466
+ // decrement chat unread counter
467
+ // if the message has already been marked read by us
468
+ const chatId = message.key.remoteJid;
469
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
470
+ if (isRealMessage(message, '') && shouldIncrementChatUnread(message) && typeof chat?.unreadCount === 'number' && chat.unreadCount > 0) {
471
+ logger.debug({
472
+ chatId: chat.id
473
+ }, 'decrementing chat counter');
474
+ chat.unreadCount -= 1;
475
+ if (chat.unreadCount === 0) {
476
+ delete chat.unreadCount;
477
+ }
478
+ }
479
+ }
468
480
  }
469
481
  function consolidateEvents(data) {
470
- const map = {};
471
- if (!data.historySets.empty) {
472
- map['messaging-history.set'] = {
473
- chats: Object.values(data.historySets.chats),
474
- messages: Object.values(data.historySets.messages),
475
- contacts: Object.values(data.historySets.contacts),
476
- syncType: data.historySets.syncType,
477
- progress: data.historySets.progress,
478
- isLatest: data.historySets.isLatest,
479
- peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
480
- };
481
- }
482
- const chatUpsertList = Object.values(data.chatUpserts);
483
- if (chatUpsertList.length) {
484
- map['chats.upsert'] = chatUpsertList;
485
- }
486
- const chatUpdateList = Object.values(data.chatUpdates);
487
- if (chatUpdateList.length) {
488
- map['chats.update'] = chatUpdateList;
489
- }
490
- const chatDeleteList = Array.from(data.chatDeletes);
491
- if (chatDeleteList.length) {
492
- map['chats.delete'] = chatDeleteList;
493
- }
494
- const messageUpsertList = Object.values(data.messageUpserts);
495
- if (messageUpsertList.length) {
496
- const type = messageUpsertList[0].type;
497
- map['messages.upsert'] = {
498
- messages: messageUpsertList.map(m => m.message),
499
- type
500
- };
501
- }
502
- const messageUpdateList = Object.values(data.messageUpdates);
503
- if (messageUpdateList.length) {
504
- map['messages.update'] = messageUpdateList;
505
- }
506
- const messageDeleteList = Object.values(data.messageDeletes);
507
- if (messageDeleteList.length) {
508
- map['messages.delete'] = { keys: messageDeleteList };
509
- }
510
- const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
511
- if (messageReactionList.length) {
512
- map['messages.reaction'] = messageReactionList;
513
- }
514
- const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
515
- if (messageReceiptList.length) {
516
- map['message-receipt.update'] = messageReceiptList;
517
- }
518
- const contactUpsertList = Object.values(data.contactUpserts);
519
- if (contactUpsertList.length) {
520
- map['contacts.upsert'] = contactUpsertList;
521
- }
522
- const contactUpdateList = Object.values(data.contactUpdates);
523
- if (contactUpdateList.length) {
524
- map['contacts.update'] = contactUpdateList;
525
- }
526
- const groupUpdateList = Object.values(data.groupUpdates);
527
- if (groupUpdateList.length) {
528
- map['groups.update'] = groupUpdateList;
529
- }
530
- return map;
482
+ const map = {};
483
+ if (!data.historySets.empty) {
484
+ map['messaging-history.set'] = {
485
+ chats: Object.values(data.historySets.chats),
486
+ messages: Object.values(data.historySets.messages),
487
+ contacts: Object.values(data.historySets.contacts),
488
+ syncType: data.historySets.syncType,
489
+ progress: data.historySets.progress,
490
+ isLatest: data.historySets.isLatest,
491
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
492
+ };
493
+ }
494
+ const chatUpsertList = Object.values(data.chatUpserts);
495
+ if (chatUpsertList.length) {
496
+ map['chats.upsert'] = chatUpsertList;
497
+ }
498
+ const chatUpdateList = Object.values(data.chatUpdates);
499
+ if (chatUpdateList.length) {
500
+ map['chats.update'] = chatUpdateList;
501
+ }
502
+ const chatDeleteList = Array.from(data.chatDeletes);
503
+ if (chatDeleteList.length) {
504
+ map['chats.delete'] = chatDeleteList;
505
+ }
506
+ const messageUpsertList = Object.values(data.messageUpserts);
507
+ if (messageUpsertList.length) {
508
+ const type = messageUpsertList[0].type;
509
+ map['messages.upsert'] = {
510
+ messages: messageUpsertList.map(m => m.message),
511
+ type
512
+ };
513
+ }
514
+ const messageUpdateList = Object.values(data.messageUpdates);
515
+ if (messageUpdateList.length) {
516
+ map['messages.update'] = messageUpdateList;
517
+ }
518
+ const messageDeleteList = Object.values(data.messageDeletes);
519
+ if (messageDeleteList.length) {
520
+ map['messages.delete'] = {
521
+ keys: messageDeleteList
522
+ };
523
+ }
524
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({
525
+ key,
526
+ reactions
527
+ }) => reactions.flatMap(reaction => ({
528
+ key,
529
+ reaction
530
+ })));
531
+ if (messageReactionList.length) {
532
+ map['messages.reaction'] = messageReactionList;
533
+ }
534
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({
535
+ key,
536
+ userReceipt
537
+ }) => userReceipt.flatMap(receipt => ({
538
+ key,
539
+ receipt
540
+ })));
541
+ if (messageReceiptList.length) {
542
+ map['message-receipt.update'] = messageReceiptList;
543
+ }
544
+ const contactUpsertList = Object.values(data.contactUpserts);
545
+ if (contactUpsertList.length) {
546
+ map['contacts.upsert'] = contactUpsertList;
547
+ }
548
+ const contactUpdateList = Object.values(data.contactUpdates);
549
+ if (contactUpdateList.length) {
550
+ map['contacts.update'] = contactUpdateList;
551
+ }
552
+ const groupUpdateList = Object.values(data.groupUpdates);
553
+ if (groupUpdateList.length) {
554
+ map['groups.update'] = groupUpdateList;
555
+ }
556
+ return map;
531
557
  }
532
558
  function concatChats(a, b) {
533
- if (b.unreadCount === null && // neutralize unread counter
534
- a.unreadCount < 0) {
535
- a.unreadCount = undefined;
536
- b.unreadCount = undefined;
537
- }
538
- if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
539
- b = { ...b };
540
- if (b.unreadCount >= 0) {
541
- b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
542
- }
559
+ if (b.unreadCount === null &&
560
+ // neutralize unread counter
561
+ a.unreadCount < 0) {
562
+ a.unreadCount = undefined;
563
+ b.unreadCount = undefined;
564
+ }
565
+ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
566
+ b = {
567
+ ...b
568
+ };
569
+ if (b.unreadCount >= 0) {
570
+ b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
543
571
  }
544
- return Object.assign(a, b);
572
+ }
573
+ return Object.assign(a, b);
545
574
  }
546
- const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
575
+ const stringifyMessageKey = key => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
547
576
  //# sourceMappingURL=event-buffer.js.map