@nerxa/socketon 0.0.0-stage → 1.21.1

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 (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +125 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +77 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,624 @@
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
+ export const DEFAULT_MAX_EVENT_LISTENERS = 64;
23
+
24
+ export const makeEventBuffer = (logger, maxListeners = DEFAULT_MAX_EVENT_LISTENERS) => {
25
+ const ev = new EventEmitter();
26
+ ev.setMaxListeners(Number.isFinite(maxListeners) && maxListeners >= 0 ? maxListeners : DEFAULT_MAX_EVENT_LISTENERS);
27
+ const historyCache = new Set();
28
+ let data = makeBufferData();
29
+ let isBuffering = false;
30
+ let bufferTimeout = null;
31
+ let flushPendingTimeout = null;
32
+ let bufferCount = 0;
33
+ const MAX_HISTORY_CACHE_SIZE = 10000;
34
+ const BUFFER_TIMEOUT_MS = 30000;
35
+
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
+
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
+
67
+ if (bufferTimeout) {
68
+ clearTimeout(bufferTimeout);
69
+ bufferTimeout = null;
70
+ }
71
+ if (flushPendingTimeout) {
72
+ clearTimeout(flushPendingTimeout);
73
+ flushPendingTimeout = null;
74
+ }
75
+
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
+
110
+ if (event === 'messages.upsert') {
111
+ const { type } = evData;
112
+ const existingUpserts = Object.values(data.messageUpserts);
113
+ if (existingUpserts.length > 0) {
114
+ const bufferedType = existingUpserts[0].type;
115
+ if (bufferedType !== type) {
116
+ logger.debug({ bufferedType, newType: type }, 'messages.upsert type mismatch, emitting buffered messages');
117
+
118
+ ev.emit('event', {
119
+ 'messages.upsert': {
120
+ messages: existingUpserts.map(m => m.message),
121
+ type: bufferedType
122
+ }
123
+ });
124
+
125
+ data.messageUpserts = {};
126
+ }
127
+ }
128
+ }
129
+ if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) {
130
+ append(data, historyCache, event, evData, logger);
131
+ return true;
132
+ }
133
+ return ev.emit('event', { [event]: evData });
134
+ },
135
+ isBuffering() {
136
+ return isBuffering;
137
+ },
138
+ buffer,
139
+ flush,
140
+ createBufferedFunction(work) {
141
+ return async (...args) => {
142
+ buffer();
143
+ try {
144
+ const result = await work(...args);
145
+
146
+ if (bufferCount === 1) {
147
+ setTimeout(() => {
148
+ if (isBuffering && bufferCount === 1) {
149
+ flush();
150
+ }
151
+ }, 100);
152
+ }
153
+ return result;
154
+ }
155
+ catch (error) {
156
+ throw error;
157
+ }
158
+ finally {
159
+ bufferCount = Math.max(0, bufferCount - 1);
160
+ if (bufferCount === 0) {
161
+
162
+ if (!flushPendingTimeout) {
163
+ flushPendingTimeout = setTimeout(flush, 100);
164
+ }
165
+ }
166
+ }
167
+ };
168
+ },
169
+ on: (...args) => ev.on(...args),
170
+ off: (...args) => ev.off(...args),
171
+ once: (...args) => ev.once(...args),
172
+ addListener: (...args) => ev.addListener(...args),
173
+ removeListener: (...args) => ev.removeListener(...args),
174
+ removeAllListeners: (...args) => ev.removeAllListeners(...args),
175
+ setMaxListeners: (count) => ev.setMaxListeners(count),
176
+ getMaxListeners: () => ev.getMaxListeners(),
177
+ listenerCount: (...args) => ev.listenerCount(...args),
178
+ listeners: (...args) => ev.listeners(...args),
179
+ rawListeners: (...args) => ev.rawListeners(...args),
180
+ eventNames: () => ev.eventNames(),
181
+ destroy() {
182
+
183
+ if (bufferTimeout) {
184
+ clearTimeout(bufferTimeout);
185
+ bufferTimeout = null;
186
+ }
187
+ if (flushPendingTimeout) {
188
+ clearTimeout(flushPendingTimeout);
189
+ flushPendingTimeout = null;
190
+ }
191
+
192
+ historyCache.clear();
193
+
194
+ data = makeBufferData();
195
+ isBuffering = false;
196
+ bufferCount = 0;
197
+
198
+ ev.removeAllListeners();
199
+ logger.debug('Event buffer destroyed');
200
+ }
201
+ };
202
+ };
203
+ const makeBufferData = () => {
204
+ return {
205
+ historySets: {
206
+ chats: {},
207
+ messages: {},
208
+ contacts: {},
209
+ isLatest: false,
210
+ empty: true
211
+ },
212
+ chatUpserts: {},
213
+ chatUpdates: {},
214
+ chatDeletes: new Set(),
215
+ contactUpserts: {},
216
+ contactUpdates: {},
217
+ messageUpserts: {},
218
+ messageUpdates: {},
219
+ messageReactions: {},
220
+ messageDeletes: {},
221
+ messageReceipts: {},
222
+ groupUpdates: {}
223
+ };
224
+ };
225
+ function append(data, historyCache, event,
226
+
227
+ eventData, logger) {
228
+ switch (event) {
229
+ case 'messaging-history.set':
230
+ for (const chat of eventData.chats) {
231
+ const id = chat.id || '';
232
+ const existingChat = data.historySets.chats[id];
233
+ if (existingChat) {
234
+ existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
235
+ }
236
+ if (!existingChat && !historyCache.has(id)) {
237
+ data.historySets.chats[id] = chat;
238
+ historyCache.add(id);
239
+ absorbingChatUpdate(chat);
240
+ }
241
+ }
242
+ for (const contact of eventData.contacts) {
243
+ const existingContact = data.historySets.contacts[contact.id];
244
+ if (existingContact) {
245
+ Object.assign(existingContact, trimUndefined(contact));
246
+ }
247
+ else {
248
+ const historyContactId = `c:${contact.id}`;
249
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName;
250
+ if (!historyCache.has(historyContactId) || hasAnyName) {
251
+ data.historySets.contacts[contact.id] = contact;
252
+ historyCache.add(historyContactId);
253
+ }
254
+ }
255
+ }
256
+ for (const message of eventData.messages) {
257
+ const key = stringifyMessageKey(message.key);
258
+ const existingMsg = data.historySets.messages[key];
259
+ if (!existingMsg && !historyCache.has(key)) {
260
+ data.historySets.messages[key] = message;
261
+ historyCache.add(key);
262
+ }
263
+ }
264
+ data.historySets.empty = false;
265
+ data.historySets.syncType = eventData.syncType;
266
+ if (eventData.pastParticipants?.length) {
267
+ const merged = new Map();
268
+ const sigOf = (p) => `${p.userJid || ''}:${p.leaveTs || ''}:${p.leaveReason || ''}`;
269
+ const ingest = (entry) => {
270
+ const key = entry.groupJid ?? JSON.stringify(entry);
271
+ const existing = merged.get(key);
272
+ if (!existing) {
273
+ merged.set(key, { ...entry, pastParticipants: [...(entry.pastParticipants || [])] });
274
+ return;
275
+ }
276
+ const seen = new Set((existing.pastParticipants || []).map(sigOf));
277
+ for (const p of entry.pastParticipants || []) {
278
+ const sig = sigOf(p);
279
+ if (!seen.has(sig)) {
280
+ existing.pastParticipants.push(p);
281
+ seen.add(sig);
282
+ }
283
+ }
284
+ };
285
+ for (const entry of data.historySets.pastParticipants || [])
286
+ ingest(entry);
287
+ for (const entry of eventData.pastParticipants)
288
+ ingest(entry);
289
+ data.historySets.pastParticipants = [...merged.values()];
290
+ }
291
+ data.historySets.progress = eventData.progress;
292
+ data.historySets.chunkOrder = eventData.chunkOrder;
293
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
294
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
295
+ break;
296
+ case 'chats.upsert':
297
+ for (const chat of eventData) {
298
+ const id = chat.id || '';
299
+ let upsert = data.chatUpserts[id];
300
+ if (id && !upsert) {
301
+ upsert = data.historySets.chats[id];
302
+ if (upsert) {
303
+ logger.debug({ chatId: id }, 'absorbed chat upsert in chat set');
304
+ }
305
+ }
306
+ if (upsert) {
307
+ upsert = concatChats(upsert, chat);
308
+ }
309
+ else {
310
+ upsert = chat;
311
+ data.chatUpserts[id] = upsert;
312
+ }
313
+ absorbingChatUpdate(upsert);
314
+ if (data.chatDeletes.has(id)) {
315
+ data.chatDeletes.delete(id);
316
+ }
317
+ }
318
+ break;
319
+ case 'chats.update':
320
+ for (const update of eventData) {
321
+ const chatId = update.id;
322
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
323
+ if (conditionMatches) {
324
+ delete update.conditional;
325
+
326
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
327
+ if (upsert) {
328
+ concatChats(upsert, update);
329
+ }
330
+ else {
331
+
332
+ const chatUpdate = data.chatUpdates[chatId] || {};
333
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update);
334
+ }
335
+ }
336
+ else if (conditionMatches === undefined) {
337
+
338
+ data.chatUpdates[chatId] = update;
339
+ }
340
+
341
+ if (data.chatDeletes.has(chatId)) {
342
+ data.chatDeletes.delete(chatId);
343
+ }
344
+ }
345
+ break;
346
+ case 'chats.delete':
347
+ for (const chatId of eventData) {
348
+ if (!data.chatDeletes.has(chatId)) {
349
+ data.chatDeletes.add(chatId);
350
+ }
351
+
352
+ if (data.chatUpdates[chatId]) {
353
+ delete data.chatUpdates[chatId];
354
+ }
355
+ if (data.chatUpserts[chatId]) {
356
+ delete data.chatUpserts[chatId];
357
+ }
358
+ if (data.historySets.chats[chatId]) {
359
+ delete data.historySets.chats[chatId];
360
+ }
361
+ }
362
+ break;
363
+ case 'contacts.upsert':
364
+ for (const contact of eventData) {
365
+ let upsert = data.contactUpserts[contact.id];
366
+ if (!upsert) {
367
+ upsert = data.historySets.contacts[contact.id];
368
+ if (upsert) {
369
+ logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set');
370
+ }
371
+ }
372
+ if (upsert) {
373
+ upsert = Object.assign(upsert, trimUndefined(contact));
374
+ }
375
+ else {
376
+ upsert = contact;
377
+ data.contactUpserts[contact.id] = upsert;
378
+ }
379
+ if (data.contactUpdates[contact.id]) {
380
+ upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
381
+ delete data.contactUpdates[contact.id];
382
+ }
383
+ }
384
+ break;
385
+ case 'contacts.update':
386
+ const contactUpdates = eventData;
387
+ for (const update of contactUpdates) {
388
+ const id = update.id;
389
+
390
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
391
+ if (upsert) {
392
+ Object.assign(upsert, update);
393
+ }
394
+ else {
395
+
396
+ const contactUpdate = data.contactUpdates[id] || {};
397
+ data.contactUpdates[id] = Object.assign(contactUpdate, update);
398
+ }
399
+ }
400
+ break;
401
+ case 'messages.upsert':
402
+ const { messages, type } = eventData;
403
+ for (const message of messages) {
404
+ const key = stringifyMessageKey(message.key);
405
+ let existing = data.messageUpserts[key]?.message;
406
+ if (!existing) {
407
+ existing = data.historySets.messages[key];
408
+ if (existing) {
409
+ logger.debug({ messageId: key }, 'absorbed message upsert in message set');
410
+ }
411
+ }
412
+ if (existing) {
413
+ message.messageTimestamp = existing.messageTimestamp;
414
+ }
415
+ if (data.messageUpdates[key]) {
416
+ logger.debug('absorbed prior message update in message upsert');
417
+ Object.assign(message, data.messageUpdates[key].update);
418
+ delete data.messageUpdates[key];
419
+ }
420
+ if (data.historySets.messages[key]) {
421
+ data.historySets.messages[key] = message;
422
+ }
423
+ else {
424
+ data.messageUpserts[key] = {
425
+ message,
426
+ type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
427
+ };
428
+ }
429
+ }
430
+ break;
431
+ case 'messages.update':
432
+ const msgUpdates = eventData;
433
+ for (const { key, update } of msgUpdates) {
434
+ const keyStr = stringifyMessageKey(key);
435
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
436
+ if (existing) {
437
+ Object.assign(existing, update);
438
+
439
+ if (update.status === WAMessageStatus.READ && !key.fromMe) {
440
+ decrementChatReadCounterIfMsgDidUnread(existing);
441
+ }
442
+ }
443
+ else {
444
+ const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} };
445
+ Object.assign(msgUpdate.update, update);
446
+ data.messageUpdates[keyStr] = msgUpdate;
447
+ }
448
+ }
449
+ break;
450
+ case 'messages.delete':
451
+ const deleteData = eventData;
452
+ if ('keys' in deleteData) {
453
+ const { keys } = deleteData;
454
+ for (const key of keys) {
455
+ const keyStr = stringifyMessageKey(key);
456
+ if (!data.messageDeletes[keyStr]) {
457
+ data.messageDeletes[keyStr] = key;
458
+ }
459
+ if (data.messageUpserts[keyStr]) {
460
+ delete data.messageUpserts[keyStr];
461
+ }
462
+ if (data.messageUpdates[keyStr]) {
463
+ delete data.messageUpdates[keyStr];
464
+ }
465
+ }
466
+ }
467
+ else {
468
+
469
+ }
470
+ break;
471
+ case 'messages.reaction':
472
+ const reactions = eventData;
473
+ for (const { key, reaction } of reactions) {
474
+ const keyStr = stringifyMessageKey(key);
475
+ const existing = data.messageUpserts[keyStr];
476
+ if (existing) {
477
+ updateMessageWithReaction(existing.message, reaction);
478
+ }
479
+ else {
480
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
481
+ updateMessageWithReaction(data.messageReactions[keyStr], reaction);
482
+ }
483
+ }
484
+ break;
485
+ case 'message-receipt.update':
486
+ const receipts = eventData;
487
+ for (const { key, receipt } of receipts) {
488
+ const keyStr = stringifyMessageKey(key);
489
+ const existing = data.messageUpserts[keyStr];
490
+ if (existing) {
491
+ updateMessageWithReceipt(existing.message, receipt);
492
+ }
493
+ else {
494
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
495
+ updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
496
+ }
497
+ }
498
+ break;
499
+ case 'groups.update':
500
+ const groupUpdates = eventData;
501
+ for (const update of groupUpdates) {
502
+ const id = update.id;
503
+ const groupUpdate = data.groupUpdates[id] || {};
504
+ if (!data.groupUpdates[id]) {
505
+ data.groupUpdates[id] = Object.assign(groupUpdate, update);
506
+ }
507
+ }
508
+ break;
509
+ default:
510
+ throw new Error(`"${event}" cannot be buffered`);
511
+ }
512
+ function absorbingChatUpdate(existing) {
513
+ const chatId = existing.id || '';
514
+ const update = data.chatUpdates[chatId];
515
+ if (update) {
516
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
517
+ if (conditionMatches) {
518
+ delete update.conditional;
519
+ logger.debug({ chatId }, 'absorbed chat update in existing chat');
520
+ Object.assign(existing, concatChats(update, existing));
521
+ delete data.chatUpdates[chatId];
522
+ }
523
+ else if (conditionMatches === false) {
524
+ logger.debug({ chatId }, 'chat update condition fail, removing');
525
+ delete data.chatUpdates[chatId];
526
+ }
527
+ }
528
+ }
529
+ function decrementChatReadCounterIfMsgDidUnread(message) {
530
+
531
+ const chatId = message.key.remoteJid;
532
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
533
+ if (isRealMessage(message) &&
534
+ shouldIncrementChatUnread(message) &&
535
+ typeof chat?.unreadCount === 'number' &&
536
+ chat.unreadCount > 0) {
537
+ logger.debug({ chatId: chat.id }, 'decrementing chat counter');
538
+ chat.unreadCount -= 1;
539
+ if (chat.unreadCount === 0) {
540
+ delete chat.unreadCount;
541
+ }
542
+ }
543
+ }
544
+ }
545
+ function consolidateEvents(data) {
546
+ const map = {};
547
+ if (!data.historySets.empty) {
548
+ map['messaging-history.set'] = {
549
+ chats: Object.values(data.historySets.chats),
550
+ messages: Object.values(data.historySets.messages),
551
+ contacts: Object.values(data.historySets.contacts),
552
+ pastParticipants: data.historySets.pastParticipants,
553
+ syncType: data.historySets.syncType,
554
+ progress: data.historySets.progress,
555
+ isLatest: data.historySets.isLatest,
556
+ chunkOrder: data.historySets.chunkOrder,
557
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
558
+ };
559
+ }
560
+ const chatUpsertList = Object.values(data.chatUpserts);
561
+ if (chatUpsertList.length) {
562
+ map['chats.upsert'] = chatUpsertList;
563
+ }
564
+ const chatUpdateList = Object.values(data.chatUpdates);
565
+ if (chatUpdateList.length) {
566
+ map['chats.update'] = chatUpdateList;
567
+ }
568
+ const chatDeleteList = Array.from(data.chatDeletes);
569
+ if (chatDeleteList.length) {
570
+ map['chats.delete'] = chatDeleteList;
571
+ }
572
+ const messageUpsertList = Object.values(data.messageUpserts);
573
+ if (messageUpsertList.length) {
574
+ const type = messageUpsertList[0].type;
575
+ map['messages.upsert'] = {
576
+ messages: messageUpsertList.map(m => m.message),
577
+ type
578
+ };
579
+ }
580
+ const messageUpdateList = Object.values(data.messageUpdates);
581
+ if (messageUpdateList.length) {
582
+ map['messages.update'] = messageUpdateList;
583
+ }
584
+ const messageDeleteList = Object.values(data.messageDeletes);
585
+ if (messageDeleteList.length) {
586
+ map['messages.delete'] = { keys: messageDeleteList };
587
+ }
588
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
589
+ if (messageReactionList.length) {
590
+ map['messages.reaction'] = messageReactionList;
591
+ }
592
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
593
+ if (messageReceiptList.length) {
594
+ map['message-receipt.update'] = messageReceiptList;
595
+ }
596
+ const contactUpsertList = Object.values(data.contactUpserts);
597
+ if (contactUpsertList.length) {
598
+ map['contacts.upsert'] = contactUpsertList;
599
+ }
600
+ const contactUpdateList = Object.values(data.contactUpdates);
601
+ if (contactUpdateList.length) {
602
+ map['contacts.update'] = contactUpdateList;
603
+ }
604
+ const groupUpdateList = Object.values(data.groupUpdates);
605
+ if (groupUpdateList.length) {
606
+ map['groups.update'] = groupUpdateList;
607
+ }
608
+ return map;
609
+ }
610
+ function concatChats(a, b) {
611
+ if (b.unreadCount === null &&
612
+ a.unreadCount < 0) {
613
+ a.unreadCount = undefined;
614
+ b.unreadCount = undefined;
615
+ }
616
+ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
617
+ b = { ...b };
618
+ if (b.unreadCount >= 0) {
619
+ b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
620
+ }
621
+ }
622
+ return Object.assign(a, b);
623
+ }
624
+ const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
@@ -0,0 +1,63 @@
1
+ export function promiseTimeout(ms: any, promise: any): Promise<any>;
2
+ export function bindWaitForEvent(ev: any, event: any): (check: any, timeoutMs: any) => Promise<void>;
3
+ export function trimUndefined(obj: any): any;
4
+ export function bytesToCrockford(buffer: any): string;
5
+ export function encodeNewsletterMessage(message: any): any;
6
+ export namespace BufferJSON {
7
+ function replacer(k: any, value: any): any;
8
+ function reviver(_: any, value: any): any;
9
+ }
10
+ export function getKeyAuthor(key: any, meId?: string): any;
11
+ export function isStringNullOrEmpty(value: any): boolean;
12
+ export function writeRandomPadMax16(msg: any): any;
13
+ export function unpadRandomMax16(e: any): Uint8Array<any>;
14
+ export function generateParticipantHashV2(participants: any): string;
15
+ export function encodeWAMessage(message: any): any;
16
+ export function generateRegistrationId(): number;
17
+ export function encodeBigEndian(e: any, t?: number): Uint8Array<ArrayBuffer>;
18
+ export function toNumber(t: any): any;
19
+ export function unixTimestampSeconds(date?: Date): number;
20
+ export function debouncedTimeout(intervalMs: number | undefined, task: any): {
21
+ start: (newIntervalMs: any, newTask: any) => void;
22
+ cancel: () => void;
23
+ setTask: (newTask: any) => any;
24
+ setInterval: (newInterval: any) => any;
25
+ };
26
+ export function delay(ms: any): Promise<any>;
27
+ export function delayCancellable(ms: any): {
28
+ delay: Promise<any>;
29
+ cancel: () => void;
30
+ };
31
+ export function generateMessageIDV2(userId: any): string;
32
+ export function generateMessageID(): string;
33
+ export function bindWaitForConnectionUpdate(ev: any): (check: any, timeoutMs: any) => Promise<void>;
34
+ export function fetchLatestBaileysVersion(options?: {}): Promise<{
35
+ version: number[];
36
+ isLatest: boolean;
37
+ error?: undefined;
38
+ } | {
39
+ version: number[];
40
+ isLatest: boolean;
41
+ error: unknown;
42
+ }>;
43
+ export function fetchLatestWaWebVersion(options?: {}): Promise<{
44
+ version: number[];
45
+ isLatest: boolean;
46
+ error?: undefined;
47
+ } | {
48
+ version: number[];
49
+ isLatest: boolean;
50
+ error: unknown;
51
+ }>;
52
+ export function generateMdTagPrefix(): string;
53
+ export function getStatusFromReceiptType(type: any): any;
54
+ export function getErrorCodeFromStreamError(node: any): {
55
+ reason: any;
56
+ statusCode: number;
57
+ };
58
+ export function getCallStatusFromNode({ tag, attrs }: {
59
+ tag: any;
60
+ attrs: any;
61
+ }): string;
62
+ export function getCodeFromWSError(error: any): number;
63
+ export function isWABusinessPlatform(platform: any): boolean;