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