@boruto_vk7/baileys 1.0.0

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