@ryuhan/baileys 1.0.10 → 2.0.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 (407) hide show
  1. package/README.md +582 -83
  2. package/WAProto/GenerateStatics.sh +3 -4
  3. package/WAProto/WAProto.proto +1215 -511
  4. package/WAProto/fix-imports.js +81 -0
  5. package/WAProto/index.d.ts +14017 -0
  6. package/WAProto/index.js +65471 -137445
  7. package/index.cjs +196 -0
  8. package/index.d.ts +30 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +78 -64
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Defaults/phonenumber-mcc.json +223 -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 +2 -5
  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 +7 -41
  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 +37 -51
  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 -57
  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 +7 -44
  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 +7 -15
  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 +8 -11
  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 +9 -12
  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 +2 -5
  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 +9 -21
  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 +27 -42
  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 +4 -7
  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 +352 -88
  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 -18
  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 +4 -6
  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 +21 -39
  81. package/lib/Socket/Client/websocket.js.map +1 -0
  82. package/lib/Socket/business.d.ts +202 -0
  83. package/lib/Socket/business.d.ts.map +1 -0
  84. package/lib/Socket/business.js +162 -43
  85. package/lib/Socket/business.js.map +1 -0
  86. package/lib/Socket/chats.d.ts +111 -0
  87. package/lib/Socket/chats.d.ts.map +1 -0
  88. package/lib/Socket/chats.js +477 -316
  89. package/lib/Socket/chats.js.map +1 -0
  90. package/lib/Socket/communities.d.ts +258 -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/community.js +361 -0
  95. package/lib/Socket/groups.d.ts +150 -0
  96. package/lib/Socket/groups.d.ts.map +1 -0
  97. package/lib/Socket/groups.js +228 -101
  98. package/lib/Socket/groups.js.map +1 -0
  99. package/lib/Socket/index.d.ts +245 -0
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +11 -9
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/messages-recv.d.ts +187 -0
  104. package/lib/Socket/messages-recv.d.ts.map +1 -0
  105. package/lib/Socket/messages-recv.js +1092 -515
  106. package/lib/Socket/messages-recv.js.map +1 -0
  107. package/lib/Socket/messages-send.d.ts +183 -0
  108. package/lib/Socket/messages-send.d.ts.map +1 -0
  109. package/lib/Socket/messages-send.js +1148 -387
  110. package/lib/Socket/messages-send.js.map +1 -0
  111. package/lib/Socket/mex.d.ts +3 -0
  112. package/lib/Socket/mex.d.ts.map +1 -0
  113. package/lib/Socket/mex.js +42 -0
  114. package/lib/Socket/mex.js.map +1 -0
  115. package/lib/Socket/newsletter.d.ts +160 -0
  116. package/lib/Socket/newsletter.d.ts.map +1 -0
  117. package/lib/Socket/newsletter.js +229 -209
  118. package/lib/Socket/newsletter.js.map +1 -0
  119. package/lib/Socket/socket.d.ts +55 -0
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +517 -219
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Socket/usync.js +19 -13
  124. package/lib/Store/index.js +4 -8
  125. package/lib/Store/make-cache-manager-store.js +77 -0
  126. package/lib/Store/make-in-memory-store.js +59 -98
  127. package/lib/Store/make-ordered-dictionary.js +1 -4
  128. package/lib/Store/object-repository.js +1 -5
  129. package/lib/Types/Auth.d.ts +116 -0
  130. package/lib/Types/Auth.d.ts.map +1 -0
  131. package/lib/Types/Auth.js +2 -2
  132. package/lib/Types/Auth.js.map +1 -0
  133. package/lib/Types/Bussines.d.ts +25 -0
  134. package/lib/Types/Bussines.d.ts.map +1 -0
  135. package/lib/Types/Bussines.js +2 -0
  136. package/lib/Types/Bussines.js.map +1 -0
  137. package/lib/Types/Call.d.ts +15 -0
  138. package/lib/Types/Call.d.ts.map +1 -0
  139. package/lib/Types/Call.js +2 -2
  140. package/lib/Types/Call.js.map +1 -0
  141. package/lib/Types/Chat.d.ts +123 -0
  142. package/lib/Types/Chat.d.ts.map +1 -0
  143. package/lib/Types/Chat.js +8 -4
  144. package/lib/Types/Chat.js.map +1 -0
  145. package/lib/Types/Contact.d.ts +24 -0
  146. package/lib/Types/Contact.d.ts.map +1 -0
  147. package/lib/Types/Contact.js +2 -2
  148. package/lib/Types/Contact.js.map +1 -0
  149. package/lib/Types/Events.d.ts +237 -0
  150. package/lib/Types/Events.d.ts.map +1 -0
  151. package/lib/Types/Events.js +2 -2
  152. package/lib/Types/Events.js.map +1 -0
  153. package/lib/Types/GroupMetadata.d.ts +67 -0
  154. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  155. package/lib/Types/GroupMetadata.js +2 -2
  156. package/lib/Types/GroupMetadata.js.map +1 -0
  157. package/lib/Types/Label.d.ts +47 -0
  158. package/lib/Types/Label.d.ts.map +1 -0
  159. package/lib/Types/Label.js +3 -5
  160. package/lib/Types/Label.js.map +1 -0
  161. package/lib/Types/LabelAssociation.d.ts +30 -0
  162. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  163. package/lib/Types/LabelAssociation.js +3 -5
  164. package/lib/Types/LabelAssociation.js.map +1 -0
  165. package/lib/Types/Message.d.ts +305 -0
  166. package/lib/Types/Message.d.ts.map +1 -0
  167. package/lib/Types/Message.js +11 -7
  168. package/lib/Types/Message.js.map +1 -0
  169. package/lib/Types/MexUpdates.js +9 -0
  170. package/lib/Types/Newsletter.d.ts +135 -0
  171. package/lib/Types/Newsletter.d.ts.map +1 -0
  172. package/lib/Types/Newsletter.js +38 -13
  173. package/lib/Types/Newsletter.js.map +1 -0
  174. package/lib/Types/Product.d.ts +79 -0
  175. package/lib/Types/Product.d.ts.map +1 -0
  176. package/lib/Types/Product.js +2 -2
  177. package/lib/Types/Product.js.map +1 -0
  178. package/lib/Types/Signal.d.ts +76 -0
  179. package/lib/Types/Signal.d.ts.map +1 -0
  180. package/lib/Types/Signal.js +2 -2
  181. package/lib/Types/Signal.js.map +1 -0
  182. package/lib/Types/Socket.d.ts +133 -0
  183. package/lib/Types/Socket.d.ts.map +1 -0
  184. package/lib/Types/Socket.js +3 -2
  185. package/lib/Types/Socket.js.map +1 -0
  186. package/lib/Types/State.d.ts +39 -0
  187. package/lib/Types/State.d.ts.map +1 -0
  188. package/lib/Types/State.js +13 -2
  189. package/lib/Types/State.js.map +1 -0
  190. package/lib/Types/USync.d.ts +26 -0
  191. package/lib/Types/USync.d.ts.map +1 -0
  192. package/lib/Types/USync.js +2 -2
  193. package/lib/Types/USync.js.map +1 -0
  194. package/lib/Types/index.d.ts +65 -0
  195. package/lib/Types/index.d.ts.map +1 -0
  196. package/lib/Types/index.js +16 -31
  197. package/lib/Types/index.js.map +1 -0
  198. package/lib/Utils/audioToBuffer.js +31 -0
  199. package/lib/Utils/auth-utils.d.ts +19 -0
  200. package/lib/Utils/auth-utils.d.ts.map +1 -0
  201. package/lib/Utils/auth-utils.js +228 -137
  202. package/lib/Utils/auth-utils.js.map +1 -0
  203. package/lib/Utils/baileys-event-stream.js +54 -0
  204. package/lib/Utils/browser-utils.d.ts +4 -0
  205. package/lib/Utils/browser-utils.d.ts.map +1 -0
  206. package/lib/Utils/browser-utils.js +37 -31
  207. package/lib/Utils/browser-utils.js.map +1 -0
  208. package/lib/Utils/business.d.ts +23 -0
  209. package/lib/Utils/business.d.ts.map +1 -0
  210. package/lib/Utils/business.js +66 -69
  211. package/lib/Utils/business.js.map +1 -0
  212. package/lib/Utils/chat-utils.d.ts +70 -0
  213. package/lib/Utils/chat-utils.d.ts.map +1 -0
  214. package/lib/Utils/chat-utils.js +315 -233
  215. package/lib/Utils/chat-utils.js.map +1 -0
  216. package/lib/Utils/crypto.d.ts +37 -0
  217. package/lib/Utils/crypto.d.ts.map +1 -0
  218. package/lib/Utils/crypto.js +41 -116
  219. package/lib/Utils/crypto.js.map +1 -0
  220. package/lib/Utils/decode-wa-message.d.ts +48 -0
  221. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  222. package/lib/Utils/decode-wa-message.js +139 -63
  223. package/lib/Utils/decode-wa-message.js.map +1 -0
  224. package/lib/Utils/event-buffer.d.ts +34 -0
  225. package/lib/Utils/event-buffer.d.ts.map +1 -0
  226. package/lib/Utils/event-buffer.js +128 -72
  227. package/lib/Utils/event-buffer.js.map +1 -0
  228. package/lib/Utils/generics.d.ts +91 -0
  229. package/lib/Utils/generics.d.ts.map +1 -0
  230. package/lib/Utils/generics.js +178 -234
  231. package/lib/Utils/generics.js.map +1 -0
  232. package/lib/Utils/history.d.ts +22 -0
  233. package/lib/Utils/history.d.ts.map +1 -0
  234. package/lib/Utils/history.js +83 -46
  235. package/lib/Utils/history.js.map +1 -0
  236. package/lib/Utils/identity-change-handler.d.ts +37 -0
  237. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  238. package/lib/Utils/identity-change-handler.js +49 -0
  239. package/lib/Utils/identity-change-handler.js.map +1 -0
  240. package/lib/Utils/index.d.ts +22 -0
  241. package/lib/Utils/index.d.ts.map +1 -0
  242. package/lib/Utils/index.js +27 -35
  243. package/lib/Utils/index.js.map +1 -0
  244. package/lib/Utils/link-preview.d.ts +21 -0
  245. package/lib/Utils/link-preview.d.ts.map +1 -0
  246. package/lib/Utils/link-preview.js +15 -56
  247. package/lib/Utils/link-preview.js.map +1 -0
  248. package/lib/Utils/logger.d.ts +13 -0
  249. package/lib/Utils/logger.d.ts.map +1 -0
  250. package/lib/Utils/logger.js +3 -7
  251. package/lib/Utils/logger.js.map +1 -0
  252. package/lib/Utils/lt-hash.d.ts +8 -0
  253. package/lib/Utils/lt-hash.d.ts.map +1 -0
  254. package/lib/Utils/lt-hash.js +3 -46
  255. package/lib/Utils/lt-hash.js.map +1 -0
  256. package/lib/Utils/make-mutex.d.ts +9 -0
  257. package/lib/Utils/make-mutex.d.ts.map +1 -0
  258. package/lib/Utils/make-mutex.js +24 -34
  259. package/lib/Utils/make-mutex.js.map +1 -0
  260. package/lib/Utils/message-retry-manager.d.ts +110 -0
  261. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  262. package/lib/Utils/message-retry-manager.js +146 -49
  263. package/lib/Utils/message-retry-manager.js.map +1 -0
  264. package/lib/Utils/messages-media.d.ts +130 -0
  265. package/lib/Utils/messages-media.d.ts.map +1 -0
  266. package/lib/Utils/messages-media.js +468 -517
  267. package/lib/Utils/messages-media.js.map +1 -0
  268. package/lib/Utils/messages-newsletter.d.ts +84 -0
  269. package/lib/Utils/messages-newsletter.js +316 -0
  270. package/lib/Utils/messages.d.ts +92 -0
  271. package/lib/Utils/messages.d.ts.map +1 -0
  272. package/lib/Utils/messages.js +1115 -466
  273. package/lib/Utils/messages.js.map +1 -0
  274. package/lib/Utils/noise-handler.d.ts +20 -0
  275. package/lib/Utils/noise-handler.d.ts.map +1 -0
  276. package/lib/Utils/noise-handler.js +149 -98
  277. package/lib/Utils/noise-handler.js.map +1 -0
  278. package/lib/Utils/pre-key-manager.d.ts +28 -0
  279. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  280. package/lib/Utils/pre-key-manager.js +106 -0
  281. package/lib/Utils/pre-key-manager.js.map +1 -0
  282. package/lib/Utils/process-message.d.ts +60 -0
  283. package/lib/Utils/process-message.d.ts.map +1 -0
  284. package/lib/Utils/process-message.js +319 -195
  285. package/lib/Utils/process-message.js.map +1 -0
  286. package/lib/Utils/reporting-utils.d.ts +11 -0
  287. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  288. package/lib/Utils/reporting-utils.js +258 -0
  289. package/lib/Utils/reporting-utils.js.map +1 -0
  290. package/lib/Utils/resolve-jid.d.ts +43 -0
  291. package/lib/Utils/resolve-jid.js +101 -0
  292. package/lib/Utils/signal.d.ts +34 -0
  293. package/lib/Utils/signal.d.ts.map +1 -0
  294. package/lib/Utils/signal.js +70 -64
  295. package/lib/Utils/signal.js.map +1 -0
  296. package/lib/Utils/streamToBuffer.js +17 -0
  297. package/lib/Utils/sync-action-utils.d.ts +19 -0
  298. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  299. package/lib/Utils/sync-action-utils.js +48 -0
  300. package/lib/Utils/sync-action-utils.js.map +1 -0
  301. package/lib/Utils/tc-token-utils.d.ts +12 -0
  302. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  303. package/lib/Utils/tc-token-utils.js +18 -0
  304. package/lib/Utils/tc-token-utils.js.map +1 -0
  305. package/lib/Utils/use-mongo-file-auth-state.js +77 -0
  306. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  307. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  308. package/lib/Utils/use-multi-file-auth-state.js +24 -28
  309. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  310. package/lib/Utils/use-single-file-auth-state.js +74 -0
  311. package/lib/Utils/validate-connection.d.ts +11 -0
  312. package/lib/Utils/validate-connection.d.ts.map +1 -0
  313. package/lib/Utils/validate-connection.js +70 -99
  314. package/lib/Utils/validate-connection.js.map +1 -0
  315. package/lib/WABinary/constants.d.ts +28 -0
  316. package/lib/WABinary/constants.d.ts.map +1 -0
  317. package/lib/WABinary/constants.js +9 -11
  318. package/lib/WABinary/constants.js.map +1 -0
  319. package/lib/WABinary/decode.d.ts +7 -0
  320. package/lib/WABinary/decode.d.ts.map +1 -0
  321. package/lib/WABinary/decode.js +49 -52
  322. package/lib/WABinary/decode.js.map +1 -0
  323. package/lib/WABinary/encode.d.ts +3 -0
  324. package/lib/WABinary/encode.d.ts.map +1 -0
  325. package/lib/WABinary/encode.js +19 -49
  326. package/lib/WABinary/encode.js.map +1 -0
  327. package/lib/WABinary/generic-utils.d.ts +15 -0
  328. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  329. package/lib/WABinary/generic-utils.js +61 -43
  330. package/lib/WABinary/generic-utils.js.map +1 -0
  331. package/lib/WABinary/index.d.ts +6 -0
  332. package/lib/WABinary/index.d.ts.map +1 -0
  333. package/lib/WABinary/index.js +7 -21
  334. package/lib/WABinary/index.js.map +1 -0
  335. package/lib/WABinary/jid-utils.d.ts +48 -0
  336. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  337. package/lib/WABinary/jid-utils.js +73 -60
  338. package/lib/WABinary/jid-utils.js.map +1 -0
  339. package/lib/WABinary/types.d.ts +19 -0
  340. package/lib/WABinary/types.d.ts.map +1 -0
  341. package/lib/WABinary/types.js +2 -2
  342. package/lib/WABinary/types.js.map +1 -0
  343. package/lib/WAM/BinaryInfo.d.ts +9 -0
  344. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  345. package/lib/WAM/BinaryInfo.js +2 -5
  346. package/lib/WAM/BinaryInfo.js.map +1 -0
  347. package/lib/WAM/constants.d.ts +40 -0
  348. package/lib/WAM/constants.d.ts.map +1 -0
  349. package/lib/WAM/constants.js +19071 -11568
  350. package/lib/WAM/constants.js.map +1 -0
  351. package/lib/WAM/encode.d.ts +3 -0
  352. package/lib/WAM/encode.d.ts.map +1 -0
  353. package/lib/WAM/encode.js +17 -22
  354. package/lib/WAM/encode.js.map +1 -0
  355. package/lib/WAM/index.d.ts +4 -0
  356. package/lib/WAM/index.d.ts.map +1 -0
  357. package/lib/WAM/index.js +4 -19
  358. package/lib/WAM/index.js.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  360. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  362. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  364. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  366. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  368. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +8 -11
  370. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  372. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  373. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  374. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  378. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  381. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  382. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  383. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  384. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  385. package/lib/WAUSync/Protocols/index.js +6 -20
  386. package/lib/WAUSync/Protocols/index.js.map +1 -0
  387. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  388. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  389. package/lib/WAUSync/USyncQuery.js +40 -35
  390. package/lib/WAUSync/USyncQuery.js.map +1 -0
  391. package/lib/WAUSync/USyncUser.d.ts +13 -0
  392. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  393. package/lib/WAUSync/USyncUser.js +2 -5
  394. package/lib/WAUSync/USyncUser.js.map +1 -0
  395. package/lib/WAUSync/index.d.ts +4 -0
  396. package/lib/WAUSync/index.d.ts.map +1 -0
  397. package/lib/WAUSync/index.js +4 -19
  398. package/lib/WAUSync/index.js.map +1 -0
  399. package/lib/index.d.ts +12 -0
  400. package/lib/index.d.ts.map +1 -0
  401. package/lib/index.js +30 -61
  402. package/lib/index.js.map +1 -0
  403. package/package.json +57 -79
  404. package/WAProto/p.html +0 -1
  405. package/lib/Defaults/rimuru-version.json +0 -3
  406. package/lib/Signal/Group/queue-job.js +0 -57
  407. package/lib/Utils/rimuru-event-stream.js +0 -63
@@ -1,46 +1,57 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeMessagesSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const crypto_1 = require("crypto");
10
- const WAProto_1 = require("../../WAProto");
11
- const Defaults_1 = require("../Defaults");
12
- const Utils_1 = require("../Utils");
13
- const link_preview_1 = require("../Utils/link-preview");
14
- const WABinary_1 = require("../WABinary");
15
- const WAUSync_1 = require("../WAUSync");
16
- const newsletter_1 = require("./newsletter");
17
- const makeMessagesSocket = (config) => {
18
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, albumMessageItemDelayMs = 0, } = config;
19
- const sock = (0, newsletter_1.makeNewsletterSocket)(config);
20
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
21
- const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
22
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
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 { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, prepareWAMessageMedia, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
9
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
10
+ import { areJidsSameUser, getBinaryFilteredBizBot, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isJidUser, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET, STORIES_JID } from '../WABinary/index.js';
11
+ import { delay } from '../Utils/generics.js';
12
+
13
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
+ import { makeNewsletterSocket } from './newsletter.js';
15
+ // Inline helper — no external import needed
16
+ const _isNewsletterJid = (jid) => typeof jid === 'string' && jid.endsWith('@newsletter');
17
+
18
+ export const makeMessagesSocket = (config) => {
19
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
20
+ const sock = makeNewsletterSocket(config);
21
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
22
+ const userDevicesCache = config.userDevicesCache ||
23
+ new NodeCache({
24
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
25
+ useClones: false
26
+ });
27
+ const peerSessionsCache = new NodeCache({
28
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
23
29
  useClones: false
24
30
  });
31
+ // Initialize message retry manager if enabled
32
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
+ // Prevent race conditions in Signal session encryption by user
34
+ const encryptionMutex = makeKeyedMutex();
25
35
  let mediaConn;
26
36
  const refreshMediaConn = async (forceGet = false) => {
27
37
  const media = await mediaConn;
28
- if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
38
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
29
39
  mediaConn = (async () => {
30
40
  const result = await query({
31
41
  tag: 'iq',
32
42
  attrs: {
33
43
  type: 'set',
34
44
  xmlns: 'w:m',
35
- to: WABinary_1.S_WHATSAPP_NET,
45
+ to: S_WHATSAPP_NET
36
46
  },
37
47
  content: [{ tag: 'media_conn', attrs: {} }]
38
48
  });
39
- const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
49
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
50
+ // TODO: explore full length of data that whatsapp provides
40
51
  const node = {
41
- hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
52
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
42
53
  hostname: attrs.hostname,
43
- maxContentLengthBytes: +attrs.maxContentLengthBytes,
54
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
44
55
  })),
45
56
  auth: mediaConnNode.attrs.auth,
46
57
  ttl: +mediaConnNode.attrs.ttl,
@@ -57,17 +68,20 @@ const makeMessagesSocket = (config) => {
57
68
  * used for receipts of phone call, read, delivery etc.
58
69
  * */
59
70
  const sendReceipt = async (jid, participant, messageIds, type) => {
71
+ if (!messageIds || messageIds.length === 0) {
72
+ throw new Boom('missing ids in receipt');
73
+ }
60
74
  const node = {
61
75
  tag: 'receipt',
62
76
  attrs: {
63
- id: messageIds[0],
64
- },
77
+ id: messageIds[0]
78
+ }
65
79
  };
66
80
  const isReadReceipt = type === 'read' || type === 'read-self';
67
81
  if (isReadReceipt) {
68
- node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
82
+ node.attrs.t = unixTimestampSeconds().toString();
69
83
  }
70
- if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
84
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
71
85
  node.attrs.recipient = jid;
72
86
  node.attrs.to = participant;
73
87
  }
@@ -78,7 +92,7 @@ const makeMessagesSocket = (config) => {
78
92
  }
79
93
  }
80
94
  if (type) {
81
- node.attrs.type = (0, WABinary_1.isJidNewsletter)(jid) ? 'read-self' : type;
95
+ node.attrs.type = type;
82
96
  }
83
97
  const remainingMessageIds = messageIds.slice(1);
84
98
  if (remainingMessageIds.length) {
@@ -98,7 +112,7 @@ const makeMessagesSocket = (config) => {
98
112
  };
99
113
  /** Correctly bulk send receipts to multiple chats, participants */
100
114
  const sendReceipts = async (keys, type) => {
101
- const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
115
+ const recps = aggregateMessageKeysNotFromMe(keys);
102
116
  for (const { jid, participant, messageIds } of recps) {
103
117
  await sendReceipt(jid, participant, messageIds, type);
104
118
  }
@@ -112,20 +126,44 @@ const makeMessagesSocket = (config) => {
112
126
  };
113
127
  /** Fetch all the devices we've to send a message to */
114
128
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
115
- var _a;
116
129
  const deviceResults = [];
117
130
  if (!useCache) {
118
131
  logger.debug('not using cache for devices');
119
132
  }
120
133
  const toFetch = [];
121
- jids = Array.from(new Set(jids));
122
- for (let jid of jids) {
123
- const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
124
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
134
+ const jidsWithUser = jids
135
+ .map(jid => {
136
+ const decoded = jidDecode(jid);
137
+ const user = decoded?.user;
138
+ const device = decoded?.device;
139
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
140
+ if (isExplicitDevice && user) {
141
+ deviceResults.push({
142
+ user,
143
+ device,
144
+ jid
145
+ });
146
+ return null;
147
+ }
148
+ jid = jidNormalizedUser(jid);
149
+ return { jid, user };
150
+ })
151
+ .filter(jid => jid !== null);
152
+ let mgetDevices;
153
+ if (useCache && userDevicesCache.mget) {
154
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
155
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
156
+ }
157
+ for (const { jid, user } of jidsWithUser) {
125
158
  if (useCache) {
126
- const devices = userDevicesCache.get(user);
159
+ const devices = mgetDevices?.[user] ||
160
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
127
161
  if (devices) {
128
- deviceResults.push(...devices);
162
+ const devicesWithJid = devices.map(d => ({
163
+ ...d,
164
+ jid: jidEncode(d.user, d.server, d.device)
165
+ }));
166
+ deviceResults.push(...devicesWithJid);
129
167
  logger.trace({ user }, 'using cache for devices');
130
168
  }
131
169
  else {
@@ -139,143 +177,283 @@ const makeMessagesSocket = (config) => {
139
177
  if (!toFetch.length) {
140
178
  return deviceResults;
141
179
  }
142
- const query = new WAUSync_1.USyncQuery()
143
- .withContext('message')
144
- .withDeviceProtocol();
180
+ const requestedLidUsers = new Set();
145
181
  for (const jid of toFetch) {
146
- query.withUser(new WAUSync_1.USyncUser().withId(jid));
182
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
183
+ const user = jidDecode(jid)?.user;
184
+ if (user)
185
+ requestedLidUsers.add(user);
186
+ }
187
+ }
188
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
189
+ for (const jid of toFetch) {
190
+ 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
147
191
  }
148
192
  const result = await sock.executeUSyncQuery(query);
149
193
  if (result) {
150
- const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
194
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
195
+ const lidResults = result.list.filter(a => !!a.lid);
196
+ if (lidResults.length > 0) {
197
+ logger.trace('Storing LID maps from device call');
198
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
199
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
200
+ try {
201
+ const lids = lidResults.map(a => a.lid);
202
+ if (lids.length) {
203
+ await assertSessions(lids, true);
204
+ }
205
+ }
206
+ catch (e) {
207
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
208
+ }
209
+ }
210
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
151
211
  const deviceMap = {};
152
212
  for (const item of extracted) {
153
213
  deviceMap[item.user] = deviceMap[item.user] || [];
154
- deviceMap[item.user].push(item);
155
- deviceResults.push(item);
214
+ deviceMap[item.user]?.push(item);
215
+ }
216
+ // Process each user's devices as a group for bulk LID migration
217
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
218
+ const isLidUser = requestedLidUsers.has(user);
219
+ // Process all devices for this user
220
+ for (const item of userDevices) {
221
+ const finalJid = isLidUser
222
+ ? jidEncode(user, item.server, item.device)
223
+ : jidEncode(item.user, item.server, item.device);
224
+ deviceResults.push({
225
+ ...item,
226
+ jid: finalJid
227
+ });
228
+ logger.debug({
229
+ user: item.user,
230
+ device: item.device,
231
+ finalJid,
232
+ usedLid: isLidUser
233
+ }, 'Processed device with LID priority');
234
+ }
235
+ }
236
+ if (userDevicesCache.mset) {
237
+ // if the cache supports mset, we can set all devices in one go
238
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
239
+ }
240
+ else {
241
+ for (const key in deviceMap) {
242
+ if (deviceMap[key])
243
+ await userDevicesCache.set(key, deviceMap[key]);
244
+ }
245
+ }
246
+ const userDeviceUpdates = {};
247
+ for (const [userId, devices] of Object.entries(deviceMap)) {
248
+ if (devices && devices.length > 0) {
249
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
250
+ }
156
251
  }
157
- for (const key in deviceMap) {
158
- userDevicesCache.set(key, deviceMap[key]);
252
+ if (Object.keys(userDeviceUpdates).length > 0) {
253
+ try {
254
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
255
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
256
+ }
257
+ catch (error) {
258
+ logger.warn({ error }, 'failed to store user device lists');
259
+ }
159
260
  }
160
261
  }
161
262
  return deviceResults;
162
263
  };
264
+ /**
265
+ * Update Member Label
266
+ */
267
+ const updateMemberLabel = (jid, memberLabel) => {
268
+ return relayMessage(jid, {
269
+ protocolMessage: {
270
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
271
+ memberLabel: {
272
+ label: memberLabel?.slice(0, 30),
273
+ labelTimestamp: unixTimestampSeconds()
274
+ }
275
+ }
276
+ }, {
277
+ additionalNodes: [
278
+ {
279
+ tag: 'meta',
280
+ attrs: {
281
+ tag_reason: 'user_update',
282
+ appdata: 'member_tag'
283
+ },
284
+ content: undefined
285
+ }
286
+ ]
287
+ });
288
+ };
163
289
  const assertSessions = async (jids, force) => {
164
290
  let didFetchNewSession = false;
165
- let jidsRequiringFetch = [];
166
- if (force) {
167
- jidsRequiringFetch = jids;
168
- }
169
- else {
170
- const addrs = jids.map(jid => (signalRepository
171
- .jidToSignalProtocolAddress(jid)));
172
- const sessions = await authState.keys.get('session', addrs);
173
- for (const jid of jids) {
174
- const signalId = signalRepository
175
- .jidToSignalProtocolAddress(jid);
176
- if (!sessions[signalId]) {
177
- jidsRequiringFetch.push(jid);
291
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
292
+ const jidsRequiringFetch = [];
293
+ logger.debug({ jids }, 'assertSessions call with jids');
294
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
295
+ for (const jid of uniqueJids) {
296
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
297
+ const cachedSession = peerSessionsCache.get(signalId);
298
+ if (cachedSession !== undefined) {
299
+ if (cachedSession && !force) {
300
+ continue; // Session exists in cache
301
+ }
302
+ }
303
+ else {
304
+ const sessionValidation = await signalRepository.validateSession(jid);
305
+ const hasSession = sessionValidation.exists;
306
+ peerSessionsCache.set(signalId, hasSession);
307
+ if (hasSession && !force) {
308
+ continue;
178
309
  }
179
310
  }
311
+ jidsRequiringFetch.push(jid);
180
312
  }
181
313
  if (jidsRequiringFetch.length) {
182
- logger.debug({ jidsRequiringFetch }, 'fetching sessions');
314
+ // LID if mapped, otherwise original
315
+ const wireJids = [
316
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
317
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
318
+ ];
319
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
183
320
  const result = await query({
184
321
  tag: 'iq',
185
322
  attrs: {
186
323
  xmlns: 'encrypt',
187
324
  type: 'get',
188
- to: WABinary_1.S_WHATSAPP_NET,
325
+ to: S_WHATSAPP_NET
189
326
  },
190
327
  content: [
191
328
  {
192
329
  tag: 'key',
193
330
  attrs: {},
194
- content: jidsRequiringFetch.map(jid => ({
195
- tag: 'user',
196
- attrs: { jid },
197
- }))
331
+ content: wireJids.map(jid => {
332
+ const attrs = { jid };
333
+ if (force)
334
+ attrs.reason = 'identity';
335
+ return { tag: 'user', attrs };
336
+ })
198
337
  }
199
338
  ]
200
339
  });
201
- await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
340
+ await parseAndInjectE2ESessions(result, signalRepository);
202
341
  didFetchNewSession = true;
342
+ // Cache fetched sessions using wire JIDs
343
+ for (const wireJid of wireJids) {
344
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
345
+ peerSessionsCache.set(signalId, true);
346
+ }
203
347
  }
204
348
  return didFetchNewSession;
205
349
  };
206
350
  const sendPeerDataOperationMessage = async (pdoMessage) => {
207
- var _a;
208
351
  //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
209
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
210
- throw new boom_1.Boom('Not authenticated');
352
+ if (!authState.creds.me?.id) {
353
+ throw new Boom('Not authenticated');
211
354
  }
212
355
  const protocolMessage = {
213
356
  protocolMessage: {
214
357
  peerDataOperationRequestMessage: pdoMessage,
215
- type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
358
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
216
359
  }
217
360
  };
218
- const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
361
+ const meJid = jidNormalizedUser(authState.creds.me.id);
219
362
  const msgId = await relayMessage(meJid, protocolMessage, {
220
363
  additionalAttributes: {
221
364
  category: 'peer',
222
- // eslint-disable-next-line camelcase
223
- push_priority: 'high_force',
365
+ push_priority: 'high_force'
224
366
  },
367
+ additionalNodes: [
368
+ {
369
+ tag: 'meta',
370
+ attrs: { appdata: 'default' }
371
+ }
372
+ ]
225
373
  });
226
374
  return msgId;
227
375
  };
228
- const createParticipantNodes = async (jids, message, extraAttrs) => {
229
- let patched = await patchMessageBeforeSending(message, jids);
230
- if (!Array.isArray(patched)) {
231
- patched = jids ? jids.map(jid => ({ recipientJid: jid, ...patched })) : [patched];
376
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
377
+ if (!recipientJids.length) {
378
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
232
379
  }
380
+ const patched = await patchMessageBeforeSending(message, recipientJids);
381
+ const patchedMessages = Array.isArray(patched)
382
+ ? patched
383
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
233
384
  let shouldIncludeDeviceIdentity = false;
234
- const nodes = await Promise.all(patched.map(async (patchedMessageWithJid) => {
235
- const { recipientJid: jid, ...patchedMessage } = patchedMessageWithJid;
236
- if (!jid) {
237
- return {};
238
- }
239
- const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
240
- const { type, ciphertext } = await signalRepository
241
- .encryptMessage({ jid, data: bytes });
242
- if (type === 'pkmsg') {
243
- shouldIncludeDeviceIdentity = true;
244
- }
245
- const node = {
246
- tag: 'to',
247
- attrs: { jid },
248
- content: [{
249
- tag: 'enc',
250
- attrs: {
251
- v: '2',
252
- type,
253
- ...extraAttrs || {}
254
- },
255
- content: ciphertext
256
- }]
257
- };
258
- return node;
259
- }));
385
+ const meId = authState.creds.me.id;
386
+ const meLid = authState.creds.me?.lid;
387
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
388
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
389
+ try {
390
+ if (!jid)
391
+ return null;
392
+ let msgToEncrypt = patchedMessage;
393
+ if (dsmMessage) {
394
+ const { user: targetUser } = jidDecode(jid);
395
+ const { user: ownPnUser } = jidDecode(meId);
396
+ const ownLidUser = meLidUser;
397
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
398
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
399
+ if (isOwnUser && !isExactSenderDevice) {
400
+ msgToEncrypt = dsmMessage;
401
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
402
+ }
403
+ }
404
+ const bytes = encodeWAMessage(msgToEncrypt);
405
+ const mutexKey = jid;
406
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
407
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
408
+ if (type === 'pkmsg') {
409
+ shouldIncludeDeviceIdentity = true;
410
+ }
411
+ return {
412
+ tag: 'to',
413
+ attrs: { jid },
414
+ content: [
415
+ {
416
+ tag: 'enc',
417
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
418
+ content: ciphertext
419
+ }
420
+ ]
421
+ };
422
+ });
423
+ return node;
424
+ }
425
+ catch (err) {
426
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
427
+ return null;
428
+ }
429
+ });
430
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
431
+ if (recipientJids.length > 0 && nodes.length === 0) {
432
+ throw new Boom('All encryptions failed', { statusCode: 500 });
433
+ }
260
434
  return { nodes, shouldIncludeDeviceIdentity };
261
435
  };
262
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
263
- var _a;
436
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
264
437
  const meId = authState.creds.me.id;
265
- let shouldIncludeDeviceIdentity = false;
266
- const { user, server } = (0, WABinary_1.jidDecode)(jid);
438
+ const meLid = authState.creds.me?.lid;
439
+ const isRetryResend = Boolean(participant?.jid);
440
+ let shouldIncludeDeviceIdentity = isRetryResend;
267
441
  const statusJid = 'status@broadcast';
442
+ const { user, server } = jidDecode(jid);
268
443
  const isGroup = server === 'g.us';
269
- const isNewsletter = server === 'newsletter';
270
444
  const isStatus = jid === statusJid;
271
445
  const isLid = server === 'lid';
272
- msgId = msgId || (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id);
446
+ const isNewsletter = server === 'newsletter';
447
+ const isGroupOrStatus = isGroup || isStatus;
448
+ const finalJid = jid;
449
+ msgId = msgId || generateMessageIDV2(meId);
273
450
  useUserDevicesCache = useUserDevicesCache !== false;
274
451
  useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
275
452
  const participants = [];
276
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
453
+ const destinationJid = !isStatus ? finalJid : statusJid;
277
454
  const binaryNodeContent = [];
278
455
  const devices = [];
456
+ let reportingMessage;
279
457
  const meMsg = {
280
458
  deviceSentMessage: {
281
459
  destinationJid,
@@ -285,161 +463,462 @@ const makeMessagesSocket = (config) => {
285
463
  };
286
464
  const extraAttrs = {};
287
465
  if (participant) {
288
- // when the retry request is not for a group
289
- // only send to the specific device that asked for a retry
290
- // otherwise the message is sent out to every device that should be a recipient
291
466
  if (!isGroup && !isStatus) {
292
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
467
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
293
468
  }
294
- const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
295
- devices.push({ user, device });
469
+ const { user, device } = jidDecode(participant.jid);
470
+ devices.push({
471
+ user,
472
+ device,
473
+ jid: participant.jid
474
+ });
296
475
  }
297
476
  await authState.keys.transaction(async () => {
298
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
299
477
  const mediaType = getMediaType(message);
300
478
  if (mediaType) {
301
479
  extraAttrs['mediatype'] = mediaType;
302
480
  }
303
- if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
304
- extraAttrs['decrypt-fail'] = 'hide';
481
+ if (isNewsletter) {
482
+ // Handle edit
483
+ if (message.protocolMessage?.editedMessage) {
484
+ msgId = message.protocolMessage.key?.id;
485
+ message = message.protocolMessage.editedMessage;
486
+ }
487
+ // Handle delete/revoke
488
+ if (message.protocolMessage?.type === proto.Message.ProtocolMessage.Type.REVOKE) {
489
+ msgId = message.protocolMessage.key?.id;
490
+ message = {};
491
+ }
492
+ // ── Newsletter Button Compatibility Patch ──────────────────────
493
+ // interactiveMessage (quick_reply / single_select / cta_url) bisa
494
+ // dikirim ke newsletter langsung — WA menerima via proto encoding.
495
+ // listMessage & buttonsMessage dikonversi ke interactiveMessage
496
+ // supaya konsisten dengan cara bot menulis pesan.
497
+ // ──────────────────────────────────────────────────────────────
498
+ if (message.listMessage) {
499
+ const list = message.listMessage;
500
+ message = {
501
+ interactiveMessage: {
502
+ nativeFlowMessage: {
503
+ buttons: [{
504
+ name: 'single_select',
505
+ buttonParamsJson: JSON.stringify({
506
+ title: list.buttonText || 'Select',
507
+ sections: (list.sections || []).map(sec => ({
508
+ title: sec.title || '',
509
+ highlight_label: '',
510
+ rows: (sec.rows || []).map(row => ({
511
+ header: '',
512
+ title: row.title || '',
513
+ description: row.description || '',
514
+ id: row.rowId || row.id || ''
515
+ }))
516
+ }))
517
+ })
518
+ }],
519
+ messageParamsJson: '',
520
+ messageVersion: 1
521
+ },
522
+ body: { text: list.description || '' },
523
+ ...(list.footerText ? { footer: { text: list.footerText } } : {}),
524
+ ...(list.title ? { header: { title: list.title, hasMediaAttachment: false, subtitle: '' } } : {})
525
+ }
526
+ };
527
+ }
528
+ else if (message.buttonsMessage) {
529
+ const bMsg = message.buttonsMessage;
530
+ message = {
531
+ interactiveMessage: {
532
+ nativeFlowMessage: {
533
+ buttons: (bMsg.buttons || []).map(btn => ({
534
+ name: 'quick_reply',
535
+ buttonParamsJson: JSON.stringify({
536
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
537
+ id: btn.buttonId || btn.buttonText?.displayText || ''
538
+ })
539
+ })),
540
+ messageParamsJson: '',
541
+ messageVersion: 1
542
+ },
543
+ body: { text: bMsg.contentText || bMsg.text || '' },
544
+ ...(bMsg.footerText ? { footer: { text: bMsg.footerText } } : {}),
545
+ }
546
+ };
547
+ }
548
+ // ── End Newsletter Button Compatibility Patch ──────────────────
549
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
550
+ if (Array.isArray(patched)) {
551
+ throw new Error('Per-jid patching is not supported in channel');
552
+ }
553
+ const bytes = encodeNewsletterMessage(patched);
554
+ // Set mediatype for interactive messages
555
+ if (patched.interactiveMessage && !extraAttrs['mediatype']) {
556
+ extraAttrs['mediatype'] = 'interactive';
557
+ }
558
+ // extraAttrs already has mediatype set above if media message
559
+ binaryNodeContent.push({
560
+ tag: 'plaintext',
561
+ attrs: extraAttrs,
562
+ content: bytes
563
+ });
564
+ logger.debug({ msgId, extraAttrs }, `sending newsletter message to ${jid}`);
565
+ const stanza = {
566
+ tag: 'message',
567
+ attrs: {
568
+ to: jid,
569
+ id: msgId,
570
+ type: getMessageType(message),
571
+ ...(additionalAttributes || {})
572
+ },
573
+ content: binaryNodeContent
574
+ };
575
+ await sendNode(stanza);
576
+ return;
577
+ }
578
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
579
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
305
580
  }
306
- if (isGroup || isStatus) {
581
+ if (isGroupOrStatus && !isRetryResend) {
307
582
  const [groupData, senderKeyMap] = await Promise.all([
308
583
  (async () => {
309
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
310
- if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
584
+ 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?
585
+ if (groupData && Array.isArray(groupData?.participants)) {
311
586
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
312
587
  }
313
588
  else if (!isStatus) {
314
- groupData = await groupMetadata(jid);
589
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
315
590
  }
316
591
  return groupData;
317
592
  })(),
318
593
  (async () => {
319
594
  if (!participant && !isStatus) {
320
- const result = await authState.keys.get('sender-key-memory', [jid]);
595
+ // what if sender memory is less accurate than the cached metadata
596
+ // on participant change in group, we should do sender memory manipulation
597
+ 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?
321
598
  return result[jid] || {};
322
599
  }
323
600
  return {};
324
601
  })()
325
602
  ]);
326
- if (!participant) {
327
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
328
- if (isStatus && statusJidList) {
329
- participantsList.push(...statusJidList);
330
- }
331
- if (!isStatus) {
332
- additionalAttributes = {
333
- ...additionalAttributes,
334
- // eslint-disable-next-line camelcase
335
- addressing_mode: (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) || 'pn'
603
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
604
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
605
+ additionalAttributes = {
606
+ ...additionalAttributes,
607
+ expiration: groupData.ephemeralDuration.toString()
608
+ };
609
+ }
610
+ if (isStatus && statusJidList) {
611
+ participantsList.push(...statusJidList);
612
+ }
613
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
614
+ devices.push(...additionalDevices);
615
+ if (isGroup) {
616
+ additionalAttributes = {
617
+ ...additionalAttributes,
618
+ addressing_mode: groupData?.addressingMode || 'lid'
619
+ };
620
+ }
621
+ // Ensure groupStatusMessageV2 always has messageContextInfo.messageSecret
622
+ if (message?.groupStatusMessageV2 && !message?.messageContextInfo?.messageSecret) {
623
+ const { randomBytes } = await import('node:crypto');
624
+ message = {
625
+ ...message,
626
+ messageContextInfo: {
627
+ ...(message.messageContextInfo || {}),
628
+ messageSecret: randomBytes(32)
629
+ },
630
+ groupStatusMessageV2: {
631
+ ...message.groupStatusMessageV2,
632
+ message: {
633
+ ...(message.groupStatusMessageV2.message || {}),
634
+ messageContextInfo: {
635
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
636
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
637
+ }
638
+ }
639
+ }
640
+ };
641
+ }
642
+ // ── Group Interactive Message Compatibility Patch ──────────────
643
+ // WhatsApp groups do NOT render listMessage, buttonsMessage, or
644
+ // templateMessage natively in MD protocol. All must be converted
645
+ // to interactiveMessage with nativeFlowMessage so they display
646
+ // and are interactive in group chats.
647
+ // ──────────────────────────────────────────────────────────────
648
+
649
+ // 1. listMessage → interactiveMessage single_select
650
+ if (message.listMessage) {
651
+ const list = message.listMessage;
652
+ const interactiveMessage = {
653
+ nativeFlowMessage: {
654
+ buttons: [{
655
+ name: 'single_select',
656
+ buttonParamsJson: JSON.stringify({
657
+ title: list.buttonText || 'Select',
658
+ sections: (list.sections || []).map(section => ({
659
+ title: section.title || '',
660
+ highlight_label: '',
661
+ rows: (section.rows || []).map(row => ({
662
+ header: '',
663
+ title: row.title || '',
664
+ description: row.description || '',
665
+ id: row.rowId || row.id || ''
666
+ }))
667
+ }))
668
+ })
669
+ }],
670
+ messageParamsJson: '',
671
+ messageVersion: 1
672
+ },
673
+ body: { text: list.description || '' },
674
+ footer: list.footerText ? { text: list.footerText } : undefined,
675
+ header: list.title ? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
676
+ contextInfo: list.contextInfo
677
+ };
678
+ message = { interactiveMessage };
679
+ }
680
+
681
+ // 2. buttonsMessage → interactiveMessage nativeFlowMessage quick_reply buttons
682
+ else if (message.buttonsMessage) {
683
+ const bMsg = message.buttonsMessage;
684
+ const buttons = (bMsg.buttons || []).map(btn => ({
685
+ name: 'quick_reply',
686
+ buttonParamsJson: JSON.stringify({
687
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
688
+ id: btn.buttonId || btn.buttonText?.displayText || ''
689
+ })
690
+ }));
691
+ const interactiveMessage = {
692
+ nativeFlowMessage: {
693
+ buttons,
694
+ messageParamsJson: '',
695
+ messageVersion: 1
696
+ },
697
+ body: { text: bMsg.contentText || bMsg.text || '' },
698
+ footer: bMsg.footerText ? { text: bMsg.footerText } : undefined,
699
+ header: bMsg.text
700
+ ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
701
+ : (bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
702
+ ? { hasMediaAttachment: true, ...(bMsg.imageMessage ? { imageMessage: bMsg.imageMessage } : {}), ...(bMsg.videoMessage ? { videoMessage: bMsg.videoMessage } : {}) }
703
+ : undefined),
704
+ contextInfo: bMsg.contextInfo
705
+ };
706
+ message = { interactiveMessage };
707
+ }
708
+
709
+ // 3. templateMessage (hydratedFourRowTemplate) → interactiveMessage nativeFlowMessage
710
+ else if (message.templateMessage) {
711
+ const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate;
712
+ if (tmpl) {
713
+ const hydratedButtons = tmpl.hydratedButtons || [];
714
+ const buttons = hydratedButtons.map(hBtn => {
715
+ if (hBtn.quickReplyButton) {
716
+ return {
717
+ name: 'quick_reply',
718
+ buttonParamsJson: JSON.stringify({
719
+ display_text: hBtn.quickReplyButton.displayText || '',
720
+ id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || ''
721
+ })
722
+ };
723
+ } else if (hBtn.urlButton) {
724
+ return {
725
+ name: 'cta_url',
726
+ buttonParamsJson: JSON.stringify({
727
+ display_text: hBtn.urlButton.displayText || '',
728
+ url: hBtn.urlButton.url || '',
729
+ merchant_url: hBtn.urlButton.url || ''
730
+ })
731
+ };
732
+ } else if (hBtn.callButton) {
733
+ return {
734
+ name: 'cta_call',
735
+ buttonParamsJson: JSON.stringify({
736
+ display_text: hBtn.callButton.displayText || '',
737
+ phone_number: hBtn.callButton.phoneNumber || ''
738
+ })
739
+ };
740
+ }
741
+ return null;
742
+ }).filter(Boolean);
743
+ const interactiveMessage = {
744
+ nativeFlowMessage: {
745
+ buttons,
746
+ messageParamsJson: '',
747
+ messageVersion: 1
748
+ },
749
+ body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
750
+ footer: tmpl.hydratedFooterText ? { text: tmpl.hydratedFooterText } : undefined,
751
+ header: tmpl.hydratedTitleText
752
+ ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
753
+ : (tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
754
+ ? { hasMediaAttachment: true, ...(tmpl.imageMessage ? { imageMessage: tmpl.imageMessage } : {}), ...(tmpl.videoMessage ? { videoMessage: tmpl.videoMessage } : {}) }
755
+ : undefined),
756
+ contextInfo: tmpl.contextInfo
336
757
  };
758
+ message = { interactiveMessage };
337
759
  }
338
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
339
- devices.push(...additionalDevices);
340
760
  }
761
+ // ── End Group Interactive Message Compatibility Patch ──────────
341
762
  const patched = await patchMessageBeforeSending(message);
342
763
  if (Array.isArray(patched)) {
343
- throw new boom_1.Boom('Per-jid patching is not supported in groups');
764
+ throw new Boom('Per-jid patching is not supported in groups');
344
765
  }
345
- const bytes = (0, Utils_1.encodeWAMessage)(patched);
766
+ const bytes = encodeWAMessage(patched);
767
+ reportingMessage = patched;
768
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
769
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
346
770
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
347
771
  group: destinationJid,
348
772
  data: bytes,
349
- meId,
773
+ meId: groupSenderIdentity
350
774
  });
351
- const senderKeyJids = [];
352
- // ensure a connection is established with every device
353
- for (const { user, device } of devices) {
354
- const jid = (0, WABinary_1.jidEncode)(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
355
- if (!senderKeyMap[jid] || !!participant) {
356
- senderKeyJids.push(jid);
357
- // store that this person has had the sender keys sent to them
358
- senderKeyMap[jid] = true;
775
+ const senderKeyRecipients = [];
776
+ for (const device of devices) {
777
+ const deviceJid = device.jid;
778
+ const hasKey = !!senderKeyMap[deviceJid];
779
+ if ((!hasKey || !!participant) &&
780
+ !isHostedLidUser(deviceJid) &&
781
+ !isHostedPnUser(deviceJid) &&
782
+ device.device !== 99) {
783
+ //todo: revamp all this logic
784
+ // 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
785
+ senderKeyRecipients.push(deviceJid);
786
+ senderKeyMap[deviceJid] = true;
359
787
  }
360
788
  }
361
- // if there are some participants with whom the session has not been established
362
- // if there are, we re-send the senderkey
363
- if (senderKeyJids.length) {
364
- logger.debug({ senderKeyJids }, 'sending new sender key');
789
+ if (senderKeyRecipients.length) {
790
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
365
791
  const senderKeyMsg = {
366
792
  senderKeyDistributionMessage: {
367
793
  axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
368
794
  groupId: destinationJid
369
795
  }
370
796
  };
371
- await assertSessions(senderKeyJids, false);
372
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
797
+ const senderKeySessionTargets = senderKeyRecipients;
798
+ await assertSessions(senderKeySessionTargets);
799
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
373
800
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
374
801
  participants.push(...result.nodes);
375
802
  }
376
803
  binaryNodeContent.push({
377
804
  tag: 'enc',
378
- attrs: { v: '2', type: 'skmsg' },
805
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
379
806
  content: ciphertext
380
807
  });
381
808
  await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
382
809
  }
383
- else if (isNewsletter) {
384
- // Message edit
385
- if ((_b = message.protocolMessage) === null || _b === void 0 ? void 0 : _b.editedMessage) {
386
- msgId = (_c = message.protocolMessage.key) === null || _c === void 0 ? void 0 : _c.id;
387
- message = message.protocolMessage.editedMessage;
388
- }
389
- // Message delete
390
- if (((_d = message.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
391
- msgId = (_e = message.protocolMessage.key) === null || _e === void 0 ? void 0 : _e.id;
392
- message = {};
810
+ else {
811
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
812
+ // TODO: investigate if this is true
813
+ let ownId = meId;
814
+ if (isLid && meLid) {
815
+ ownId = meLid;
816
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
393
817
  }
394
- const patched = await patchMessageBeforeSending(message, []);
395
- if (Array.isArray(patched)) {
396
- throw new boom_1.Boom('Per-jid patching is not supported in channel');
818
+ else {
819
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
397
820
  }
398
- const bytes = (0, Utils_1.encodeNewsletterMessage)(patched);
399
- binaryNodeContent.push({
400
- tag: 'plaintext',
401
- attrs: mediaType ? { mediatype: mediaType } : {},
402
- content: bytes
403
- });
404
- }
405
- else {
406
- const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
821
+ const { user: ownUser } = jidDecode(ownId);
407
822
  if (!participant) {
408
- devices.push({ user });
409
- if (user !== meUser) {
410
- devices.push({ user: meUser });
823
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
824
+ reportingMessage = Array.isArray(patchedForReporting)
825
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
826
+ : patchedForReporting;
827
+ }
828
+ if (!isRetryResend) {
829
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
830
+ devices.push({
831
+ user,
832
+ device: 0,
833
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
834
+ });
835
+ if (user !== ownUser) {
836
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
837
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
838
+ devices.push({
839
+ user: ownUserForAddressing,
840
+ device: 0,
841
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
842
+ });
411
843
  }
412
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
413
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
414
- devices.push(...additionalDevices);
844
+ if (additionalAttributes?.['category'] !== 'peer') {
845
+ // Clear placeholders and enumerate actual devices
846
+ devices.length = 0;
847
+ // Use conversation-appropriate sender identity
848
+ const senderIdentity = isLid && meLid
849
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
850
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
851
+ // Enumerate devices for sender and target with consistent addressing
852
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
853
+ devices.push(...sessionDevices);
854
+ logger.debug({
855
+ deviceCount: devices.length,
856
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
857
+ }, 'Device enumeration complete with unified addressing');
415
858
  }
416
859
  }
417
- const allJids = [];
418
- const meJids = [];
419
- const otherJids = [];
420
- for (const { user, device } of devices) {
421
- const isMe = user === meUser;
422
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_g = (_f = authState.creds) === null || _f === void 0 ? void 0 : _f.me) === null || _g === void 0 ? void 0 : _g.lid.split(':')[0]) || user : user, isLid ? 'lid' : 's.whatsapp.net', device);
860
+ const allRecipients = [];
861
+ const meRecipients = [];
862
+ const otherRecipients = [];
863
+ const { user: mePnUser } = jidDecode(meId);
864
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
865
+ for (const { user, jid } of devices) {
866
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
867
+ if (isExactSenderDevice) {
868
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
869
+ continue;
870
+ }
871
+ // Check if this is our device (could match either PN or LID user)
872
+ const isMe = user === mePnUser || user === meLidUser;
423
873
  if (isMe) {
424
- meJids.push(jid);
874
+ meRecipients.push(jid);
425
875
  }
426
876
  else {
427
- otherJids.push(jid);
877
+ otherRecipients.push(jid);
428
878
  }
429
- allJids.push(jid);
879
+ allRecipients.push(jid);
430
880
  }
431
- await assertSessions(allJids, false);
881
+ await assertSessions(allRecipients);
432
882
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
433
- createParticipantNodes(meJids, meMsg, extraAttrs),
434
- createParticipantNodes(otherJids, message, extraAttrs)
883
+ // For own devices: use DSM if available (1:1 chats only)
884
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
885
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
435
886
  ]);
436
887
  participants.push(...meNodes);
437
888
  participants.push(...otherNodes);
889
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
890
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
891
+ }
438
892
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
439
893
  }
894
+ if (isRetryResend) {
895
+ const isParticipantLid = isLidUser(participant.jid);
896
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
897
+ const encodedMessageToSend = isMe
898
+ ? encodeWAMessage({
899
+ deviceSentMessage: {
900
+ destinationJid,
901
+ message
902
+ }
903
+ })
904
+ : encodeWAMessage(message);
905
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
906
+ data: encodedMessageToSend,
907
+ jid: participant.jid
908
+ });
909
+ binaryNodeContent.push({
910
+ tag: 'enc',
911
+ attrs: {
912
+ v: '2',
913
+ type,
914
+ count: participant.count.toString()
915
+ },
916
+ content: encryptedContent
917
+ });
918
+ }
440
919
  if (participants.length) {
441
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
442
- const peerNode = (_j = (_h = participants[0]) === null || _h === void 0 ? void 0 : _h.content) === null || _j === void 0 ? void 0 : _j[0];
920
+ if (additionalAttributes?.['category'] === 'peer') {
921
+ const peerNode = participants[0]?.content?.[0];
443
922
  if (peerNode) {
444
923
  binaryNodeContent.push(peerNode); // push only enc
445
924
  }
@@ -456,7 +935,8 @@ const makeMessagesSocket = (config) => {
456
935
  tag: 'message',
457
936
  attrs: {
458
937
  id: msgId,
459
- type: isNewsletter ? getTypeMessage(message) : 'text',
938
+ to: destinationJid,
939
+ type: getMessageType(message),
460
940
  ...(additionalAttributes || {})
461
941
  },
462
942
  content: binaryNodeContent
@@ -465,11 +945,11 @@ const makeMessagesSocket = (config) => {
465
945
  // ensure the message is only sent to that person
466
946
  // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
467
947
  if (participant) {
468
- if ((0, WABinary_1.isJidGroup)(destinationJid)) {
948
+ if (isJidGroup(destinationJid)) {
469
949
  stanza.attrs.to = destinationJid;
470
950
  stanza.attrs.participant = participant.jid;
471
951
  }
472
- else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
952
+ else if (areJidsSameUser(participant.jid, meId)) {
473
953
  stanza.attrs.to = participant.jid;
474
954
  stanza.attrs.recipient = destinationJid;
475
955
  }
@@ -481,80 +961,100 @@ const makeMessagesSocket = (config) => {
481
961
  stanza.attrs.to = destinationJid;
482
962
  }
483
963
  if (shouldIncludeDeviceIdentity) {
964
+ ;
484
965
  stanza.content.push({
485
966
  tag: 'device-identity',
486
967
  attrs: {},
487
- content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
968
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
488
969
  });
489
970
  logger.debug({ jid }, 'adding device identity');
490
971
  }
491
- if (additionalNodes && additionalNodes.length > 0) {
492
- stanza.content.push(...additionalNodes);
972
+ if (!isNewsletter &&
973
+ !isRetryResend &&
974
+ reportingMessage?.messageContextInfo?.messageSecret &&
975
+ shouldIncludeReportingToken(reportingMessage)) {
976
+ try {
977
+ const encoded = encodeWAMessage(reportingMessage);
978
+ const reportingKey = {
979
+ id: msgId,
980
+ fromMe: true,
981
+ remoteJid: destinationJid,
982
+ participant: participant?.jid
983
+ };
984
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
985
+ if (reportingNode) {
986
+ ;
987
+ stanza.content.push(reportingNode);
988
+ logger.trace({ jid }, 'added reporting token to message');
989
+ }
990
+ }
991
+ catch (error) {
992
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
993
+ }
493
994
  }
494
- const content = (0, Utils_1.normalizeMessageContent)(message);
495
- const contentType = (0, Utils_1.getContentType)(content);
496
- if (((0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidUser)(jid)) && (contentType === 'interactiveMessage' ||
497
- contentType === 'buttonsMessage' ||
498
- contentType === 'listMessage')) {
499
- const bizNode = { tag: 'biz', attrs: {} };
500
- if ((((_l = (_k = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _k === void 0 ? void 0 : _k.message) === null || _l === void 0 ? void 0 : _l.interactiveMessage) || ((_o = (_m = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _m === void 0 ? void 0 : _m.message) === null || _o === void 0 ? void 0 : _o.interactiveMessage) || ((_q = (_p = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _p === void 0 ? void 0 : _p.message) === null || _q === void 0 ? void 0 : _q.interactiveMessage) || (message === null || message === void 0 ? void 0 : message.interactiveMessage)) || (((_s = (_r = message === null || message === void 0 ? void 0 : message.viewOnceMessage) === null || _r === void 0 ? void 0 : _r.message) === null || _s === void 0 ? void 0 : _s.buttonsMessage) || ((_u = (_t = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2) === null || _t === void 0 ? void 0 : _t.message) === null || _u === void 0 ? void 0 : _u.buttonsMessage) || ((_w = (_v = message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension) === null || _v === void 0 ? void 0 : _v.message) === null || _w === void 0 ? void 0 : _w.buttonsMessage) || (message === null || message === void 0 ? void 0 : message.buttonsMessage))) {
501
- bizNode.content = [{
502
- tag: 'interactive',
503
- attrs: {
504
- type: 'native_flow',
505
- v: '1'
506
- },
507
- content: [{
508
- tag: 'native_flow',
509
- attrs: { v: '9', name: 'mixed' }
510
- }]
511
- }];
512
- }
513
- else if (message === null || message === void 0 ? void 0 : message.listMessage) {
514
- // list message only support in private chat
515
- bizNode.content = [{
516
- tag: 'list',
517
- attrs: {
518
- type: 'product_list',
519
- v: '2'
520
- }
521
- }];
995
+ const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {};
996
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
997
+ if (tcTokenBuffer) {
998
+ ;
999
+ stanza.content.push({
1000
+ tag: 'tctoken',
1001
+ attrs: {},
1002
+ content: tcTokenBuffer
1003
+ });
1004
+ }
1005
+ if (AI && !isGroup && !isStatus && !isNewsletter) {
1006
+ const existingBizBot = getBinaryFilteredBizBot(additionalNodes || []);
1007
+ if (existingBizBot) {
1008
+ if (additionalNodes && additionalNodes.length > 0) {
1009
+ stanza.content.push(...additionalNodes);
1010
+ }
1011
+ } else {
1012
+ stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } });
1013
+ if (additionalNodes && additionalNodes.length > 0) {
1014
+ stanza.content.push(...additionalNodes);
1015
+ }
522
1016
  }
523
- stanza.content.push(bizNode);
1017
+ } else if (additionalNodes && additionalNodes.length > 0) {
1018
+ ;
1019
+ stanza.content.push(...additionalNodes);
524
1020
  }
525
1021
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
526
1022
  await sendNode(stanza);
527
- });
1023
+ // Add message to retry cache if enabled
1024
+ if (messageRetryManager && !participant) {
1025
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1026
+ }
1027
+ }, meId);
528
1028
  return msgId;
529
1029
  };
530
- const getTypeMessage = (msg) => {
531
- if (msg.viewOnceMessage) {
532
- return getTypeMessage(msg.viewOnceMessage.message);
533
- }
534
- else if (msg.viewOnceMessageV2) {
535
- return getTypeMessage(msg.viewOnceMessageV2.message);
536
- }
537
- else if (msg.viewOnceMessageV2Extension) {
538
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
539
- }
540
- else if (msg.ephemeralMessage) {
541
- return getTypeMessage(msg.ephemeralMessage.message);
542
- }
543
- else if (msg.documentWithCaptionMessage) {
544
- return getTypeMessage(msg.documentWithCaptionMessage.message);
1030
+ const getMessageType = (message) => {
1031
+ // groupStatusMessageV2 must be checked BEFORE normalizeMessageContent
1032
+ // because normalizeMessageContent will unwrap it into inner message
1033
+ if (message?.groupStatusMessageV2 || message?.groupStatusMessage) {
1034
+ return 'text';
545
1035
  }
546
- else if (msg.reactionMessage) {
1036
+ const normalizedMessage = normalizeMessageContent(message);
1037
+ if (!normalizedMessage)
1038
+ return 'text';
1039
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
547
1040
  return 'reaction';
548
1041
  }
549
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
1042
+ if (normalizedMessage.pollCreationMessage ||
1043
+ normalizedMessage.pollCreationMessageV2 ||
1044
+ normalizedMessage.pollCreationMessageV3 ||
1045
+ normalizedMessage.pollUpdateMessage) {
550
1046
  return 'poll';
551
1047
  }
552
- else if (getMediaType(msg)) {
553
- return 'media';
1048
+ if (normalizedMessage.eventMessage) {
1049
+ return 'event';
554
1050
  }
555
- else {
1051
+ if (normalizedMessage.interactiveMessage) {
556
1052
  return 'text';
557
1053
  }
1054
+ if (getMediaType(normalizedMessage) !== '') {
1055
+ return 'media';
1056
+ }
1057
+ return 'text';
558
1058
  };
559
1059
  const getMediaType = (message) => {
560
1060
  if (message.imageMessage) {
@@ -563,6 +1063,9 @@ const makeMessagesSocket = (config) => {
563
1063
  else if (message.videoMessage) {
564
1064
  return message.videoMessage.gifPlayback ? 'gif' : 'video';
565
1065
  }
1066
+ else if (message.ptvMessage) {
1067
+ return 'video';
1068
+ }
566
1069
  else if (message.audioMessage) {
567
1070
  return message.audioMessage.ptt ? 'ptt' : 'audio';
568
1071
  }
@@ -581,6 +1084,9 @@ const makeMessagesSocket = (config) => {
581
1084
  else if (message.stickerMessage) {
582
1085
  return 'sticker';
583
1086
  }
1087
+ else if (message.stickerPackMessage) {
1088
+ return 'sticker_pack';
1089
+ }
584
1090
  else if (message.listMessage) {
585
1091
  return 'list';
586
1092
  }
@@ -602,13 +1108,14 @@ const makeMessagesSocket = (config) => {
602
1108
  else if (message.groupInviteMessage) {
603
1109
  return 'url';
604
1110
  }
1111
+ return '';
605
1112
  };
606
1113
  const getPrivacyTokens = async (jids) => {
607
- const t = (0, Utils_1.unixTimestampSeconds)().toString();
1114
+ const t = unixTimestampSeconds().toString();
608
1115
  const result = await query({
609
1116
  tag: 'iq',
610
1117
  attrs: {
611
- to: WABinary_1.S_WHATSAPP_NET,
1118
+ to: S_WHATSAPP_NET,
612
1119
  type: 'set',
613
1120
  xmlns: 'privacy'
614
1121
  },
@@ -619,7 +1126,7 @@ const makeMessagesSocket = (config) => {
619
1126
  content: jids.map(jid => ({
620
1127
  tag: 'token',
621
1128
  attrs: {
622
- jid: (0, WABinary_1.jidNormalizedUser)(jid),
1129
+ jid: jidNormalizedUser(jid),
623
1130
  t,
624
1131
  type: 'trusted_contact'
625
1132
  }
@@ -629,8 +1136,66 @@ const makeMessagesSocket = (config) => {
629
1136
  });
630
1137
  return result;
631
1138
  };
632
- const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
633
- const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
1139
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1140
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1141
+ // ── Button type helpers (ported from itsukichan) ──────────────────────────
1142
+ const getButtonType = (message) => {
1143
+ if (message.listMessage) return 'list';
1144
+ if (message.buttonsMessage) return 'buttons';
1145
+ if (message.templateMessage) return 'template';
1146
+ if (message.interactiveMessage?.nativeFlowMessage) return 'native_flow';
1147
+ if (message.interactiveMessage?.shopStorefrontMessage) return 'shop';
1148
+ if (message.interactiveMessage?.collectionMessage) return 'collection';
1149
+ if (message.interactiveMessage?.carouselMessage) return 'carousel';
1150
+ if (message.interactiveMessage) return 'interactive';
1151
+ return null;
1152
+ };
1153
+ const getButtonArgs = (message) => {
1154
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage;
1155
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name;
1156
+ const nativeFlowSpecials = [
1157
+ 'mpm', 'cta_catalog', 'send_location',
1158
+ 'call_permission_request', 'wa_payment_transaction_details',
1159
+ 'automated_greeting_message_view_catalog'
1160
+ ];
1161
+ const ts = unixTimestampSeconds().toString();
1162
+ const bizBase = { actual_actors: '2', host_storage: '2', privacy_mode_ts: ts };
1163
+ const qualityControl = { tag: 'quality_control', attrs: { source_type: 'third_party' } };
1164
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1165
+ return {
1166
+ tag: 'biz',
1167
+ attrs: { native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName }
1168
+ };
1169
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1170
+ return {
1171
+ tag: 'biz', attrs: bizBase,
1172
+ content: [{
1173
+ tag: 'interactive', attrs: { type: 'native_flow', v: '1' },
1174
+ content: [{ tag: 'native_flow', attrs: { v: '2', name: firstButtonName } }]
1175
+ }, qualityControl]
1176
+ };
1177
+ } else if (nativeFlow || message.buttonsMessage || message.templateMessage || message.interactiveMessage) {
1178
+ // All interactive types in groups use native_flow biz node
1179
+ // This covers: nativeFlowMessage, buttonsMessage→interactiveMessage,
1180
+ // templateMessage→interactiveMessage, and direct interactiveMessage
1181
+ return {
1182
+ tag: 'biz', attrs: bizBase,
1183
+ content: [{
1184
+ tag: 'interactive', attrs: { type: 'native_flow', v: '1' },
1185
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
1186
+ }, qualityControl]
1187
+ };
1188
+ } else if (message.listMessage) {
1189
+ // Standalone listMessage (private chat) keeps the list biz node
1190
+ return {
1191
+ tag: 'biz', attrs: bizBase,
1192
+ content: [{ tag: 'list', attrs: { v: '2', type: 'product_list' } }, qualityControl]
1193
+ };
1194
+ } else {
1195
+ return { tag: 'biz', attrs: bizBase };
1196
+ }
1197
+ };
1198
+ // ── End button type helpers ───────────────────────────────────────────────
634
1199
  return {
635
1200
  ...sock,
636
1201
  getPrivacyTokens,
@@ -642,14 +1207,16 @@ const makeMessagesSocket = (config) => {
642
1207
  refreshMediaConn,
643
1208
  waUploadToServer,
644
1209
  fetchPrivacySettings,
645
- getUSyncDevices,
646
- createParticipantNodes,
647
1210
  sendPeerDataOperationMessage,
1211
+ createParticipantNodes,
1212
+ getUSyncDevices,
1213
+ messageRetryManager,
1214
+ updateMemberLabel,
648
1215
  updateMediaMessage: async (message) => {
649
- const content = (0, Utils_1.assertMediaContent)(message.message);
1216
+ const content = assertMediaContent(message.message);
650
1217
  const mediaKey = content.mediaKey;
651
1218
  const meId = authState.creds.me.id;
652
- const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
1219
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
653
1220
  let error = undefined;
654
1221
  await Promise.all([
655
1222
  sendNode(node),
@@ -661,13 +1228,16 @@ const makeMessagesSocket = (config) => {
661
1228
  }
662
1229
  else {
663
1230
  try {
664
- const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
665
- if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
666
- const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
667
- throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
1231
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1232
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1233
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1234
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1235
+ data: media,
1236
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1237
+ });
668
1238
  }
669
1239
  content.directPath = media.directPath;
670
- content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
1240
+ content.url = getUrlFromDirectPath(content.directPath);
671
1241
  logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
672
1242
  }
673
1243
  catch (err) {
@@ -681,189 +1251,380 @@ const makeMessagesSocket = (config) => {
681
1251
  if (error) {
682
1252
  throw error;
683
1253
  }
684
- ev.emit('messages.update', [
685
- { key: message.key, update: { message: message.message } }
686
- ]);
1254
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
687
1255
  return message;
688
1256
  },
689
- sendMessage: async (jid, content, options = {}) => {
690
- var _a, _b, _c;
691
- const userJid = authState.creds.me.id;
692
- if (!options.ephemeralExpiration) {
693
- if ((0, WABinary_1.isJidGroup)(jid)) {
694
- const groups = await sock.groupQuery(jid, 'get', [{
695
- tag: 'query',
696
- attrs: {
697
- request: 'interactive'
698
- }
699
- }]);
700
- const metadata = (0, WABinary_1.getBinaryNodeChild)(groups, 'group');
701
- const expiration = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(metadata, 'ephemeral')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.expiration) || 0;
702
- options.ephemeralExpiration = expiration;
1257
+ resize: async (media, width, height) => {
1258
+ const { getStream, toBuffer } = await import('../Utils/messages-media.js');
1259
+ let sharp;
1260
+ try { sharp = (await import('sharp')).default; } catch (_) {}
1261
+ if (!sharp) throw new Error('sharp is required for resize');
1262
+ const { stream } = await getStream(media);
1263
+ const buf = await toBuffer(stream);
1264
+ return sharp(buf).resize(width, height, { fit: 'cover' }).toBuffer();
1265
+ },
1266
+ sendStatusMentions: async (content, jids = []) => {
1267
+ const userJid = jidNormalizedUser(authState.creds.me.id);
1268
+ let allUsers = new Set();
1269
+ allUsers.add(userJid);
1270
+
1271
+ for (const id of jids) {
1272
+ const isGroup = isJidGroup(id);
1273
+ const isPrivate = isJidUser(id);
1274
+ if (isGroup) {
1275
+ try {
1276
+ const metadata = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1277
+ const participants = metadata.participants.map(p => jidNormalizedUser(p.id));
1278
+ participants.forEach(j => allUsers.add(j));
1279
+ } catch (error) {
1280
+ logger.error(`Error getting metadata for group ${id}: ${error}`);
1281
+ }
1282
+ } else if (isPrivate) {
1283
+ allUsers.add(jidNormalizedUser(id));
703
1284
  }
704
1285
  }
705
- if (typeof content === 'object' &&
706
- 'disappearingMessagesInChat' in content &&
707
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
708
- (0, WABinary_1.isJidGroup)(jid)) {
709
- const { disappearingMessagesInChat } = content;
710
- const value = typeof disappearingMessagesInChat === 'boolean' ?
711
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
712
- disappearingMessagesInChat;
713
- await groupToggleEphemeral(jid, value);
1286
+
1287
+ const uniqueUsers = Array.from(allUsers);
1288
+ const getRandomHexColor = () => '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
1289
+
1290
+ const isMedia = content.image || content.video || content.audio;
1291
+ const isAudio = !!content.audio;
1292
+
1293
+ const messageContent = { ...content };
1294
+
1295
+ if (isMedia && !isAudio) {
1296
+ if (messageContent.text) {
1297
+ messageContent.caption = messageContent.text;
1298
+ delete messageContent.text;
1299
+ }
1300
+ delete messageContent.ptt;
1301
+ delete messageContent.font;
1302
+ delete messageContent.backgroundColor;
1303
+ delete messageContent.textColor;
1304
+ }
1305
+ if (isAudio) {
1306
+ delete messageContent.text;
1307
+ delete messageContent.caption;
1308
+ delete messageContent.font;
1309
+ delete messageContent.textColor;
1310
+ }
1311
+
1312
+ const font = !isMedia ? (content.font ?? Math.floor(Math.random() * 9)) : undefined;
1313
+ const textColor = !isMedia ? (content.textColor ?? getRandomHexColor()) : undefined;
1314
+ const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor ?? getRandomHexColor()) : undefined;
1315
+ const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined;
1316
+
1317
+ let msg;
1318
+ let mediaHandle;
1319
+ try {
1320
+ msg = await generateWAMessage(STORIES_JID, messageContent, {
1321
+ logger,
1322
+ userJid,
1323
+ getUrlInfo: text => getUrlInfo(text, {
1324
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1325
+ fetchOpts: { timeout: 3000 },
1326
+ logger,
1327
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1328
+ }),
1329
+ upload: async (encFilePath, opts) => {
1330
+ const up = await waUploadToServer(encFilePath, { ...opts });
1331
+ mediaHandle = up.handle;
1332
+ return up;
1333
+ },
1334
+ mediaCache: config.mediaCache,
1335
+ options: config.options,
1336
+ font,
1337
+ textColor,
1338
+ backgroundColor,
1339
+ ptt
1340
+ });
1341
+ } catch (error) {
1342
+ logger.error(`Error generating status message: ${error}`);
1343
+ throw error;
714
1344
  }
715
- if (typeof content === 'object' && 'album' in content && content.album) {
716
- const { album, caption } = content;
717
- if (caption && !album[0].caption) {
718
- album[0].caption = caption;
1345
+
1346
+ await relayMessage(STORIES_JID, msg.message, {
1347
+ messageId: msg.key.id,
1348
+ statusJidList: uniqueUsers,
1349
+ additionalNodes: [{
1350
+ tag: 'meta',
1351
+ attrs: {},
1352
+ content: [{
1353
+ tag: 'mentioned_users',
1354
+ attrs: {},
1355
+ content: jids.map(jid => ({
1356
+ tag: 'to',
1357
+ attrs: { jid: jidNormalizedUser(jid) }
1358
+ }))
1359
+ }]
1360
+ }]
1361
+ });
1362
+
1363
+ for (const id of jids) {
1364
+ try {
1365
+ const normalizedId = jidNormalizedUser(id);
1366
+ const isPrivate = isJidUser(normalizedId);
1367
+ const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage';
1368
+ const protocolMessage = {
1369
+ [type]: {
1370
+ message: {
1371
+ protocolMessage: {
1372
+ key: msg.key,
1373
+ type: 25
1374
+ }
1375
+ }
1376
+ },
1377
+ messageContextInfo: {
1378
+ messageSecret: randomBytes(32)
1379
+ }
1380
+ };
1381
+ const statusMsg = await generateWAMessageFromContent(normalizedId, protocolMessage, {});
1382
+ await relayMessage(normalizedId, statusMsg.message, {
1383
+ additionalNodes: [{
1384
+ tag: 'meta',
1385
+ attrs: isPrivate
1386
+ ? { is_status_mention: 'true' }
1387
+ : { is_group_status_mention: 'true' }
1388
+ }]
1389
+ });
1390
+ await delay(2000);
1391
+ } catch (error) {
1392
+ logger.error(`Error sending status mention to ${id}: ${error}`);
719
1393
  }
720
- let mediaHandle;
721
- let mediaMsg;
722
- const albumMsg = (0, Utils_1.generateWAMessageFromContent)(jid, {
723
- albumMessage: {
724
- expectedImageCount: album.filter(item => 'image' in item).length,
725
- expectedVideoCount: album.filter(item => 'video' in item).length
1394
+ }
1395
+
1396
+ return msg;
1397
+ },
1398
+ sendMessage: async (jid, content, options = {}) => {
1399
+ const userJid = authState.creds.me.id;
1400
+ // ── Normalize: buttons[].nativeFlowInfo -> interactiveButtons ──────
1401
+ if (
1402
+ typeof content === 'object' &&
1403
+ Array.isArray(content.buttons) &&
1404
+ content.buttons.length > 0 &&
1405
+ content.buttons.some(b => b.nativeFlowInfo)
1406
+ ) {
1407
+ const interactiveButtons = content.buttons.map(b => {
1408
+ if (b.nativeFlowInfo) {
1409
+ return {
1410
+ name: b.nativeFlowInfo.name,
1411
+ buttonParamsJson: b.nativeFlowInfo.paramsJson || '{}'
1412
+ };
726
1413
  }
727
- }, { userJid, ...options });
728
- await relayMessage(jid, albumMsg.message, {
729
- messageId: albumMsg.key.id
1414
+ return {
1415
+ name: 'quick_reply',
1416
+ buttonParamsJson: JSON.stringify({
1417
+ display_text: b.buttonText?.displayText || b.buttonId || 'Button',
1418
+ id: b.buttonId || b.buttonText?.displayText || 'btn'
1419
+ })
1420
+ };
730
1421
  });
731
- for (const i in album) {
732
- const media = album[i];
733
- if ('image' in media) {
734
- mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
735
- image: media.image,
736
- ...(media.caption ? { caption: media.caption } : {}),
737
- ...options
738
- }, {
739
- userJid,
740
- upload: async (readStream, opts) => {
741
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
742
- mediaHandle = up.handle;
743
- return up;
744
- },
745
- ...options,
746
- });
1422
+ const { buttons, headerType, viewOnce, ...rest } = content;
1423
+ content = { ...rest, interactiveButtons };
1424
+ }
1425
+ // ── Interactive Button (sendButton logic) ──────────────────────────
1426
+ if (typeof content === 'object' && Array.isArray(content.interactiveButtons) && content.interactiveButtons.length > 0) {
1427
+ const {
1428
+ text = '',
1429
+ caption = '',
1430
+ title = '',
1431
+ footer = '',
1432
+ interactiveButtons,
1433
+ hasMediaAttachment = false,
1434
+ image = null,
1435
+ video = null,
1436
+ document = null,
1437
+ mimetype = null,
1438
+ jpegThumbnail = null,
1439
+ location = null,
1440
+ product = null,
1441
+ businessOwnerJid = null,
1442
+ externalAdReply = null,
1443
+ } = content;
1444
+ // Normalize buttons
1445
+ const processedButtons = [];
1446
+ for (let i = 0; i < interactiveButtons.length; i++) {
1447
+ const btn = interactiveButtons[i];
1448
+ if (!btn || typeof btn !== 'object') throw new Error(`interactiveButtons[${i}] must be an object`);
1449
+ if (btn.name && btn.buttonParamsJson) { processedButtons.push(btn); continue; }
1450
+ if (btn.id || btn.text || btn.displayText) {
1451
+ processedButtons.push({ name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.text || btn.displayText || `Button ${i + 1}`, id: btn.id || `quick_${i + 1}` }) });
1452
+ continue;
747
1453
  }
748
- else if ('video' in media) {
749
- mediaMsg = await (0, Utils_1.generateWAMessage)(jid, {
750
- video: media.video,
751
- ...(media.caption ? { caption: media.caption } : {}),
752
- ...(media.gifPlayback !== undefined ? { gifPlayback: media.gifPlayback } : {}),
753
- ...options
754
- }, {
755
- userJid,
756
- upload: async (readStream, opts) => {
757
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
758
- mediaHandle = up.handle;
759
- return up;
760
- },
761
- ...options,
762
- });
1454
+ if (btn.buttonId && btn.buttonText?.displayText) {
1455
+ processedButtons.push({ name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.buttonText.displayText, id: btn.buttonId }) });
1456
+ continue;
763
1457
  }
764
- if (mediaMsg) {
765
- mediaMsg.message.messageContextInfo = {
766
- messageSecret: (0, crypto_1.randomBytes)(32),
767
- messageAssociation: {
768
- associationType: 1,
769
- parentMessageKey: albumMsg.key
770
- }
771
- };
1458
+ throw new Error(`interactiveButtons[${i}] has invalid shape`);
1459
+ }
1460
+ let messageContent = {};
1461
+ // Header
1462
+ if (image) {
1463
+ const mi = Buffer.isBuffer(image) ? { image } : { image: { url: typeof image === 'object' ? image.url : image } };
1464
+ const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1465
+ messageContent.header = { title: title || '', hasMediaAttachment: true, imageMessage: pm.imageMessage };
1466
+ } else if (video) {
1467
+ const mi = Buffer.isBuffer(video) ? { video } : { video: { url: typeof video === 'object' ? video.url : video } };
1468
+ const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1469
+ messageContent.header = { title: title || '', hasMediaAttachment: true, videoMessage: pm.videoMessage };
1470
+ } else if (document) {
1471
+ const mi = Buffer.isBuffer(document) ? { document } : { document: { url: typeof document === 'object' ? document.url : document } };
1472
+ if (mimetype && typeof mi.document === 'object') mi.document.mimetype = mimetype;
1473
+ if (jpegThumbnail) {
1474
+ const thumb = Buffer.isBuffer(jpegThumbnail) ? jpegThumbnail : await (async () => { try { const r = await fetch(jpegThumbnail); return Buffer.from(await r.arrayBuffer()); } catch { return undefined; } })();
1475
+ if (thumb) mi.document.jpegThumbnail = thumb;
772
1476
  }
773
- await relayMessage(jid, mediaMsg.message, {
774
- messageId: mediaMsg.key.id
775
- });
776
- if (albumMessageItemDelayMs > 0) {
777
- await new Promise(resolve => setTimeout(resolve, albumMessageItemDelayMs));
1477
+ const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1478
+ messageContent.header = { title: title || '', hasMediaAttachment: true, documentMessage: pm.documentMessage };
1479
+ } else if (location && typeof location === 'object') {
1480
+ messageContent.header = { title: title || location.name || 'Location', hasMediaAttachment: false, locationMessage: { degreesLatitude: location.degreesLatitude || location.degressLatitude || 0, degreesLongitude: location.degreesLongitude || location.degressLongitude || 0, name: location.name || '', address: location.address || '' } };
1481
+ } else if (product && typeof product === 'object') {
1482
+ let productImageMessage = null;
1483
+ if (product.productImage) {
1484
+ const mi = Buffer.isBuffer(product.productImage) ? { image: product.productImage } : { image: { url: typeof product.productImage === 'object' ? product.productImage.url : product.productImage } };
1485
+ const pm = await prepareWAMessageMedia(mi, { upload: waUploadToServer });
1486
+ productImageMessage = pm.imageMessage;
778
1487
  }
1488
+ messageContent.header = { title: title || product.title || 'Product', hasMediaAttachment: false, productMessage: { product: { productImage: productImageMessage, productId: product.productId || '', title: product.title || '', description: product.description || '', currencyCode: product.currencyCode || 'USD', priceAmount1000: parseInt(product.priceAmount1000) || 0, retailerId: product.retailerId || '', url: product.url || '', productImageCount: product.productImageCount || 1 }, businessOwnerJid: businessOwnerJid || product.businessOwnerJid || userJid } };
1489
+ } else if (title) {
1490
+ messageContent.header = { title, hasMediaAttachment: false };
779
1491
  }
780
- return albumMsg;
1492
+ const hasMedia = !!(image || video || document || location || product);
1493
+ const bodyText = hasMedia ? caption : text || caption;
1494
+ if (bodyText) messageContent.body = { text: bodyText };
1495
+ if (footer) messageContent.footer = { text: footer };
1496
+ messageContent.nativeFlowMessage = { buttons: processedButtons };
1497
+ // Context info
1498
+ if (externalAdReply && typeof externalAdReply === 'object') {
1499
+ messageContent.contextInfo = { externalAdReply: { title: externalAdReply.title || '', body: externalAdReply.body || '', mediaType: externalAdReply.mediaType || 1, sourceUrl: externalAdReply.sourceUrl || externalAdReply.url || '', thumbnailUrl: externalAdReply.thumbnailUrl || externalAdReply.thumbnail || '', renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false, showAdAttribution: externalAdReply.showAdAttribution !== false, containsAutoReply: externalAdReply.containsAutoReply || false, ...(externalAdReply.mediaUrl && { mediaUrl: externalAdReply.mediaUrl }), ...(Buffer.isBuffer(externalAdReply.thumbnail) && { thumbnail: externalAdReply.thumbnail }), ...(externalAdReply.jpegThumbnail && { jpegThumbnail: externalAdReply.jpegThumbnail }) }, ...(options.mentionedJid && { mentionedJid: options.mentionedJid }) };
1500
+ } else if (options.mentionedJid) {
1501
+ messageContent.contextInfo = { mentionedJid: options.mentionedJid };
1502
+ }
1503
+ const payload = proto.Message.InteractiveMessage.create(messageContent);
1504
+ const msg = generateWAMessageFromContent(jid, { viewOnceMessage: { message: { interactiveMessage: payload } } }, { userJid, quoted: options?.quoted || null });
1505
+ const additionalNodes = [{ tag: 'biz', attrs: {}, content: [{ tag: 'interactive', attrs: { type: 'native_flow', v: '1' }, content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }] }] }];
1506
+ await relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes });
1507
+ return msg;
1508
+ }
1509
+ // ── End Interactive Button ─────────────────────────────────────────
1510
+ if (typeof content === 'object' &&
1511
+ 'disappearingMessagesInChat' in content &&
1512
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1513
+ isJidGroup(jid)) {
1514
+ const { disappearingMessagesInChat } = content;
1515
+ const value = typeof disappearingMessagesInChat === 'boolean'
1516
+ ? disappearingMessagesInChat
1517
+ ? WA_DEFAULT_EPHEMERAL
1518
+ : 0
1519
+ : disappearingMessagesInChat;
1520
+ await groupToggleEphemeral(jid, value);
781
1521
  }
782
1522
  else {
783
1523
  let mediaHandle;
784
- const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
1524
+ const fullMsg = await generateWAMessage(jid, content, {
785
1525
  logger,
786
1526
  userJid,
787
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
1527
+ getUrlInfo: text => getUrlInfo(text, {
788
1528
  thumbnailWidth: linkPreviewImageThumbnailWidth,
789
1529
  fetchOpts: {
790
1530
  timeout: 3000,
791
- ...axiosOptions || {}
1531
+ ...(httpRequestOptions || {})
792
1532
  },
793
1533
  logger,
794
- uploadImage: generateHighQualityLinkPreview
795
- ? waUploadToServer
796
- : undefined
1534
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
797
1535
  }),
1536
+ //TODO: CACHE
798
1537
  getProfilePicUrl: sock.profilePictureUrl,
799
- upload: async (readStream, opts) => {
800
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsletter)(jid) });
1538
+ getCallLink: sock.createCallLink,
1539
+ newsletter: _isNewsletterJid(jid),
1540
+ upload: async (encFilePath, opts) => {
1541
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: _isNewsletterJid(jid) });
801
1542
  mediaHandle = up.handle;
802
1543
  return up;
803
1544
  },
804
1545
  mediaCache: config.mediaCache,
805
1546
  options: config.options,
806
- messageId: (0, Utils_1.generateMessageIDV2)((_c = sock.user) === null || _c === void 0 ? void 0 : _c.id),
807
- ...options,
1547
+ messageId: generateMessageIDV2(sock.user?.id),
1548
+ ...options
808
1549
  });
1550
+ if (content?.audio && options?.contextInfo) {
1551
+ const msgContent = fullMsg.message;
1552
+ if (msgContent?.audioMessage) {
1553
+ msgContent.audioMessage.contextInfo = options.contextInfo;
1554
+ }
1555
+ }
1556
+ // Extract handle from newsletter upload (set by prepareWAMessageMedia)
1557
+ if (!mediaHandle) {
1558
+ const msgContent = fullMsg.message;
1559
+ const msgTypes = ['audioMessage','imageMessage','videoMessage','documentMessage','stickerMessage'];
1560
+ for (const t of msgTypes) {
1561
+ if (msgContent?.[t]?._uploadHandle) {
1562
+ mediaHandle = msgContent[t]._uploadHandle;
1563
+
1564
+ delete msgContent[t]._uploadHandle;
1565
+ break;
1566
+ }
1567
+ }
1568
+ }
1569
+ const isEventMsg = 'event' in content && !!content.event;
809
1570
  const isDeleteMsg = 'delete' in content && !!content.delete;
810
1571
  const isEditMsg = 'edit' in content && !!content.edit;
811
1572
  const isPinMsg = 'pin' in content && !!content.pin;
812
- const isKeepMsg = 'keep' in content && content.keep;
813
1573
  const isPollMessage = 'poll' in content && !!content.poll;
814
- const isAiMsg = 'ai' in content && !!content.ai;
815
1574
  const additionalAttributes = {};
816
1575
  const additionalNodes = [];
817
1576
  // required for delete
818
1577
  if (isDeleteMsg) {
819
1578
  // if the chat is a group, and I am not the author, then delete the message as an admin
820
- if (((0, WABinary_1.isJidGroup)(content.delete.remoteJid) && !content.delete.fromMe) || (0, WABinary_1.isJidNewsletter)(jid)) {
1579
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
821
1580
  additionalAttributes.edit = '8';
822
1581
  }
823
1582
  else {
824
1583
  additionalAttributes.edit = '7';
825
1584
  }
826
- // required for edit message
827
1585
  }
828
1586
  else if (isEditMsg) {
829
- additionalAttributes.edit = (0, WABinary_1.isJidNewsletter)(jid) ? '3' : '1';
830
- // required for pin message
1587
+ additionalAttributes.edit = '1';
831
1588
  }
832
1589
  else if (isPinMsg) {
833
1590
  additionalAttributes.edit = '2';
834
- // required for keep message
835
- }
836
- else if (isKeepMsg) {
837
- additionalAttributes.edit = '6';
838
- // required for polling message
839
1591
  }
840
1592
  else if (isPollMessage) {
841
1593
  additionalNodes.push({
842
1594
  tag: 'meta',
843
1595
  attrs: {
844
1596
  polltype: 'creation'
845
- },
1597
+ }
846
1598
  });
847
- // required to display AI icon on message
848
1599
  }
849
- else if (isAiMsg) {
1600
+ else if (isEventMsg) {
850
1601
  additionalNodes.push({
1602
+ tag: 'meta',
851
1603
  attrs: {
852
- biz_bot: '1'
853
- },
854
- tag: "bot"
1604
+ event_type: 'creation'
1605
+ }
855
1606
  });
856
1607
  }
1608
+ // Auto-attach biz node for button/list/interactive messages
1609
+ const buttonType = getButtonType(fullMsg.message);
1610
+ if (buttonType) {
1611
+ const btnNode = getButtonArgs(fullMsg.message);
1612
+ if (btnNode) additionalNodes.push(btnNode);
1613
+ }
857
1614
  if (mediaHandle) {
858
1615
  additionalAttributes['media_id'] = mediaHandle;
859
1616
  }
860
- if ('cachedGroupMetadata' in options) {
861
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
862
- }
863
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
1617
+ await relayMessage(jid, fullMsg.message, {
1618
+ messageId: fullMsg.key.id,
1619
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1620
+ additionalAttributes,
1621
+ statusJidList: options.statusJidList,
1622
+ additionalNodes,
1623
+ AI: options.ai || false
1624
+ });
864
1625
  if (config.emitOwnEvents) {
865
- process.nextTick(() => {
866
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
1626
+ process.nextTick(async () => {
1627
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
867
1628
  });
868
1629
  }
869
1630
  return fullMsg;
@@ -871,4 +1632,4 @@ const makeMessagesSocket = (config) => {
871
1632
  }
872
1633
  };
873
1634
  };
874
- exports.makeMessagesSocket = makeMessagesSocket;
1635
+ //# sourceMappingURL=messages-send.js.map