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