@baileysmod-ubed/baileys 0.3.17

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 (430) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +79 -0
  3. package/WAProto/index.d.ts +15871 -0
  4. package/WAProto/index.js +115447 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.d.ts +145 -0
  7. package/lib/Defaults/index.d.ts.map +1 -0
  8. package/lib/Defaults/index.js +152 -0
  9. package/lib/Defaults/index.js.map +1 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.js +30 -0
  17. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  18. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  19. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  20. package/lib/Signal/Group/group_cipher.js +82 -0
  21. package/lib/Signal/Group/group_cipher.js.map +1 -0
  22. package/lib/Signal/Group/index.d.ts +12 -0
  23. package/lib/Signal/Group/index.d.ts.map +1 -0
  24. package/lib/Signal/Group/index.js +12 -0
  25. package/lib/Signal/Group/index.js.map +1 -0
  26. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  27. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  28. package/lib/Signal/Group/keyhelper.js +18 -0
  29. package/lib/Signal/Group/keyhelper.js.map +1 -0
  30. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.js +26 -0
  33. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  34. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  38. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.js +66 -0
  41. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  42. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.js +48 -0
  45. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  46. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.js +41 -0
  49. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  50. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.js +84 -0
  53. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  54. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.js +26 -0
  57. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  58. package/lib/Signal/libsignal.d.ts +55 -0
  59. package/lib/Signal/libsignal.d.ts.map +1 -0
  60. package/lib/Signal/libsignal.js +431 -0
  61. package/lib/Signal/libsignal.js.map +1 -0
  62. package/lib/Signal/lid-mapping.d.ts +21 -0
  63. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  64. package/lib/Signal/lid-mapping.js +277 -0
  65. package/lib/Signal/lid-mapping.js.map +1 -0
  66. package/lib/Socket/Client/index.d.ts +3 -0
  67. package/lib/Socket/Client/index.d.ts.map +1 -0
  68. package/lib/Socket/Client/index.js +3 -0
  69. package/lib/Socket/Client/index.js.map +1 -0
  70. package/lib/Socket/Client/types.d.ts +6 -0
  71. package/lib/Socket/Client/types.d.ts.map +1 -0
  72. package/lib/Socket/Client/types.js +11 -0
  73. package/lib/Socket/Client/types.js.map +1 -0
  74. package/lib/Socket/Client/websocket.d.ts +13 -0
  75. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  76. package/lib/Socket/Client/websocket.js +54 -0
  77. package/lib/Socket/Client/websocket.js.map +1 -0
  78. package/lib/Socket/business.d.ts +395 -0
  79. package/lib/Socket/business.d.ts.map +1 -0
  80. package/lib/Socket/business.js +380 -0
  81. package/lib/Socket/business.js.map +1 -0
  82. package/lib/Socket/chats.d.ts +137 -0
  83. package/lib/Socket/chats.d.ts.map +1 -0
  84. package/lib/Socket/chats.js +1214 -0
  85. package/lib/Socket/chats.js.map +1 -0
  86. package/lib/Socket/communities.d.ts +562 -0
  87. package/lib/Socket/communities.d.ts.map +1 -0
  88. package/lib/Socket/communities.js +432 -0
  89. package/lib/Socket/communities.js.map +1 -0
  90. package/lib/Socket/groups.d.ts +286 -0
  91. package/lib/Socket/groups.d.ts.map +1 -0
  92. package/lib/Socket/groups.js +348 -0
  93. package/lib/Socket/groups.js.map +1 -0
  94. package/lib/Socket/index.d.ts +530 -0
  95. package/lib/Socket/index.d.ts.map +1 -0
  96. package/lib/Socket/index.js +12 -0
  97. package/lib/Socket/index.js.map +1 -0
  98. package/lib/Socket/messages-recv.d.ts +334 -0
  99. package/lib/Socket/messages-recv.d.ts.map +1 -0
  100. package/lib/Socket/messages-recv.js +1772 -0
  101. package/lib/Socket/messages-recv.js.map +1 -0
  102. package/lib/Socket/messages-send.d.ts +330 -0
  103. package/lib/Socket/messages-send.d.ts.map +1 -0
  104. package/lib/Socket/messages-send.js +1368 -0
  105. package/lib/Socket/messages-send.js.map +1 -0
  106. package/lib/Socket/mex.d.ts +2 -0
  107. package/lib/Socket/mex.d.ts.map +1 -0
  108. package/lib/Socket/mex.js +42 -0
  109. package/lib/Socket/mex.js.map +1 -0
  110. package/lib/Socket/newsletter.d.ts +283 -0
  111. package/lib/Socket/newsletter.d.ts.map +1 -0
  112. package/lib/Socket/newsletter.js +226 -0
  113. package/lib/Socket/newsletter.js.map +1 -0
  114. package/lib/Socket/socket.d.ts +61 -0
  115. package/lib/Socket/socket.d.ts.map +1 -0
  116. package/lib/Socket/socket.js +967 -0
  117. package/lib/Socket/socket.js.map +1 -0
  118. package/lib/Store/index.d.ts +4 -0
  119. package/lib/Store/index.d.ts.map +1 -0
  120. package/lib/Store/index.js +4 -0
  121. package/lib/Store/index.js.map +1 -0
  122. package/lib/Store/make-in-memory-store.d.ts +63 -0
  123. package/lib/Store/make-in-memory-store.d.ts.map +1 -0
  124. package/lib/Store/make-in-memory-store.js +421 -0
  125. package/lib/Store/make-in-memory-store.js.map +1 -0
  126. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  127. package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
  128. package/lib/Store/make-ordered-dictionary.js +79 -0
  129. package/lib/Store/make-ordered-dictionary.js.map +1 -0
  130. package/lib/Store/object-repository.d.ts +11 -0
  131. package/lib/Store/object-repository.d.ts.map +1 -0
  132. package/lib/Store/object-repository.js +24 -0
  133. package/lib/Store/object-repository.js.map +1 -0
  134. package/lib/Types/Auth.d.ts +2 -0
  135. package/lib/Types/Auth.d.ts.map +1 -0
  136. package/lib/Types/Auth.js +2 -0
  137. package/lib/Types/Auth.js.map +1 -0
  138. package/lib/Types/Bussines.d.ts +2 -0
  139. package/lib/Types/Bussines.d.ts.map +1 -0
  140. package/lib/Types/Bussines.js +2 -0
  141. package/lib/Types/Bussines.js.map +1 -0
  142. package/lib/Types/Call.d.ts +2 -0
  143. package/lib/Types/Call.d.ts.map +1 -0
  144. package/lib/Types/Call.js +2 -0
  145. package/lib/Types/Call.js.map +1 -0
  146. package/lib/Types/Chat.d.ts +2 -0
  147. package/lib/Types/Chat.d.ts.map +1 -0
  148. package/lib/Types/Chat.js +8 -0
  149. package/lib/Types/Chat.js.map +1 -0
  150. package/lib/Types/Contact.d.ts +2 -0
  151. package/lib/Types/Contact.d.ts.map +1 -0
  152. package/lib/Types/Contact.js +2 -0
  153. package/lib/Types/Contact.js.map +1 -0
  154. package/lib/Types/Events.d.ts +2 -0
  155. package/lib/Types/Events.d.ts.map +1 -0
  156. package/lib/Types/Events.js +2 -0
  157. package/lib/Types/Events.js.map +1 -0
  158. package/lib/Types/GroupMetadata.d.ts +2 -0
  159. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  160. package/lib/Types/GroupMetadata.js +2 -0
  161. package/lib/Types/GroupMetadata.js.map +1 -0
  162. package/lib/Types/Label.d.ts +3 -0
  163. package/lib/Types/Label.d.ts.map +1 -0
  164. package/lib/Types/Label.js +25 -0
  165. package/lib/Types/Label.js.map +1 -0
  166. package/lib/Types/LabelAssociation.d.ts +3 -0
  167. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  168. package/lib/Types/LabelAssociation.js +7 -0
  169. package/lib/Types/LabelAssociation.js.map +1 -0
  170. package/lib/Types/Message.d.ts +12 -0
  171. package/lib/Types/Message.d.ts.map +1 -0
  172. package/lib/Types/Message.js +18 -0
  173. package/lib/Types/Message.js.map +1 -0
  174. package/lib/Types/Mex.d.ts +3 -0
  175. package/lib/Types/Mex.d.ts.map +1 -0
  176. package/lib/Types/Mex.js +39 -0
  177. package/lib/Types/Mex.js.map +1 -0
  178. package/lib/Types/Product.d.ts +2 -0
  179. package/lib/Types/Product.d.ts.map +1 -0
  180. package/lib/Types/Product.js +2 -0
  181. package/lib/Types/Product.js.map +1 -0
  182. package/lib/Types/RichType.d.ts +3 -0
  183. package/lib/Types/RichType.d.ts.map +1 -0
  184. package/lib/Types/RichType.js +23 -0
  185. package/lib/Types/RichType.js.map +1 -0
  186. package/lib/Types/Signal.d.ts +2 -0
  187. package/lib/Types/Signal.d.ts.map +1 -0
  188. package/lib/Types/Signal.js +2 -0
  189. package/lib/Types/Signal.js.map +1 -0
  190. package/lib/Types/Socket.d.ts +2 -0
  191. package/lib/Types/Socket.d.ts.map +1 -0
  192. package/lib/Types/Socket.js +2 -0
  193. package/lib/Types/Socket.js.map +1 -0
  194. package/lib/Types/State.d.ts +6 -0
  195. package/lib/Types/State.d.ts.map +1 -0
  196. package/lib/Types/State.js +56 -0
  197. package/lib/Types/State.js.map +1 -0
  198. package/lib/Types/USync.d.ts +2 -0
  199. package/lib/Types/USync.d.ts.map +1 -0
  200. package/lib/Types/USync.js +2 -0
  201. package/lib/Types/USync.js.map +1 -0
  202. package/lib/Types/index.d.ts +14 -0
  203. package/lib/Types/index.d.ts.map +1 -0
  204. package/lib/Types/index.js +26 -0
  205. package/lib/Types/index.js.map +1 -0
  206. package/lib/Utils/auth-utils.d.ts +58 -0
  207. package/lib/Utils/auth-utils.d.ts.map +1 -0
  208. package/lib/Utils/auth-utils.js +302 -0
  209. package/lib/Utils/auth-utils.js.map +1 -0
  210. package/lib/Utils/browser-utils.d.ts +9 -0
  211. package/lib/Utils/browser-utils.d.ts.map +1 -0
  212. package/lib/Utils/browser-utils.js +28 -0
  213. package/lib/Utils/browser-utils.js.map +1 -0
  214. package/lib/Utils/business.d.ts +50 -0
  215. package/lib/Utils/business.d.ts.map +1 -0
  216. package/lib/Utils/business.js +231 -0
  217. package/lib/Utils/business.js.map +1 -0
  218. package/lib/Utils/chat-utils.d.ts +409 -0
  219. package/lib/Utils/chat-utils.d.ts.map +1 -0
  220. package/lib/Utils/chat-utils.js +872 -0
  221. package/lib/Utils/chat-utils.js.map +1 -0
  222. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  223. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  224. package/lib/Utils/companion-reg-client-utils.js +40 -0
  225. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  226. package/lib/Utils/crypto.d.ts +40 -0
  227. package/lib/Utils/crypto.d.ts.map +1 -0
  228. package/lib/Utils/crypto.js +118 -0
  229. package/lib/Utils/crypto.js.map +1 -0
  230. package/lib/Utils/decode-wa-message.d.ts +84 -0
  231. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  232. package/lib/Utils/decode-wa-message.js +317 -0
  233. package/lib/Utils/decode-wa-message.js.map +1 -0
  234. package/lib/Utils/event-buffer.d.ts +13 -0
  235. package/lib/Utils/event-buffer.d.ts.map +1 -0
  236. package/lib/Utils/event-buffer.js +622 -0
  237. package/lib/Utils/event-buffer.js.map +1 -0
  238. package/lib/Utils/generics.d.ts +64 -0
  239. package/lib/Utils/generics.d.ts.map +1 -0
  240. package/lib/Utils/generics.js +395 -0
  241. package/lib/Utils/generics.js.map +1 -0
  242. package/lib/Utils/history.d.ts +76 -0
  243. package/lib/Utils/history.d.ts.map +1 -0
  244. package/lib/Utils/history.js +134 -0
  245. package/lib/Utils/history.js.map +1 -0
  246. package/lib/Utils/identity-change-handler.d.ts +14 -0
  247. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  248. package/lib/Utils/identity-change-handler.js +50 -0
  249. package/lib/Utils/identity-change-handler.js.map +1 -0
  250. package/lib/Utils/index.d.ts +25 -0
  251. package/lib/Utils/index.d.ts.map +1 -0
  252. package/lib/Utils/index.js +25 -0
  253. package/lib/Utils/index.js.map +1 -0
  254. package/lib/Utils/link-preview.d.ts +13 -0
  255. package/lib/Utils/link-preview.d.ts.map +1 -0
  256. package/lib/Utils/link-preview.js +85 -0
  257. package/lib/Utils/link-preview.js.map +1 -0
  258. package/lib/Utils/logger.d.ts +3 -0
  259. package/lib/Utils/logger.d.ts.map +1 -0
  260. package/lib/Utils/logger.js +3 -0
  261. package/lib/Utils/logger.js.map +1 -0
  262. package/lib/Utils/lt-hash.d.ts +7 -0
  263. package/lib/Utils/lt-hash.d.ts.map +1 -0
  264. package/lib/Utils/lt-hash.js +8 -0
  265. package/lib/Utils/lt-hash.js.map +1 -0
  266. package/lib/Utils/make-mutex.d.ts +7 -0
  267. package/lib/Utils/make-mutex.d.ts.map +1 -0
  268. package/lib/Utils/make-mutex.js +33 -0
  269. package/lib/Utils/make-mutex.js.map +1 -0
  270. package/lib/Utils/message-retry-manager.d.ts +80 -0
  271. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  272. package/lib/Utils/message-retry-manager.js +265 -0
  273. package/lib/Utils/message-retry-manager.js.map +1 -0
  274. package/lib/Utils/messages-media.d.ts +137 -0
  275. package/lib/Utils/messages-media.d.ts.map +1 -0
  276. package/lib/Utils/messages-media.js +843 -0
  277. package/lib/Utils/messages-media.js.map +1 -0
  278. package/lib/Utils/messages.d.ts +46 -0
  279. package/lib/Utils/messages.d.ts.map +1 -0
  280. package/lib/Utils/messages.js +1863 -0
  281. package/lib/Utils/messages.js.map +1 -0
  282. package/lib/Utils/noise-handler.d.ts +21 -0
  283. package/lib/Utils/noise-handler.d.ts.map +1 -0
  284. package/lib/Utils/noise-handler.js +201 -0
  285. package/lib/Utils/noise-handler.js.map +1 -0
  286. package/lib/Utils/offline-node-processor.d.ts +10 -0
  287. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  288. package/lib/Utils/offline-node-processor.js +40 -0
  289. package/lib/Utils/offline-node-processor.js.map +1 -0
  290. package/lib/Utils/pre-key-manager.d.ts +26 -0
  291. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  292. package/lib/Utils/pre-key-manager.js +106 -0
  293. package/lib/Utils/pre-key-manager.js.map +1 -0
  294. package/lib/Utils/process-message.d.ts +84 -0
  295. package/lib/Utils/process-message.d.ts.map +1 -0
  296. package/lib/Utils/process-message.js +749 -0
  297. package/lib/Utils/process-message.js.map +1 -0
  298. package/lib/Utils/reporting-utils.d.ts +13 -0
  299. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  300. package/lib/Utils/reporting-utils.js +258 -0
  301. package/lib/Utils/reporting-utils.js.map +1 -0
  302. package/lib/Utils/rich-message-utils.d.ts +49 -0
  303. package/lib/Utils/rich-message-utils.d.ts.map +1 -0
  304. package/lib/Utils/rich-message-utils.js +370 -0
  305. package/lib/Utils/rich-message-utils.js.map +1 -0
  306. package/lib/Utils/signal.d.ts +83 -0
  307. package/lib/Utils/signal.d.ts.map +1 -0
  308. package/lib/Utils/signal.js +201 -0
  309. package/lib/Utils/signal.js.map +1 -0
  310. package/lib/Utils/stanza-ack.d.ts +17 -0
  311. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  312. package/lib/Utils/stanza-ack.js +38 -0
  313. package/lib/Utils/stanza-ack.js.map +1 -0
  314. package/lib/Utils/sync-action-utils.d.ts +3 -0
  315. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  316. package/lib/Utils/sync-action-utils.js +49 -0
  317. package/lib/Utils/sync-action-utils.js.map +1 -0
  318. package/lib/Utils/tc-token-utils.d.ts +30 -0
  319. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  320. package/lib/Utils/tc-token-utils.js +163 -0
  321. package/lib/Utils/tc-token-utils.js.map +1 -0
  322. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  323. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  324. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  325. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  326. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  327. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  328. package/lib/Utils/use-single-file-auth-state.js +109 -0
  329. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  330. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  331. package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
  332. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  333. package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
  334. package/lib/Utils/validate-connection.d.ts +44 -0
  335. package/lib/Utils/validate-connection.d.ts.map +1 -0
  336. package/lib/Utils/validate-connection.js +203 -0
  337. package/lib/Utils/validate-connection.js.map +1 -0
  338. package/lib/WABinary/constants.d.ts +62 -0
  339. package/lib/WABinary/constants.d.ts.map +1 -0
  340. package/lib/WABinary/constants.js +1467 -0
  341. package/lib/WABinary/constants.js.map +1 -0
  342. package/lib/WABinary/decode.d.ts +10 -0
  343. package/lib/WABinary/decode.d.ts.map +1 -0
  344. package/lib/WABinary/decode.js +262 -0
  345. package/lib/WABinary/decode.js.map +1 -0
  346. package/lib/WABinary/encode.d.ts +3 -0
  347. package/lib/WABinary/encode.d.ts.map +1 -0
  348. package/lib/WABinary/encode.js +220 -0
  349. package/lib/WABinary/encode.js.map +1 -0
  350. package/lib/WABinary/generic-utils.d.ts +77 -0
  351. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  352. package/lib/WABinary/generic-utils.js +226 -0
  353. package/lib/WABinary/generic-utils.js.map +1 -0
  354. package/lib/WABinary/index.d.ts +6 -0
  355. package/lib/WABinary/index.d.ts.map +1 -0
  356. package/lib/WABinary/index.js +6 -0
  357. package/lib/WABinary/index.js.map +1 -0
  358. package/lib/WABinary/jid-utils.d.ts +29 -0
  359. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  360. package/lib/WABinary/jid-utils.js +96 -0
  361. package/lib/WABinary/jid-utils.js.map +1 -0
  362. package/lib/WABinary/types.d.ts +2 -0
  363. package/lib/WABinary/types.d.ts.map +1 -0
  364. package/lib/WABinary/types.js +2 -0
  365. package/lib/WABinary/types.js.map +1 -0
  366. package/lib/WAM/BinaryInfo.d.ts +8 -0
  367. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  368. package/lib/WAM/BinaryInfo.js +10 -0
  369. package/lib/WAM/BinaryInfo.js.map +1 -0
  370. package/lib/WAM/constants.d.ts +34927 -0
  371. package/lib/WAM/constants.d.ts.map +1 -0
  372. package/lib/WAM/constants.js +22853 -0
  373. package/lib/WAM/constants.js.map +1 -0
  374. package/lib/WAM/encode.d.ts +2 -0
  375. package/lib/WAM/encode.d.ts.map +1 -0
  376. package/lib/WAM/encode.js +150 -0
  377. package/lib/WAM/encode.js.map +1 -0
  378. package/lib/WAM/index.d.ts +4 -0
  379. package/lib/WAM/index.d.ts.map +1 -0
  380. package/lib/WAM/index.js +4 -0
  381. package/lib/WAM/index.js.map +1 -0
  382. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  383. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  384. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  385. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  386. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  387. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  388. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  389. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  390. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  391. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  392. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  393. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  394. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  395. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  396. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  397. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  398. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  399. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  400. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  401. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  402. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  403. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  404. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  405. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  406. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  407. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  408. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  409. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  410. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  411. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  412. package/lib/WAUSync/Protocols/index.js +6 -0
  413. package/lib/WAUSync/Protocols/index.js.map +1 -0
  414. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  415. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  416. package/lib/WAUSync/USyncQuery.js +98 -0
  417. package/lib/WAUSync/USyncQuery.js.map +1 -0
  418. package/lib/WAUSync/USyncUser.d.ts +17 -0
  419. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  420. package/lib/WAUSync/USyncUser.js +31 -0
  421. package/lib/WAUSync/USyncUser.js.map +1 -0
  422. package/lib/WAUSync/index.d.ts +4 -0
  423. package/lib/WAUSync/index.d.ts.map +1 -0
  424. package/lib/WAUSync/index.js +4 -0
  425. package/lib/WAUSync/index.js.map +1 -0
  426. package/lib/index.d.ts +12 -0
  427. package/lib/index.d.ts.map +1 -0
  428. package/lib/index.js +12 -0
  429. package/lib/index.js.map +1 -0
  430. package/package.json +108 -0
@@ -0,0 +1,1368 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { AssociationType } from '../Types/index.js';
8
+ import { getUrlInfo } from '../Utils/link-preview.js';
9
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
10
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
11
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
12
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
13
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
+ import { makeNewsletterSocket } from './newsletter.js';
15
+ export const makeMessagesSocket = (config) => {
16
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
17
+ const sock = makeNewsletterSocket(config);
18
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
19
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
20
+ /**
21
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
22
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
23
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
24
+ */
25
+ const inFlightTcTokenIssuance = new Set();
26
+ const userDevicesCache = config.userDevicesCache ||
27
+ new NodeCache({
28
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
29
+ useClones: false
30
+ });
31
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
32
+ const devicesMutex = makeMutex();
33
+ // Initialize message retry manager if enabled
34
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
35
+ // Prevent race conditions in Signal session encryption by user
36
+ const encryptionMutex = makeKeyedMutex();
37
+ // Prevent race conditions in media connection refresh
38
+ const mediaConnMutex = makeKeyedMutex();
39
+ let mediaConn;
40
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
41
+ let mediaHost = DEF_MEDIA_HOST;
42
+ const refreshMediaConn = async (forceGet = false) => {
43
+ return mediaConnMutex.mutex('media-conn', async () => {
44
+ const media = await mediaConn;
45
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
46
+ mediaConn = (async () => {
47
+ const result = await query({
48
+ tag: 'iq',
49
+ attrs: {
50
+ type: 'set',
51
+ xmlns: 'w:m',
52
+ to: S_WHATSAPP_NET
53
+ },
54
+ content: [{ tag: 'media_conn', attrs: {} }]
55
+ });
56
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
57
+ // TODO: explore full length of data that whatsapp provides
58
+ const node = {
59
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
60
+ hostname: attrs.hostname,
61
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
62
+ })),
63
+ auth: mediaConnNode.attrs.auth,
64
+ ttl: +mediaConnNode.attrs.ttl,
65
+ fetchDate: new Date()
66
+ };
67
+ logger.debug('fetched media conn');
68
+ if (node.hosts[0]) {
69
+ mediaHost = node.hosts[0].hostname;
70
+ }
71
+ return node;
72
+ })();
73
+ }
74
+ return mediaConn;
75
+ });
76
+ };
77
+ /**
78
+ * generic send receipt function
79
+ * used for receipts of phone call, read, delivery etc.
80
+ * */
81
+ const sendReceipt = async (jid, participant, messageIds, type) => {
82
+ if (!messageIds || messageIds.length === 0) {
83
+ throw new Boom('missing ids in receipt');
84
+ }
85
+ const node = {
86
+ tag: 'receipt',
87
+ attrs: {
88
+ id: messageIds[0]
89
+ }
90
+ };
91
+ const isReadReceipt = type === 'read' || type === 'read-self';
92
+ if (isReadReceipt) {
93
+ node.attrs.t = unixTimestampSeconds().toString();
94
+ }
95
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
96
+ node.attrs.recipient = jid;
97
+ node.attrs.to = participant;
98
+ }
99
+ else {
100
+ node.attrs.to = jid;
101
+ if (participant) {
102
+ node.attrs.participant = participant;
103
+ }
104
+ }
105
+ if (type) {
106
+ node.attrs.type = type;
107
+ }
108
+ const remainingMessageIds = messageIds.slice(1);
109
+ if (remainingMessageIds.length) {
110
+ node.content = [
111
+ {
112
+ tag: 'list',
113
+ attrs: {},
114
+ content: remainingMessageIds.map(id => ({
115
+ tag: 'item',
116
+ attrs: { id }
117
+ }))
118
+ }
119
+ ];
120
+ }
121
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
122
+ await sendNode(node);
123
+ };
124
+ /** Correctly bulk send receipts to multiple chats, participants */
125
+ const sendReceipts = async (keys, type) => {
126
+ const recps = aggregateMessageKeysNotFromMe(keys);
127
+ for (const { jid, participant, messageIds } of recps) {
128
+ await sendReceipt(jid, participant, messageIds, type);
129
+ }
130
+ };
131
+ /** Bulk read messages. Keys can be from different chats & participants */
132
+ const readMessages = async (keys) => {
133
+ const privacySettings = await fetchPrivacySettings();
134
+ // based on privacy settings, we have to change the read type
135
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
136
+ await sendReceipts(keys, readType);
137
+ };
138
+ /** Fetch all the devices we've to send a message to */
139
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
140
+ const deviceResults = [];
141
+ if (!useCache) {
142
+ logger.debug('not using cache for devices');
143
+ }
144
+ const toFetch = [];
145
+ const jidsWithUser = jids
146
+ .map(jid => {
147
+ const decoded = jidDecode(jid);
148
+ const user = decoded?.user;
149
+ const device = decoded?.device;
150
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
151
+ if (isExplicitDevice && user) {
152
+ deviceResults.push({
153
+ user,
154
+ device,
155
+ jid
156
+ });
157
+ return null;
158
+ }
159
+ jid = jidNormalizedUser(jid);
160
+ return { jid, user };
161
+ })
162
+ .filter(jid => jid !== null);
163
+ let mgetDevices;
164
+ if (useCache && userDevicesCache.mget) {
165
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
166
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
167
+ }
168
+ for (const { jid, user } of jidsWithUser) {
169
+ if (useCache) {
170
+ const devices = mgetDevices?.[user] ||
171
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
172
+ if (devices) {
173
+ const devicesWithJid = devices.map(d => ({
174
+ ...d,
175
+ jid: jidEncode(d.user, d.server, d.device)
176
+ }));
177
+ deviceResults.push(...devicesWithJid);
178
+ logger.trace({ user }, 'using cache for devices');
179
+ }
180
+ else {
181
+ toFetch.push(jid);
182
+ }
183
+ }
184
+ else {
185
+ toFetch.push(jid);
186
+ }
187
+ }
188
+ if (!toFetch.length) {
189
+ return deviceResults;
190
+ }
191
+ const requestedLidUsers = new Set();
192
+ for (const jid of toFetch) {
193
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
194
+ const user = jidDecode(jid)?.user;
195
+ if (user)
196
+ requestedLidUsers.add(user);
197
+ }
198
+ }
199
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
200
+ for (const jid of toFetch) {
201
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
202
+ }
203
+ const result = await sock.executeUSyncQuery(query);
204
+ if (result) {
205
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
206
+ const lidResults = result.list.filter(a => !!a.lid);
207
+ if (lidResults.length > 0) {
208
+ logger.trace('Storing LID maps from device call');
209
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
210
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
211
+ try {
212
+ const lids = lidResults.map(a => a.lid);
213
+ if (lids.length) {
214
+ await assertSessions(lids, true);
215
+ }
216
+ }
217
+ catch (e) {
218
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
219
+ }
220
+ }
221
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
222
+ const deviceMap = {};
223
+ for (const item of extracted) {
224
+ deviceMap[item.user] = deviceMap[item.user] || [];
225
+ deviceMap[item.user]?.push(item);
226
+ }
227
+ // Process each user's devices as a group for bulk LID migration
228
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
229
+ const isLidUser = requestedLidUsers.has(user);
230
+ // Process all devices for this user
231
+ for (const item of userDevices) {
232
+ const finalJid = isLidUser
233
+ ? jidEncode(user, item.server, item.device)
234
+ : jidEncode(item.user, item.server, item.device);
235
+ deviceResults.push({
236
+ ...item,
237
+ jid: finalJid
238
+ });
239
+ logger.debug({
240
+ user: item.user,
241
+ device: item.device,
242
+ finalJid,
243
+ usedLid: isLidUser
244
+ }, 'Processed device with LID priority');
245
+ }
246
+ }
247
+ await devicesMutex.mutex(async () => {
248
+ if (userDevicesCache.mset) {
249
+ // if the cache supports mset, we can set all devices in one go
250
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
251
+ }
252
+ else {
253
+ for (const key in deviceMap) {
254
+ if (deviceMap[key])
255
+ await userDevicesCache.set(key, deviceMap[key]);
256
+ }
257
+ }
258
+ });
259
+ const userDeviceUpdates = {};
260
+ for (const [userId, devices] of Object.entries(deviceMap)) {
261
+ if (devices && devices.length > 0) {
262
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
263
+ }
264
+ }
265
+ if (Object.keys(userDeviceUpdates).length > 0) {
266
+ try {
267
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
268
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
269
+ }
270
+ catch (error) {
271
+ logger.warn({ error }, 'failed to store user device lists');
272
+ }
273
+ }
274
+ }
275
+ return deviceResults;
276
+ };
277
+ /**
278
+ * Update Member Label
279
+ */
280
+ const updateMemberLabel = (jid, memberLabel) => {
281
+ return relayMessage(jid, {
282
+ protocolMessage: {
283
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
284
+ memberLabel: {
285
+ label: memberLabel?.slice(0, 30),
286
+ labelTimestamp: unixTimestampSeconds()
287
+ }
288
+ }
289
+ }, {
290
+ additionalNodes: [
291
+ {
292
+ tag: 'meta',
293
+ attrs: {
294
+ tag_reason: 'user_update',
295
+ appdata: 'member_tag'
296
+ },
297
+ content: undefined
298
+ }
299
+ ]
300
+ });
301
+ };
302
+ const assertSessions = async (jids, force) => {
303
+ let didFetchNewSession = false;
304
+ const uniqueJids = [...new Set(jids)];
305
+ const jidsRequiringFetch = [];
306
+ logger.debug({ jids }, 'assertSessions call with jids');
307
+ for (const jid of uniqueJids) {
308
+ if (!force) {
309
+ const sessionValidation = await signalRepository.validateSession(jid);
310
+ if (sessionValidation.exists) {
311
+ continue;
312
+ }
313
+ }
314
+ jidsRequiringFetch.push(jid);
315
+ }
316
+ if (jidsRequiringFetch.length) {
317
+ // LID if mapped, otherwise original
318
+ const wireJids = [
319
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
320
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
321
+ ];
322
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
323
+ const result = await query({
324
+ tag: 'iq',
325
+ attrs: {
326
+ xmlns: 'encrypt',
327
+ type: 'get',
328
+ to: S_WHATSAPP_NET
329
+ },
330
+ content: [
331
+ {
332
+ tag: 'key',
333
+ attrs: {},
334
+ content: wireJids.map(jid => {
335
+ const attrs = { jid };
336
+ if (force)
337
+ attrs.reason = 'identity';
338
+ return { tag: 'user', attrs };
339
+ })
340
+ }
341
+ ]
342
+ });
343
+ await parseAndInjectE2ESessions(result, signalRepository);
344
+ didFetchNewSession = true;
345
+ }
346
+ return didFetchNewSession;
347
+ };
348
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
349
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
350
+ if (!authState.creds.me?.id) {
351
+ throw new Boom('Not authenticated');
352
+ }
353
+ const protocolMessage = {
354
+ protocolMessage: {
355
+ peerDataOperationRequestMessage: pdoMessage,
356
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
357
+ }
358
+ };
359
+ const meJid = jidNormalizedUser(authState.creds.me.id);
360
+ const msgId = await relayMessage(meJid, protocolMessage, {
361
+ additionalAttributes: {
362
+ category: 'peer',
363
+ push_priority: 'high_force'
364
+ },
365
+ additionalNodes: [
366
+ {
367
+ tag: 'meta',
368
+ attrs: { appdata: 'default' }
369
+ }
370
+ ]
371
+ });
372
+ return msgId;
373
+ };
374
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
375
+ if (!recipientJids.length) {
376
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
377
+ }
378
+ const patched = await patchMessageBeforeSending(message, recipientJids);
379
+ const patchedMessages = Array.isArray(patched)
380
+ ? patched
381
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
382
+ let shouldIncludeDeviceIdentity = false;
383
+ const meId = authState.creds.me.id;
384
+ const meLid = authState.creds.me?.lid;
385
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
386
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
387
+ try {
388
+ if (!jid)
389
+ return null;
390
+ let msgToEncrypt = patchedMessage;
391
+ if (dsmMessage) {
392
+ const { user: targetUser } = jidDecode(jid);
393
+ const { user: ownPnUser } = jidDecode(meId);
394
+ const ownLidUser = meLidUser;
395
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
396
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
397
+ if (isOwnUser && !isExactSenderDevice) {
398
+ msgToEncrypt = dsmMessage;
399
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
400
+ }
401
+ }
402
+ const bytes = encodeWAMessage(msgToEncrypt);
403
+ const mutexKey = jid;
404
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
405
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
406
+ if (type === 'pkmsg') {
407
+ shouldIncludeDeviceIdentity = true;
408
+ }
409
+ return {
410
+ tag: 'to',
411
+ attrs: { jid },
412
+ content: [
413
+ {
414
+ tag: 'enc',
415
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
416
+ content: ciphertext
417
+ }
418
+ ]
419
+ };
420
+ });
421
+ return node;
422
+ }
423
+ catch (err) {
424
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
425
+ return null;
426
+ }
427
+ });
428
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
429
+ if (recipientJids.length > 0 && nodes.length === 0) {
430
+ throw new Boom('All encryptions failed', { statusCode: 500 });
431
+ }
432
+ return { nodes, shouldIncludeDeviceIdentity };
433
+ };
434
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList }) => {
435
+ const meId = assertMeId(authState.creds);
436
+ const meLid = authState.creds.me?.lid;
437
+ const isRetryResend = Boolean(participant?.jid);
438
+ let shouldIncludeDeviceIdentity = isRetryResend;
439
+ const statusJid = 'status@broadcast';
440
+ const { user, server } = jidDecode(jid);
441
+ const isGroup = server === 'g.us';
442
+ const isStatus = jid === statusJid;
443
+ const isLid = server === 'lid';
444
+ const isNewsletter = server === 'newsletter';
445
+ const isGroupOrStatus = isGroup || isStatus;
446
+ const finalJid = jid;
447
+ msgId = msgId || generateMessageIDV2(meId);
448
+ useUserDevicesCache = useUserDevicesCache !== false;
449
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
450
+ const participants = [];
451
+ const destinationJid = !isStatus ? finalJid : statusJid;
452
+ const binaryNodeContent = [];
453
+ const devices = [];
454
+ let reportingMessage;
455
+ const meMsg = {
456
+ deviceSentMessage: {
457
+ destinationJid,
458
+ message
459
+ },
460
+ messageContextInfo: message.messageContextInfo
461
+ };
462
+ const extraAttrs = {};
463
+ if (participant) {
464
+ if (!isGroup && !isStatus) {
465
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
466
+ }
467
+ const { user, device } = jidDecode(participant.jid);
468
+ devices.push({
469
+ user,
470
+ device,
471
+ jid: participant.jid
472
+ });
473
+ }
474
+ await authState.keys.transaction(async () => {
475
+ // Lia@Changes 02-02-26 --- Normalize message first to extract the original message and valid media type
476
+ const innerMessage = normalizeMessageContent(message);
477
+ const mediaType = getMediaType(innerMessage);
478
+ if (mediaType) {
479
+ extraAttrs['mediatype'] = mediaType;
480
+ }
481
+ if (isNewsletter) {
482
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
483
+ const bytes = encodeNewsletterMessage(patched);
484
+ // Lia@Changes 08-02-26 --- Add "additionalNodes" for newsletter too (⁠っ⁠˘̩⁠╭⁠╮⁠˘̩⁠)⁠っ
485
+ if (additionalNodes && additionalNodes.length > 0) {
486
+ ;
487
+ binaryNodeContent.push(...additionalNodes);
488
+ }
489
+ binaryNodeContent.push({
490
+ tag: 'plaintext',
491
+ attrs: extraAttrs, // Lia@Changes 02-02-26 --- Add extraAttrs to fix media being rejected when sending to newsletter (⁠◠⁠‿⁠◕⁠)
492
+ content: bytes
493
+ });
494
+ const stanza = {
495
+ tag: 'message',
496
+ attrs: {
497
+ to: jid,
498
+ id: msgId,
499
+ type: getMessageType(innerMessage),
500
+ ...(additionalAttributes || {})
501
+ },
502
+ content: binaryNodeContent
503
+ };
504
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
505
+ await sendNode(stanza);
506
+ return;
507
+ }
508
+ // Lia@Changes 02-02-26 --- Add keepInChat, editedMessage, mediaNotifyMessage and pollUpdateMessage
509
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
510
+ // Lia@Changes 12-05-26 --- Add groupStatusMessage attributes
511
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
512
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
513
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
514
+ const metaAttrs = {};
515
+ if (isNeedMetaAttrs) {
516
+ metaAttrs.content_type = 'add_on';
517
+ }
518
+ if (isPollUpdate && !isGroupStatus) {
519
+ metaAttrs.polltype = 'vote';
520
+ }
521
+ if (isGroupStatus) {
522
+ metaAttrs.is_group_status = 'true';
523
+ }
524
+ binaryNodeContent.push({
525
+ tag: 'meta',
526
+ attrs: metaAttrs,
527
+ content: undefined
528
+ });
529
+ }
530
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
531
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
532
+ }
533
+ // Lia@Changes 02-02-26 --- Add native_flow_name to extraAttrs when sending interactiveResponseMessage
534
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
535
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
536
+ }
537
+ if (isGroupOrStatus && !isRetryResend) {
538
+ const [groupData, senderKeyMap] = await Promise.all([
539
+ (async () => {
540
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
541
+ if (groupData && Array.isArray(groupData?.participants)) {
542
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
543
+ }
544
+ else if (!isStatus) {
545
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
546
+ }
547
+ return groupData;
548
+ })(),
549
+ (async () => {
550
+ if (!participant && !isStatus) {
551
+ // what if sender memory is less accurate than the cached metadata
552
+ // on participant change in group, we should do sender memory manipulation
553
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
554
+ return result[jid] || {};
555
+ }
556
+ return {};
557
+ })()
558
+ ]);
559
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
560
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
561
+ additionalAttributes = {
562
+ ...additionalAttributes,
563
+ expiration: groupData.ephemeralDuration.toString()
564
+ };
565
+ }
566
+ if (isStatus && statusJidList) {
567
+ participantsList.push(...statusJidList);
568
+ }
569
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
570
+ devices.push(...additionalDevices);
571
+ if (isGroup) {
572
+ additionalAttributes = {
573
+ ...additionalAttributes,
574
+ addressing_mode: groupData?.addressingMode || 'lid'
575
+ };
576
+ }
577
+ const patched = await patchMessageBeforeSending(message);
578
+ if (Array.isArray(patched)) {
579
+ throw new Boom('Per-jid patching is not supported in groups');
580
+ }
581
+ const bytes = encodeWAMessage(patched);
582
+ reportingMessage = patched;
583
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
584
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
585
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
586
+ group: destinationJid,
587
+ data: bytes,
588
+ meId: groupSenderIdentity
589
+ });
590
+ const senderKeyRecipients = [];
591
+ for (const device of devices) {
592
+ const deviceJid = device.jid;
593
+ const hasKey = !!senderKeyMap[deviceJid];
594
+ if ((!hasKey || !!participant) &&
595
+ !isHostedLidUser(deviceJid) &&
596
+ !isHostedPnUser(deviceJid) &&
597
+ device.device !== 99) {
598
+ //todo: revamp all this logic
599
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
600
+ senderKeyRecipients.push(deviceJid);
601
+ senderKeyMap[deviceJid] = true;
602
+ }
603
+ }
604
+ if (senderKeyRecipients.length) {
605
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
606
+ const senderKeyMsg = {
607
+ senderKeyDistributionMessage: {
608
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
609
+ groupId: destinationJid
610
+ }
611
+ };
612
+ const senderKeySessionTargets = senderKeyRecipients;
613
+ await assertSessions(senderKeySessionTargets);
614
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
615
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
616
+ participants.push(...result.nodes);
617
+ }
618
+ binaryNodeContent.push({
619
+ tag: 'enc',
620
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
621
+ content: ciphertext
622
+ });
623
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
624
+ }
625
+ else {
626
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
627
+ // TODO: investigate if this is true
628
+ let ownId = meId;
629
+ if (isLid && meLid) {
630
+ ownId = meLid;
631
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
632
+ }
633
+ else {
634
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
635
+ }
636
+ const { user: ownUser } = jidDecode(ownId);
637
+ if (!participant) {
638
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
639
+ reportingMessage = Array.isArray(patchedForReporting)
640
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
641
+ : patchedForReporting;
642
+ }
643
+ if (!isRetryResend) {
644
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
645
+ devices.push({
646
+ user,
647
+ device: 0,
648
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
649
+ });
650
+ if (user !== ownUser) {
651
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
652
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
653
+ devices.push({
654
+ user: ownUserForAddressing,
655
+ device: 0,
656
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
657
+ });
658
+ }
659
+ if (additionalAttributes?.['category'] !== 'peer') {
660
+ // Clear placeholders and enumerate actual devices
661
+ devices.length = 0;
662
+ // Use conversation-appropriate sender identity
663
+ const senderIdentity = isLid && meLid
664
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
665
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
666
+ // Enumerate devices for sender and target with consistent addressing
667
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
668
+ devices.push(...sessionDevices);
669
+ logger.debug({
670
+ deviceCount: devices.length,
671
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
672
+ }, 'Device enumeration complete with unified addressing');
673
+ }
674
+ }
675
+ const allRecipients = [];
676
+ const meRecipients = [];
677
+ const otherRecipients = [];
678
+ const { user: mePnUser } = jidDecode(meId);
679
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
680
+ for (const { user, jid } of devices) {
681
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
682
+ if (isExactSenderDevice) {
683
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
684
+ continue;
685
+ }
686
+ // Check if this is our device (could match either PN or LID user)
687
+ const isMe = user === mePnUser || user === meLidUser;
688
+ if (isMe) {
689
+ meRecipients.push(jid);
690
+ }
691
+ else {
692
+ otherRecipients.push(jid);
693
+ }
694
+ allRecipients.push(jid);
695
+ }
696
+ await assertSessions(allRecipients);
697
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
698
+ // For own devices: use DSM if available (1:1 chats only)
699
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
700
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
701
+ ]);
702
+ participants.push(...meNodes);
703
+ participants.push(...otherNodes);
704
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
705
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
706
+ }
707
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
708
+ }
709
+ if (isRetryResend) {
710
+ const isParticipantLid = isLidUser(participant.jid);
711
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
712
+ let messageToSend = message;
713
+ if (isGroupOrStatus) {
714
+ let groupSenderIdentity;
715
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
716
+ groupSenderIdentity = meLid;
717
+ }
718
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
719
+ groupSenderIdentity = meId;
720
+ }
721
+ if (groupSenderIdentity) {
722
+ try {
723
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
724
+ group: destinationJid,
725
+ meId: groupSenderIdentity
726
+ });
727
+ messageToSend = {
728
+ ...message,
729
+ senderKeyDistributionMessage: {
730
+ groupId: destinationJid,
731
+ axolotlSenderKeyDistributionMessage: skdm
732
+ }
733
+ };
734
+ }
735
+ catch (err) {
736
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
737
+ }
738
+ }
739
+ }
740
+ const encodedMessageToSend = isMe
741
+ ? encodeWAMessage({
742
+ deviceSentMessage: {
743
+ destinationJid,
744
+ message: messageToSend
745
+ }
746
+ })
747
+ : encodeWAMessage(messageToSend);
748
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
749
+ data: encodedMessageToSend,
750
+ jid: participant.jid
751
+ });
752
+ binaryNodeContent.push({
753
+ tag: 'enc',
754
+ attrs: {
755
+ v: '2',
756
+ type,
757
+ count: (participant.count || 0).toString()
758
+ },
759
+ content: encryptedContent
760
+ });
761
+ }
762
+ if (participants.length) {
763
+ if (additionalAttributes?.['category'] === 'peer') {
764
+ const peerNode = participants[0]?.content?.[0];
765
+ if (peerNode) {
766
+ binaryNodeContent.push(peerNode); // push only enc
767
+ }
768
+ }
769
+ else {
770
+ binaryNodeContent.push({
771
+ tag: 'participants',
772
+ attrs: {},
773
+ content: participants
774
+ });
775
+ }
776
+ }
777
+ const stanza = {
778
+ tag: 'message',
779
+ attrs: {
780
+ id: msgId,
781
+ to: destinationJid,
782
+ type: getMessageType(innerMessage),
783
+ ...(additionalAttributes || {})
784
+ },
785
+ content: binaryNodeContent
786
+ };
787
+ // if the participant to send to is explicitly specified (generally retry recp)
788
+ // ensure the message is only sent to that person
789
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
790
+ if (participant) {
791
+ if (isJidGroup(destinationJid)) {
792
+ stanza.attrs.to = destinationJid;
793
+ stanza.attrs.participant = participant.jid;
794
+ }
795
+ else if (areJidsSameUser(participant.jid, meId)) {
796
+ stanza.attrs.to = participant.jid;
797
+ stanza.attrs.recipient = destinationJid;
798
+ }
799
+ else {
800
+ stanza.attrs.to = participant.jid;
801
+ }
802
+ }
803
+ else {
804
+ stanza.attrs.to = destinationJid;
805
+ }
806
+ if (shouldIncludeDeviceIdentity) {
807
+ ;
808
+ stanza.content.push({
809
+ tag: 'device-identity',
810
+ attrs: {},
811
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
812
+ });
813
+ logger.debug({ jid }, 'adding device identity');
814
+ }
815
+ if (!isNewsletter &&
816
+ !isRetryResend &&
817
+ reportingMessage?.messageContextInfo?.messageSecret &&
818
+ shouldIncludeReportingToken(reportingMessage)) {
819
+ try {
820
+ const encoded = encodeWAMessage(reportingMessage);
821
+ const reportingKey = {
822
+ id: msgId,
823
+ fromMe: true,
824
+ remoteJid: destinationJid,
825
+ participant: participant?.jid
826
+ };
827
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
828
+ if (reportingNode) {
829
+ ;
830
+ stanza.content.push(reportingNode);
831
+ logger.trace({ jid }, 'added reporting token to message');
832
+ }
833
+ }
834
+ catch (error) {
835
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
836
+ }
837
+ }
838
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
839
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
840
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
841
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
842
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
843
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
844
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
845
+ let tcTokenBuffer = existingTokenEntry?.token;
846
+ // Treat expired tokens the same as missing — clear from cache
847
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
848
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
849
+ tcTokenBuffer = undefined;
850
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
851
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
852
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
853
+ : null;
854
+ try {
855
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
856
+ }
857
+ catch (err) {
858
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
859
+ }
860
+ }
861
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
862
+ ;
863
+ stanza.content.push({
864
+ tag: 'tctoken',
865
+ attrs: {},
866
+ content: tcTokenBuffer
867
+ });
868
+ }
869
+ let alreadyHasBizNode = false;
870
+ if (additionalNodes && additionalNodes.length > 0) {
871
+ ;
872
+ stanza.content.push(...additionalNodes);
873
+ alreadyHasBizNode = !addBizAttributes &&
874
+ additionalNodes.some(node => node.tag === 'biz');
875
+ }
876
+ // Lia@Changes 30-01-26 --- Add Biz Binary Node to support button messages
877
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
878
+ const bizNode = getBizBinaryNode(innerMessage);
879
+ stanza.content.push(bizNode);
880
+ }
881
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
882
+ await sendNode(stanza);
883
+ // Fire-and-forget: issue our token to the contact AFTER message send.
884
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
885
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
886
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
887
+ if (is1on1Send &&
888
+ !isProtocolMsg &&
889
+ !isBotOrPSA &&
890
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
891
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
892
+ inFlightTcTokenIssuance.add(tcTokenJid);
893
+ const issueTimestamp = unixTimestampSeconds();
894
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
895
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
896
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
897
+ .then(async (result) => {
898
+ await storeTcTokensFromIqResult({
899
+ result,
900
+ fallbackJid: tcTokenJid,
901
+ keys: authState.keys,
902
+ getLIDForPN
903
+ });
904
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
905
+ const currentEntry = currentData[tcTokenJid];
906
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
907
+ await authState.keys.set({
908
+ tctoken: {
909
+ [tcTokenJid]: {
910
+ token: Buffer.alloc(0),
911
+ ...currentEntry,
912
+ senderTimestamp: issueTimestamp
913
+ },
914
+ ...indexWrite
915
+ }
916
+ });
917
+ })
918
+ .catch(err => {
919
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
920
+ })
921
+ .finally(() => {
922
+ inFlightTcTokenIssuance.delete(tcTokenJid);
923
+ });
924
+ }
925
+ // Add message to retry cache if enabled
926
+ if (messageRetryManager && !participant) {
927
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
928
+ }
929
+ }, meId);
930
+ return msgId;
931
+ };
932
+ const getMessageType = (message) => {
933
+ if (!message)
934
+ return 'text';
935
+ if (message.reactionMessage || message.encReactionMessage) {
936
+ return 'reaction';
937
+ }
938
+ if (message.pollCreationMessage ||
939
+ message.pollCreationMessageV2 ||
940
+ message.pollCreationMessageV3 ||
941
+ message.pollCreationMessageV5 ||
942
+ message.pollCreationMessageV6 ||
943
+ message.pollUpdateMessage) {
944
+ return 'poll';
945
+ }
946
+ if (message.eventMessage) {
947
+ return 'event';
948
+ }
949
+ if (getMediaType(message) !== '') {
950
+ return 'media';
951
+ }
952
+ return 'text';
953
+ };
954
+ const getMediaType = (message) => {
955
+ if (message.imageMessage) {
956
+ return 'image';
957
+ }
958
+ else if (message.videoMessage) {
959
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
960
+ }
961
+ else if (message.stickerMessage) {
962
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
963
+ }
964
+ else if (message.audioMessage) {
965
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
966
+ }
967
+ else if (message.albumMessage) {
968
+ return 'collection';
969
+ }
970
+ else if (message.contactMessage) {
971
+ return 'vcard';
972
+ }
973
+ else if (message.documentMessage) {
974
+ return 'document';
975
+ }
976
+ else if (message.contactsArrayMessage) {
977
+ return 'contact_array';
978
+ }
979
+ else if (message.liveLocationMessage) {
980
+ return 'livelocation';
981
+ }
982
+ else if (message.stickerPackMessage) {
983
+ return 'sticker_pack';
984
+ }
985
+ else if (message.listMessage) {
986
+ return 'list';
987
+ }
988
+ else if (message.listResponseMessage) {
989
+ return 'list_response';
990
+ }
991
+ else if (message.buttonsResponseMessage) {
992
+ return 'buttons_response';
993
+ }
994
+ else if (message.orderMessage) {
995
+ return 'order';
996
+ }
997
+ else if (message.productMessage) {
998
+ return 'product';
999
+ }
1000
+ else if (message.interactiveResponseMessage) {
1001
+ return 'native_flow_response';
1002
+ }
1003
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1004
+ return 'url';
1005
+ }
1006
+ // Lia@Note 02-02-26 --- Add more message type here
1007
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1008
+ return 'cataloglink';
1009
+ }
1010
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1011
+ return 'productlink';
1012
+ }
1013
+ return '';
1014
+ };
1015
+ const issuePrivacyTokens = async (jids, timestamp) => {
1016
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1017
+ const result = await query({
1018
+ tag: 'iq',
1019
+ attrs: {
1020
+ to: S_WHATSAPP_NET,
1021
+ type: 'set',
1022
+ xmlns: 'privacy'
1023
+ },
1024
+ content: [
1025
+ {
1026
+ tag: 'tokens',
1027
+ attrs: {},
1028
+ content: jids.map(jid => ({
1029
+ tag: 'token',
1030
+ attrs: {
1031
+ jid: jidNormalizedUser(jid),
1032
+ t,
1033
+ type: 'trusted_contact'
1034
+ }
1035
+ }))
1036
+ }
1037
+ ]
1038
+ });
1039
+ return result;
1040
+ };
1041
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1042
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1043
+ registerSocketEndHandler(() => {
1044
+ if (!config.userDevicesCache && userDevicesCache.close) {
1045
+ userDevicesCache.close();
1046
+ }
1047
+ mediaConn = undefined;
1048
+ if (messageRetryManager) {
1049
+ messageRetryManager.clear();
1050
+ }
1051
+ });
1052
+ return {
1053
+ ...sock,
1054
+ userDevicesCache,
1055
+ devicesMutex,
1056
+ issuePrivacyTokens,
1057
+ assertSessions,
1058
+ relayMessage,
1059
+ sendReceipt,
1060
+ sendReceipts,
1061
+ readMessages,
1062
+ refreshMediaConn,
1063
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1064
+ getMediaHost: () => mediaHost,
1065
+ waUploadToServer,
1066
+ fetchPrivacySettings,
1067
+ sendPeerDataOperationMessage,
1068
+ createParticipantNodes,
1069
+ getUSyncDevices,
1070
+ messageRetryManager,
1071
+ updateMemberLabel,
1072
+ updateMediaMessage: async (message) => {
1073
+ const content = assertMediaContent(message.message);
1074
+ const mediaKey = content.mediaKey;
1075
+ const meId = authState.creds.me.id;
1076
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1077
+ let error = undefined;
1078
+ await Promise.all([
1079
+ sendNode(node),
1080
+ waitForMsgMediaUpdate(async (update) => {
1081
+ const result = update.find(c => c.key.id === message.key.id);
1082
+ if (result) {
1083
+ if (result.error) {
1084
+ error = result.error;
1085
+ }
1086
+ else {
1087
+ try {
1088
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1089
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1090
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1091
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1092
+ data: media,
1093
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1094
+ });
1095
+ }
1096
+ content.directPath = media.directPath;
1097
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1098
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1099
+ }
1100
+ catch (err) {
1101
+ error = err;
1102
+ }
1103
+ }
1104
+ return true;
1105
+ }
1106
+ })
1107
+ ]);
1108
+ if (error) {
1109
+ throw error;
1110
+ }
1111
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1112
+ return message;
1113
+ },
1114
+ // Lia@Changes 30-01-26 --- Add support for modifying additionalNodes and additionalAttributes using "options" in sendMessage()
1115
+ sendMessage: async (jid, content, options = {}) => {
1116
+ const userJid = authState.creds.me.id;
1117
+ // Lia@Changes 13-03-26 --- Add status mentions!
1118
+ if (Array.isArray(jid)) {
1119
+ const { delayMs = 1500 } = options;
1120
+ const allUsers = new Set();
1121
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1122
+ logger,
1123
+ userJid,
1124
+ upload: waUploadToServer,
1125
+ mediaCache: config.mediaCache,
1126
+ options: config.options,
1127
+ ...options,
1128
+ messageId: generateMessageIDV2(userJid)
1129
+ });
1130
+ for (const id of jid) {
1131
+ if (isJidGroup(id)) {
1132
+ try {
1133
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1134
+ for (const participant of groupData.participants) {
1135
+ if (allUsers.has(participant.id))
1136
+ continue;
1137
+ allUsers.add(participant.id);
1138
+ }
1139
+ }
1140
+ catch (error) {
1141
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1142
+ }
1143
+ }
1144
+ else if (!allUsers.has(id)) {
1145
+ allUsers.add(id);
1146
+ }
1147
+ }
1148
+ await relayMessage('status@broadcast', fullMsg.message, {
1149
+ messageId: fullMsg.key.id,
1150
+ statusJidList: Array.from(allUsers),
1151
+ additionalNodes: [
1152
+ {
1153
+ tag: 'meta',
1154
+ attrs: {},
1155
+ content: [
1156
+ {
1157
+ tag: 'mentioned_users',
1158
+ attrs: {},
1159
+ content: jid.map(id => ({
1160
+ tag: 'to',
1161
+ attrs: { jid: id },
1162
+ content: undefined
1163
+ }))
1164
+ }
1165
+ ]
1166
+ }
1167
+ ]
1168
+ });
1169
+ if (config.emitOwnEvents) {
1170
+ process.nextTick(async () => {
1171
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1172
+ });
1173
+ }
1174
+ for (const id of jid) {
1175
+ const isGroup = isJidGroup(id);
1176
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1177
+ const mentionMsg = generateWAMessageFromContent(id, {
1178
+ messageContextInfo: {
1179
+ messageSecret: randomBytes(32)
1180
+ },
1181
+ [sendType]: {
1182
+ message: {
1183
+ protocolMessage: {
1184
+ key: fullMsg.key,
1185
+ type: 25
1186
+ }
1187
+ }
1188
+ }
1189
+ }, {
1190
+ userJid
1191
+ });
1192
+ await relayMessage(id, mentionMsg.message, {
1193
+ additionalNodes: [
1194
+ {
1195
+ tag: 'meta',
1196
+ attrs: isGroup ?
1197
+ { is_group_status_mention: 'true' } :
1198
+ { is_status_mention: 'true' },
1199
+ content: undefined
1200
+ }
1201
+ ]
1202
+ });
1203
+ if (config.emitOwnEvents) {
1204
+ process.nextTick(async () => {
1205
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1206
+ });
1207
+ }
1208
+ await delay(delayMs);
1209
+ }
1210
+ return fullMsg;
1211
+ }
1212
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1213
+ const { disappearingMessagesInChat } = content;
1214
+ const value = typeof disappearingMessagesInChat === 'boolean'
1215
+ ? disappearingMessagesInChat
1216
+ ? WA_DEFAULT_EPHEMERAL
1217
+ : 0
1218
+ : disappearingMessagesInChat;
1219
+ await groupToggleEphemeral(jid, value);
1220
+ }
1221
+ else {
1222
+ const fullMsg = await generateWAMessage(jid, content, {
1223
+ logger,
1224
+ userJid,
1225
+ getUrlInfo: text => getUrlInfo(text, {
1226
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1227
+ fetchOpts: {
1228
+ timeout: 3000,
1229
+ ...(httpRequestOptions || {})
1230
+ },
1231
+ logger,
1232
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1233
+ }),
1234
+ //TODO: CACHE
1235
+ getProfilePicUrl: sock.profilePictureUrl,
1236
+ getCallLink: sock.createCallLink,
1237
+ upload: waUploadToServer,
1238
+ mediaCache: config.mediaCache,
1239
+ options: config.options,
1240
+ ...options,
1241
+ messageId: generateMessageIDV2(userJid)
1242
+ });
1243
+ const isNewsletter = isJidNewsletter(jid);
1244
+ const isEventMsg = 'event' in content && !!content.event;
1245
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1246
+ const isEditMsg = 'edit' in content && !!content.edit;
1247
+ const isPinMsg = 'pin' in content && !!content.pin;
1248
+ const isKeepMsg = 'keep' in content && !!content.keep;
1249
+ const isPollMsg = 'poll' in content && !!content.poll;
1250
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
1251
+ const isAiMsg = 'ai' in content && !!content.ai;
1252
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1253
+ const additionalAttributes = options.additionalAttributes || {};
1254
+ const additionalNodes = options.additionalNodes || [];
1255
+ // required for delete
1256
+ if (isDeleteMsg || isKeepMsg) {
1257
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1258
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1259
+ additionalAttributes.edit = '8';
1260
+ }
1261
+ else {
1262
+ additionalAttributes.edit = '7';
1263
+ }
1264
+ }
1265
+ else if (isEditMsg) {
1266
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1267
+ }
1268
+ else if (isPinMsg) {
1269
+ additionalAttributes.edit = '2';
1270
+ }
1271
+ else if (isPollMsg) {
1272
+ if (!isNewsletter && isQuizMsg) {
1273
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
1274
+ }
1275
+ additionalNodes.push({
1276
+ tag: 'meta',
1277
+ attrs: {
1278
+ // Lia@Note 08-02-26 --- Still a hypothesis regarding PollResult ༎ຶ⁠‿⁠༎ຶ
1279
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1280
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1281
+ },
1282
+ content: undefined
1283
+ });
1284
+ }
1285
+ else if (isEventMsg) {
1286
+ additionalNodes.push({
1287
+ tag: 'meta',
1288
+ attrs: {
1289
+ event_type: 'creation'
1290
+ },
1291
+ content: undefined
1292
+ });
1293
+ }
1294
+ // Lia@Changes 30-01-26 --- Add support for AI label in message when "ai" is true, but works only in private chat
1295
+ else if (isAiMsg) {
1296
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1297
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1298
+ }
1299
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1300
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1301
+ }
1302
+ ;
1303
+ additionalNodes.push({
1304
+ tag: 'bot',
1305
+ attrs: {
1306
+ biz_bot: '1'
1307
+ },
1308
+ content: undefined
1309
+ });
1310
+ delete content.ai;
1311
+ }
1312
+ await relayMessage(jid, fullMsg.message, {
1313
+ messageId: fullMsg.key.id,
1314
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1315
+ addBizAttributes: isNeedBizAttrs,
1316
+ statusJidList: options.statusJidList,
1317
+ additionalAttributes,
1318
+ additionalNodes
1319
+ });
1320
+ if (config.emitOwnEvents) {
1321
+ process.nextTick(async () => {
1322
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1323
+ });
1324
+ }
1325
+ // Lia@Changes 31-01-26 --- Add support for album messages
1326
+ // Lia@Note 06-02-26 --- Refactored to reduce high RSS usage (⁠╥⁠﹏⁠╥⁠)
1327
+ if ('album' in content) {
1328
+ const { delayMs = 1500 } = options;
1329
+ for (const albumMedia of content.album) {
1330
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1331
+ logger,
1332
+ userJid,
1333
+ upload: waUploadToServer,
1334
+ mediaCache: config.mediaCache,
1335
+ options: config.options,
1336
+ ...options,
1337
+ messageId: generateMessageIDV2(userJid)
1338
+ });
1339
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1340
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
1341
+ }
1342
+ albumMsg.message.messageContextInfo ||= {};
1343
+ albumMsg.message.messageContextInfo.messageAssociation = {
1344
+ parentMessageKey: fullMsg.key,
1345
+ associationType: AssociationType.MEDIA_ALBUM
1346
+ };
1347
+ await relayMessage(jid, albumMsg.message, {
1348
+ messageId: albumMsg.key.id,
1349
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1350
+ addBizAttributes: isNeedBizAttrs,
1351
+ statusJidList: options.statusJidList,
1352
+ additionalAttributes,
1353
+ additionalNodes
1354
+ });
1355
+ if (config.emitOwnEvents) {
1356
+ process.nextTick(async () => {
1357
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1358
+ });
1359
+ }
1360
+ await delay(delayMs);
1361
+ }
1362
+ }
1363
+ return fullMsg;
1364
+ }
1365
+ }
1366
+ };
1367
+ };
1368
+ //# sourceMappingURL=messages-send.js.map