@mrlegendbot/baileys 1.2.4 → 1.2.6

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