@zelynskybail/baileys 0.0.0-stage → 2.6.28

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 (226) hide show
  1. package/BUILD_STATUS.md +21 -0
  2. package/CHANGELOG.md +17 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE.md +9 -0
  5. package/README.md +165 -2
  6. package/THANKS.md +7 -0
  7. package/THIRD_PARTY_NOTICES.md +8 -0
  8. package/WAProto/GenerateStatics.sh +3 -0
  9. package/WAProto/WAProto.proto +6035 -0
  10. package/WAProto/fix-imports.js +81 -0
  11. package/WAProto/index.d.ts +2 -0
  12. package/WAProto/index.js +132326 -0
  13. package/lib/Builders/advanced.d.ts +14 -0
  14. package/lib/Builders/advanced.js +142 -0
  15. package/lib/Builders/group-status.d.ts +9 -0
  16. package/lib/Builders/group-status.js +19 -0
  17. package/lib/Builders/index.d.ts +62 -0
  18. package/lib/Builders/index.js +242 -0
  19. package/lib/Defaults/index.d.ts +74 -0
  20. package/lib/Defaults/index.js +136 -0
  21. package/lib/Modded/MessageBuilder.js +3222 -0
  22. package/lib/Modded/message_builder.d.ts +43 -0
  23. package/lib/Modded/message_builder.js +2 -0
  24. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  25. package/lib/Signal/Group/ciphertext-message.js +11 -0
  26. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  27. package/lib/Signal/Group/group-session-builder.js +29 -0
  28. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  29. package/lib/Signal/Group/group_cipher.js +81 -0
  30. package/lib/Signal/Group/index.d.ts +12 -0
  31. package/lib/Signal/Group/index.js +11 -0
  32. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  33. package/lib/Signal/Group/keyhelper.js +17 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  35. package/lib/Signal/Group/sender-chain-key.js +25 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  38. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  39. package/lib/Signal/Group/sender-key-message.js +65 -0
  40. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  41. package/lib/Signal/Group/sender-key-name.js +47 -0
  42. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  43. package/lib/Signal/Group/sender-key-record.js +40 -0
  44. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  45. package/lib/Signal/Group/sender-key-state.js +83 -0
  46. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  47. package/lib/Signal/Group/sender-message-key.js +25 -0
  48. package/lib/Signal/libsignal.d.ts +5 -0
  49. package/lib/Signal/libsignal.js +402 -0
  50. package/lib/Signal/lid-mapping.d.ts +19 -0
  51. package/lib/Signal/lid-mapping.js +270 -0
  52. package/lib/Socket/Client/index.d.ts +3 -0
  53. package/lib/Socket/Client/index.js +2 -0
  54. package/lib/Socket/Client/types.d.ts +16 -0
  55. package/lib/Socket/Client/types.js +10 -0
  56. package/lib/Socket/Client/websocket.d.ts +13 -0
  57. package/lib/Socket/Client/websocket.js +53 -0
  58. package/lib/Socket/business.d.ts +536 -0
  59. package/lib/Socket/business.js +421 -0
  60. package/lib/Socket/chats.d.ts +111 -0
  61. package/lib/Socket/chats.js +990 -0
  62. package/lib/Socket/communities.d.ts +645 -0
  63. package/lib/Socket/communities.js +430 -0
  64. package/lib/Socket/dugong.d.ts +130 -0
  65. package/lib/Socket/dugong.js +767 -0
  66. package/lib/Socket/groups.d.ts +150 -0
  67. package/lib/Socket/groups.js +326 -0
  68. package/lib/Socket/index.d.ts +657 -0
  69. package/lib/Socket/index.js +26 -0
  70. package/lib/Socket/messages-recv.d.ts +238 -0
  71. package/lib/Socket/messages-recv.js +1307 -0
  72. package/lib/Socket/messages-send.d.ts +579 -0
  73. package/lib/Socket/messages-send.js +1594 -0
  74. package/lib/Socket/mex.d.ts +3 -0
  75. package/lib/Socket/mex.js +47 -0
  76. package/lib/Socket/newsletter.d.ts +177 -0
  77. package/lib/Socket/newsletter.js +314 -0
  78. package/lib/Socket/socket.d.ts +55 -0
  79. package/lib/Socket/socket.js +935 -0
  80. package/lib/Types/Auth.d.ts +116 -0
  81. package/lib/Types/Auth.js +1 -0
  82. package/lib/Types/Bussines.d.ts +37 -0
  83. package/lib/Types/Bussines.js +1 -0
  84. package/lib/Types/Call.d.ts +15 -0
  85. package/lib/Types/Call.js +1 -0
  86. package/lib/Types/Chat.d.ts +123 -0
  87. package/lib/Types/Chat.js +7 -0
  88. package/lib/Types/Contact.d.ts +24 -0
  89. package/lib/Types/Contact.js +1 -0
  90. package/lib/Types/Events.d.ts +237 -0
  91. package/lib/Types/Events.js +1 -0
  92. package/lib/Types/GroupMetadata.d.ts +68 -0
  93. package/lib/Types/GroupMetadata.js +1 -0
  94. package/lib/Types/Label.d.ts +47 -0
  95. package/lib/Types/Label.js +24 -0
  96. package/lib/Types/LabelAssociation.d.ts +30 -0
  97. package/lib/Types/LabelAssociation.js +6 -0
  98. package/lib/Types/Message.d.ts +422 -0
  99. package/lib/Types/Message.js +10 -0
  100. package/lib/Types/Newsletter.d.ts +135 -0
  101. package/lib/Types/Newsletter.js +30 -0
  102. package/lib/Types/Product.d.ts +79 -0
  103. package/lib/Types/Product.js +1 -0
  104. package/lib/Types/Signal.d.ts +76 -0
  105. package/lib/Types/Signal.js +1 -0
  106. package/lib/Types/Socket.d.ts +154 -0
  107. package/lib/Types/Socket.js +2 -0
  108. package/lib/Types/State.d.ts +39 -0
  109. package/lib/Types/State.js +12 -0
  110. package/lib/Types/USync.d.ts +26 -0
  111. package/lib/Types/USync.js +1 -0
  112. package/lib/Types/index.d.ts +66 -0
  113. package/lib/Types/index.js +32 -0
  114. package/lib/Utils/auth-utils.d.ts +19 -0
  115. package/lib/Utils/auth-utils.js +289 -0
  116. package/lib/Utils/browser-utils.d.ts +4 -0
  117. package/lib/Utils/browser-utils.js +27 -0
  118. package/lib/Utils/business.d.ts +23 -0
  119. package/lib/Utils/business.js +230 -0
  120. package/lib/Utils/chat-utils.d.ts +70 -0
  121. package/lib/Utils/chat-utils.js +811 -0
  122. package/lib/Utils/crypto.d.ts +37 -0
  123. package/lib/Utils/crypto.js +117 -0
  124. package/lib/Utils/decode-wa-message.d.ts +48 -0
  125. package/lib/Utils/decode-wa-message.js +282 -0
  126. package/lib/Utils/event-buffer.d.ts +34 -0
  127. package/lib/Utils/event-buffer.js +573 -0
  128. package/lib/Utils/generics.d.ts +91 -0
  129. package/lib/Utils/generics.js +383 -0
  130. package/lib/Utils/history.d.ts +22 -0
  131. package/lib/Utils/history.js +130 -0
  132. package/lib/Utils/identity-change-handler.d.ts +37 -0
  133. package/lib/Utils/identity-change-handler.js +48 -0
  134. package/lib/Utils/index.d.ts +24 -0
  135. package/lib/Utils/index.js +24 -0
  136. package/lib/Utils/link-preview.d.ts +21 -0
  137. package/lib/Utils/link-preview.js +84 -0
  138. package/lib/Utils/logger.d.ts +13 -0
  139. package/lib/Utils/logger.js +2 -0
  140. package/lib/Utils/lt-hash.d.ts +8 -0
  141. package/lib/Utils/lt-hash.js +7 -0
  142. package/lib/Utils/make-mutex.d.ts +9 -0
  143. package/lib/Utils/make-mutex.js +32 -0
  144. package/lib/Utils/message-retry-manager.d.ts +110 -0
  145. package/lib/Utils/message-retry-manager.js +224 -0
  146. package/lib/Utils/message-tools.d.ts +31 -0
  147. package/lib/Utils/message-tools.js +182 -0
  148. package/lib/Utils/messages-media.d.ts +130 -0
  149. package/lib/Utils/messages-media.js +781 -0
  150. package/lib/Utils/messages.d.ts +91 -0
  151. package/lib/Utils/messages.js +1239 -0
  152. package/lib/Utils/noise-handler.d.ts +20 -0
  153. package/lib/Utils/noise-handler.js +200 -0
  154. package/lib/Utils/offline-node-processor.d.ts +17 -0
  155. package/lib/Utils/offline-node-processor.js +68 -0
  156. package/lib/Utils/performance.d.ts +3 -0
  157. package/lib/Utils/performance.js +35 -0
  158. package/lib/Utils/pre-key-manager.d.ts +28 -0
  159. package/lib/Utils/pre-key-manager.js +105 -0
  160. package/lib/Utils/process-message.d.ts +60 -0
  161. package/lib/Utils/process-message.js +527 -0
  162. package/lib/Utils/reporting-utils.d.ts +11 -0
  163. package/lib/Utils/reporting-utils.js +257 -0
  164. package/lib/Utils/rich-messages.d.ts +277 -0
  165. package/lib/Utils/rich-messages.js +1143 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +158 -0
  168. package/lib/Utils/stanza-ack.d.ts +11 -0
  169. package/lib/Utils/stanza-ack.js +37 -0
  170. package/lib/Utils/sticker-pack.d.ts +10 -0
  171. package/lib/Utils/sticker-pack.js +111 -0
  172. package/lib/Utils/sync-action-utils.d.ts +19 -0
  173. package/lib/Utils/sync-action-utils.js +47 -0
  174. package/lib/Utils/tc-token-utils.d.ts +12 -0
  175. package/lib/Utils/tc-token-utils.js +17 -0
  176. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  177. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  178. package/lib/Utils/validate-connection.d.ts +11 -0
  179. package/lib/Utils/validate-connection.js +199 -0
  180. package/lib/VoIP/index.d.ts +18 -0
  181. package/lib/VoIP/index.js +81 -0
  182. package/lib/WABinary/constants.d.ts +28 -0
  183. package/lib/WABinary/constants.js +1300 -0
  184. package/lib/WABinary/decode.d.ts +7 -0
  185. package/lib/WABinary/decode.js +261 -0
  186. package/lib/WABinary/encode.d.ts +3 -0
  187. package/lib/WABinary/encode.js +219 -0
  188. package/lib/WABinary/generic-utils.d.ts +17 -0
  189. package/lib/WABinary/generic-utils.js +190 -0
  190. package/lib/WABinary/index.d.ts +6 -0
  191. package/lib/WABinary/index.js +5 -0
  192. package/lib/WABinary/jid-utils.d.ts +48 -0
  193. package/lib/WABinary/jid-utils.js +95 -0
  194. package/lib/WABinary/types.d.ts +19 -0
  195. package/lib/WABinary/types.js +1 -0
  196. package/lib/WAM/BinaryInfo.d.ts +9 -0
  197. package/lib/WAM/BinaryInfo.js +9 -0
  198. package/lib/WAM/constants.d.ts +40 -0
  199. package/lib/WAM/constants.js +22852 -0
  200. package/lib/WAM/encode.d.ts +3 -0
  201. package/lib/WAM/encode.js +149 -0
  202. package/lib/WAM/index.d.ts +4 -0
  203. package/lib/WAM/index.js +3 -0
  204. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  205. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  206. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  207. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  208. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  209. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  210. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  211. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  212. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  213. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  214. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  215. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  216. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  217. package/lib/WAUSync/Protocols/index.js +4 -0
  218. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  219. package/lib/WAUSync/USyncQuery.js +93 -0
  220. package/lib/WAUSync/USyncUser.d.ts +13 -0
  221. package/lib/WAUSync/USyncUser.js +22 -0
  222. package/lib/WAUSync/index.d.ts +4 -0
  223. package/lib/WAUSync/index.js +3 -0
  224. package/lib/index.d.ts +14 -0
  225. package/lib/index.js +14 -0
  226. package/package.json +128 -4
@@ -0,0 +1,573 @@
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
+ };
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,
198
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
199
+ eventData, logger) {
200
+ switch (event) {
201
+ case 'messaging-history.set':
202
+ for (const chat of eventData.chats) {
203
+ const id = chat.id || '';
204
+ const existingChat = data.historySets.chats[id];
205
+ if (existingChat) {
206
+ existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
207
+ }
208
+ if (!existingChat && !historyCache.has(id)) {
209
+ data.historySets.chats[id] = chat;
210
+ historyCache.add(id);
211
+ absorbingChatUpdate(chat);
212
+ }
213
+ }
214
+ for (const contact of eventData.contacts) {
215
+ const existingContact = data.historySets.contacts[contact.id];
216
+ if (existingContact) {
217
+ Object.assign(existingContact, trimUndefined(contact));
218
+ }
219
+ else {
220
+ const historyContactId = `c:${contact.id}`;
221
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName;
222
+ if (!historyCache.has(historyContactId) || hasAnyName) {
223
+ data.historySets.contacts[contact.id] = contact;
224
+ historyCache.add(historyContactId);
225
+ }
226
+ }
227
+ }
228
+ for (const message of eventData.messages) {
229
+ const key = stringifyMessageKey(message.key);
230
+ const existingMsg = data.historySets.messages[key];
231
+ if (!existingMsg && !historyCache.has(key)) {
232
+ data.historySets.messages[key] = message;
233
+ historyCache.add(key);
234
+ }
235
+ }
236
+ data.historySets.empty = false;
237
+ data.historySets.syncType = eventData.syncType;
238
+ data.historySets.progress = eventData.progress;
239
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
240
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
241
+ break;
242
+ case 'chats.upsert':
243
+ for (const chat of eventData) {
244
+ const id = chat.id || '';
245
+ let upsert = data.chatUpserts[id];
246
+ if (id && !upsert) {
247
+ upsert = data.historySets.chats[id];
248
+ if (upsert) {
249
+ logger.debug({ chatId: id }, 'absorbed chat upsert in chat set');
250
+ }
251
+ }
252
+ if (upsert) {
253
+ upsert = concatChats(upsert, chat);
254
+ }
255
+ else {
256
+ upsert = chat;
257
+ data.chatUpserts[id] = upsert;
258
+ }
259
+ absorbingChatUpdate(upsert);
260
+ if (data.chatDeletes.has(id)) {
261
+ data.chatDeletes.delete(id);
262
+ }
263
+ }
264
+ break;
265
+ case 'chats.update':
266
+ for (const update of eventData) {
267
+ const chatId = update.id;
268
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
269
+ if (conditionMatches) {
270
+ delete update.conditional;
271
+ // if there is an existing upsert, merge the update into it
272
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
273
+ if (upsert) {
274
+ concatChats(upsert, update);
275
+ }
276
+ else {
277
+ // merge the update into the existing update
278
+ const chatUpdate = data.chatUpdates[chatId] || {};
279
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update);
280
+ }
281
+ }
282
+ else if (conditionMatches === undefined) {
283
+ // condition yet to be fulfilled
284
+ data.chatUpdates[chatId] = update;
285
+ }
286
+ // otherwise -- condition not met, update is invalid
287
+ // if the chat has been updated
288
+ // ignore any existing chat delete
289
+ if (data.chatDeletes.has(chatId)) {
290
+ data.chatDeletes.delete(chatId);
291
+ }
292
+ }
293
+ break;
294
+ case 'chats.delete':
295
+ for (const chatId of eventData) {
296
+ if (!data.chatDeletes.has(chatId)) {
297
+ data.chatDeletes.add(chatId);
298
+ }
299
+ // remove any prior updates & upserts
300
+ if (data.chatUpdates[chatId]) {
301
+ delete data.chatUpdates[chatId];
302
+ }
303
+ if (data.chatUpserts[chatId]) {
304
+ delete data.chatUpserts[chatId];
305
+ }
306
+ if (data.historySets.chats[chatId]) {
307
+ delete data.historySets.chats[chatId];
308
+ }
309
+ }
310
+ break;
311
+ case 'contacts.upsert':
312
+ for (const contact of eventData) {
313
+ let upsert = data.contactUpserts[contact.id];
314
+ if (!upsert) {
315
+ upsert = data.historySets.contacts[contact.id];
316
+ if (upsert) {
317
+ logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set');
318
+ }
319
+ }
320
+ if (upsert) {
321
+ upsert = Object.assign(upsert, trimUndefined(contact));
322
+ }
323
+ else {
324
+ upsert = contact;
325
+ data.contactUpserts[contact.id] = upsert;
326
+ }
327
+ if (data.contactUpdates[contact.id]) {
328
+ upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
329
+ delete data.contactUpdates[contact.id];
330
+ }
331
+ }
332
+ break;
333
+ case 'contacts.update':
334
+ const contactUpdates = eventData;
335
+ for (const update of contactUpdates) {
336
+ const id = update.id;
337
+ // merge into prior upsert
338
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
339
+ if (upsert) {
340
+ Object.assign(upsert, update);
341
+ }
342
+ else {
343
+ // merge into prior update
344
+ const contactUpdate = data.contactUpdates[id] || {};
345
+ data.contactUpdates[id] = Object.assign(contactUpdate, update);
346
+ }
347
+ }
348
+ break;
349
+ case 'messages.upsert':
350
+ const { messages, type } = eventData;
351
+ for (const message of messages) {
352
+ const key = stringifyMessageKey(message.key);
353
+ let existing = data.messageUpserts[key]?.message;
354
+ if (!existing) {
355
+ existing = data.historySets.messages[key];
356
+ if (existing) {
357
+ logger.debug({ messageId: key }, 'absorbed message upsert in message set');
358
+ }
359
+ }
360
+ if (existing) {
361
+ message.messageTimestamp = existing.messageTimestamp;
362
+ }
363
+ if (data.messageUpdates[key]) {
364
+ logger.debug('absorbed prior message update in message upsert');
365
+ Object.assign(message, data.messageUpdates[key].update);
366
+ delete data.messageUpdates[key];
367
+ }
368
+ if (data.historySets.messages[key]) {
369
+ data.historySets.messages[key] = message;
370
+ }
371
+ else {
372
+ data.messageUpserts[key] = {
373
+ message,
374
+ type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
375
+ };
376
+ }
377
+ }
378
+ break;
379
+ case 'messages.update':
380
+ const msgUpdates = eventData;
381
+ for (const { key, update } of msgUpdates) {
382
+ const keyStr = stringifyMessageKey(key);
383
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
384
+ if (existing) {
385
+ Object.assign(existing, update);
386
+ // if the message was received & read by us
387
+ // the chat counter must have been incremented
388
+ // so we need to decrement it
389
+ if (update.status === WAMessageStatus.READ && !key.fromMe) {
390
+ decrementChatReadCounterIfMsgDidUnread(existing);
391
+ }
392
+ }
393
+ else {
394
+ const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} };
395
+ Object.assign(msgUpdate.update, update);
396
+ data.messageUpdates[keyStr] = msgUpdate;
397
+ }
398
+ }
399
+ break;
400
+ case 'messages.delete':
401
+ const deleteData = eventData;
402
+ if ('keys' in deleteData) {
403
+ const { keys } = deleteData;
404
+ for (const key of keys) {
405
+ const keyStr = stringifyMessageKey(key);
406
+ if (!data.messageDeletes[keyStr]) {
407
+ data.messageDeletes[keyStr] = key;
408
+ }
409
+ if (data.messageUpserts[keyStr]) {
410
+ delete data.messageUpserts[keyStr];
411
+ }
412
+ if (data.messageUpdates[keyStr]) {
413
+ delete data.messageUpdates[keyStr];
414
+ }
415
+ }
416
+ }
417
+ else {
418
+ // TODO: add support
419
+ }
420
+ break;
421
+ case 'messages.reaction':
422
+ const reactions = eventData;
423
+ for (const { key, reaction } of reactions) {
424
+ const keyStr = stringifyMessageKey(key);
425
+ const existing = data.messageUpserts[keyStr];
426
+ if (existing) {
427
+ updateMessageWithReaction(existing.message, reaction);
428
+ }
429
+ else {
430
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
431
+ updateMessageWithReaction(data.messageReactions[keyStr], reaction);
432
+ }
433
+ }
434
+ break;
435
+ case 'message-receipt.update':
436
+ const receipts = eventData;
437
+ for (const { key, receipt } of receipts) {
438
+ const keyStr = stringifyMessageKey(key);
439
+ const existing = data.messageUpserts[keyStr];
440
+ if (existing) {
441
+ updateMessageWithReceipt(existing.message, receipt);
442
+ }
443
+ else {
444
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
445
+ updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
446
+ }
447
+ }
448
+ break;
449
+ case 'groups.update':
450
+ const groupUpdates = eventData;
451
+ for (const update of groupUpdates) {
452
+ const id = update.id;
453
+ const groupUpdate = data.groupUpdates[id] || {};
454
+ if (!data.groupUpdates[id]) {
455
+ data.groupUpdates[id] = Object.assign(groupUpdate, update);
456
+ }
457
+ }
458
+ break;
459
+ default:
460
+ throw new Error(`"${event}" cannot be buffered`);
461
+ }
462
+ function absorbingChatUpdate(existing) {
463
+ const chatId = existing.id || '';
464
+ const update = data.chatUpdates[chatId];
465
+ if (update) {
466
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
467
+ if (conditionMatches) {
468
+ delete update.conditional;
469
+ logger.debug({ chatId }, 'absorbed chat update in existing chat');
470
+ Object.assign(existing, concatChats(update, existing));
471
+ delete data.chatUpdates[chatId];
472
+ }
473
+ else if (conditionMatches === false) {
474
+ logger.debug({ chatId }, 'chat update condition fail, removing');
475
+ delete data.chatUpdates[chatId];
476
+ }
477
+ }
478
+ }
479
+ function decrementChatReadCounterIfMsgDidUnread(message) {
480
+ // decrement chat unread counter
481
+ // if the message has already been marked read by us
482
+ const chatId = message.key.remoteJid;
483
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
484
+ if (isRealMessage(message) &&
485
+ shouldIncrementChatUnread(message) &&
486
+ typeof chat?.unreadCount === 'number' &&
487
+ chat.unreadCount > 0) {
488
+ logger.debug({ chatId: chat.id }, 'decrementing chat counter');
489
+ chat.unreadCount -= 1;
490
+ if (chat.unreadCount === 0) {
491
+ delete chat.unreadCount;
492
+ }
493
+ }
494
+ }
495
+ }
496
+ function consolidateEvents(data) {
497
+ const map = {};
498
+ if (!data.historySets.empty) {
499
+ map['messaging-history.set'] = {
500
+ chats: Object.values(data.historySets.chats),
501
+ messages: Object.values(data.historySets.messages),
502
+ contacts: Object.values(data.historySets.contacts),
503
+ syncType: data.historySets.syncType,
504
+ progress: data.historySets.progress,
505
+ isLatest: data.historySets.isLatest,
506
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
507
+ };
508
+ }
509
+ const chatUpsertList = Object.values(data.chatUpserts);
510
+ if (chatUpsertList.length) {
511
+ map['chats.upsert'] = chatUpsertList;
512
+ }
513
+ const chatUpdateList = Object.values(data.chatUpdates);
514
+ if (chatUpdateList.length) {
515
+ map['chats.update'] = chatUpdateList;
516
+ }
517
+ const chatDeleteList = Array.from(data.chatDeletes);
518
+ if (chatDeleteList.length) {
519
+ map['chats.delete'] = chatDeleteList;
520
+ }
521
+ const messageUpsertList = Object.values(data.messageUpserts);
522
+ if (messageUpsertList.length) {
523
+ const type = messageUpsertList[0].type;
524
+ map['messages.upsert'] = {
525
+ messages: messageUpsertList.map(m => m.message),
526
+ type
527
+ };
528
+ }
529
+ const messageUpdateList = Object.values(data.messageUpdates);
530
+ if (messageUpdateList.length) {
531
+ map['messages.update'] = messageUpdateList;
532
+ }
533
+ const messageDeleteList = Object.values(data.messageDeletes);
534
+ if (messageDeleteList.length) {
535
+ map['messages.delete'] = { keys: messageDeleteList };
536
+ }
537
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
538
+ if (messageReactionList.length) {
539
+ map['messages.reaction'] = messageReactionList;
540
+ }
541
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
542
+ if (messageReceiptList.length) {
543
+ map['message-receipt.update'] = messageReceiptList;
544
+ }
545
+ const contactUpsertList = Object.values(data.contactUpserts);
546
+ if (contactUpsertList.length) {
547
+ map['contacts.upsert'] = contactUpsertList;
548
+ }
549
+ const contactUpdateList = Object.values(data.contactUpdates);
550
+ if (contactUpdateList.length) {
551
+ map['contacts.update'] = contactUpdateList;
552
+ }
553
+ const groupUpdateList = Object.values(data.groupUpdates);
554
+ if (groupUpdateList.length) {
555
+ map['groups.update'] = groupUpdateList;
556
+ }
557
+ return map;
558
+ }
559
+ function concatChats(a, b) {
560
+ if (b.unreadCount === null && // 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 = { ...b };
567
+ if (b.unreadCount >= 0) {
568
+ b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
569
+ }
570
+ }
571
+ return Object.assign(a, b);
572
+ }
573
+ const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
@@ -0,0 +1,91 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { BaileysEventEmitter, BaileysEventMap, ConnectionState, WACallUpdateType, WAMessageKey, WAVersion } from '../Types/index.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ export declare const BufferJSON: {
5
+ replacer: (k: any, value: any) => any;
6
+ reviver: (_: any, value: any) => any;
7
+ };
8
+ export declare const getKeyAuthor: (key: WAMessageKey | undefined | null, meId?: string) => string;
9
+ export declare const isStringNullOrEmpty: (value: string | null | undefined) => value is null | undefined | "";
10
+ export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer;
11
+ export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array<ArrayBuffer>;
12
+ export declare const generateParticipantHashV2: (participants: string[]) => string;
13
+ export declare const encodeWAMessage: (message: proto.IMessage) => Buffer;
14
+ export declare const generateRegistrationId: () => number;
15
+ export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array<ArrayBuffer>;
16
+ export declare const toNumber: (t: Long | number | null | undefined) => number;
17
+ /** unix timestamp of a date in seconds */
18
+ export declare const unixTimestampSeconds: (date?: Date) => number;
19
+ export type DebouncedTimeout = ReturnType<typeof debouncedTimeout>;
20
+ export declare const debouncedTimeout: (intervalMs?: number, task?: () => void) => {
21
+ start: (newIntervalMs?: number, newTask?: () => void) => void;
22
+ cancel: () => void;
23
+ setTask: (newTask: () => void) => () => void;
24
+ setInterval: (newInterval: number) => number;
25
+ };
26
+ export declare const delay: (ms: number) => Promise<void>;
27
+ export declare const delayCancellable: (ms: number) => {
28
+ delay: Promise<void>;
29
+ cancel: () => void;
30
+ };
31
+ export declare function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error: any) => void) => void): Promise<T>;
32
+ export declare const generateMessageIDV2: (userId?: string) => string;
33
+ export declare const generateMessageID: () => string;
34
+ export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
35
+ export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
36
+ /**
37
+ * utility that fetches latest baileys version from the master branch.
38
+ * Use to ensure your WA connection is always on the latest version
39
+ */
40
+ export declare const fetchLatestBaileysVersion: (options?: RequestInit) => Promise<{
41
+ version: WAVersion;
42
+ isLatest: boolean;
43
+ error?: undefined;
44
+ } | {
45
+ version: WAVersion;
46
+ isLatest: boolean;
47
+ error: unknown;
48
+ }>;
49
+ /**
50
+ * A utility that fetches the latest web version of whatsapp.
51
+ * Use to ensure your WA connection is always on the latest version
52
+ */
53
+ export declare const fetchLatestWaWebVersion: (options?: RequestInit) => Promise<{
54
+ version: WAVersion;
55
+ isLatest: boolean;
56
+ error?: undefined;
57
+ } | {
58
+ version: WAVersion;
59
+ isLatest: boolean;
60
+ error: unknown;
61
+ }>;
62
+ /** unique message tag prefix for MD clients */
63
+ export declare const generateMdTagPrefix: () => string;
64
+ /**
65
+ * Given a type of receipt, returns what the new status of the message should be
66
+ * @param type type from receipt
67
+ */
68
+ export declare const getStatusFromReceiptType: (type: string | undefined) => proto.WebMessageInfo.Status | undefined;
69
+ /**
70
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
71
+ * @param reason the string reason given, eg. "conflict"
72
+ */
73
+ export declare const getErrorCodeFromStreamError: (node: BinaryNode) => {
74
+ reason: string;
75
+ statusCode: number;
76
+ };
77
+ export declare const getCallStatusFromNode: ({ tag, attrs }: BinaryNode) => WACallUpdateType;
78
+ export declare const getCodeFromWSError: (error: Error) => number;
79
+ /**
80
+ * Is the given platform WA business
81
+ * @param platform AuthenticationCreds.platform
82
+ */
83
+ export declare const isWABusinessPlatform: (platform: string) => platform is "smba" | "smbi";
84
+ export declare function trimUndefined(obj: {
85
+ [_: string]: any;
86
+ }): {
87
+ [_: string]: any;
88
+ };
89
+ export declare function bytesToCrockford(buffer: Buffer): string;
90
+ export declare function encodeNewsletterMessage(message: proto.IMessage): Uint8Array;
91
+ //# sourceMappingURL=generics.d.ts.map