@rakku-kun/baileys 2.0.2

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 (405) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +647 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +81 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97687 -0
  8. package/engine-requirements.js +10 -0
  9. package/index.cjs +196 -0
  10. package/index.d.ts +30 -0
  11. package/lib/Defaults/index.d.ts +74 -0
  12. package/lib/Defaults/index.d.ts.map +1 -0
  13. package/lib/Defaults/index.js +135 -0
  14. package/lib/Defaults/index.js.map +1 -0
  15. package/lib/Defaults/phonenumber-mcc.json +223 -0
  16. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  17. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  18. package/lib/Signal/Group/ciphertext-message.js +12 -0
  19. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  20. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  21. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  22. package/lib/Signal/Group/group-session-builder.js +30 -0
  23. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  24. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  25. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  26. package/lib/Signal/Group/group_cipher.js +82 -0
  27. package/lib/Signal/Group/group_cipher.js.map +1 -0
  28. package/lib/Signal/Group/index.d.ts +12 -0
  29. package/lib/Signal/Group/index.d.ts.map +1 -0
  30. package/lib/Signal/Group/index.js +12 -0
  31. package/lib/Signal/Group/index.js.map +1 -0
  32. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  33. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  34. package/lib/Signal/Group/keyhelper.js +18 -0
  35. package/lib/Signal/Group/keyhelper.js.map +1 -0
  36. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  37. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  38. package/lib/Signal/Group/sender-chain-key.js +26 -0
  39. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  41. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  42. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  43. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  44. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  45. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  46. package/lib/Signal/Group/sender-key-message.js +66 -0
  47. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  48. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  49. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  50. package/lib/Signal/Group/sender-key-name.js +48 -0
  51. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  52. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  53. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  54. package/lib/Signal/Group/sender-key-record.js +41 -0
  55. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  56. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  57. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  58. package/lib/Signal/Group/sender-key-state.js +84 -0
  59. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  60. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  61. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  62. package/lib/Signal/Group/sender-message-key.js +26 -0
  63. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  64. package/lib/Signal/libsignal.d.ts +5 -0
  65. package/lib/Signal/libsignal.d.ts.map +1 -0
  66. package/lib/Signal/libsignal.js +438 -0
  67. package/lib/Signal/libsignal.js.map +1 -0
  68. package/lib/Signal/lid-mapping.d.ts +19 -0
  69. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  70. package/lib/Signal/lid-mapping.js +271 -0
  71. package/lib/Signal/lid-mapping.js.map +1 -0
  72. package/lib/Socket/Client/index.d.ts +3 -0
  73. package/lib/Socket/Client/index.d.ts.map +1 -0
  74. package/lib/Socket/Client/index.js +3 -0
  75. package/lib/Socket/Client/index.js.map +1 -0
  76. package/lib/Socket/Client/types.d.ts +16 -0
  77. package/lib/Socket/Client/types.d.ts.map +1 -0
  78. package/lib/Socket/Client/types.js +11 -0
  79. package/lib/Socket/Client/types.js.map +1 -0
  80. package/lib/Socket/Client/websocket.d.ts +13 -0
  81. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  82. package/lib/Socket/Client/websocket.js +54 -0
  83. package/lib/Socket/Client/websocket.js.map +1 -0
  84. package/lib/Socket/business.d.ts +202 -0
  85. package/lib/Socket/business.d.ts.map +1 -0
  86. package/lib/Socket/business.js +379 -0
  87. package/lib/Socket/business.js.map +1 -0
  88. package/lib/Socket/chats.d.ts +111 -0
  89. package/lib/Socket/chats.d.ts.map +1 -0
  90. package/lib/Socket/chats.js +1133 -0
  91. package/lib/Socket/chats.js.map +1 -0
  92. package/lib/Socket/communities.d.ts +258 -0
  93. package/lib/Socket/communities.d.ts.map +1 -0
  94. package/lib/Socket/communities.js +431 -0
  95. package/lib/Socket/communities.js.map +1 -0
  96. package/lib/Socket/community.js +361 -0
  97. package/lib/Socket/groups.d.ts +150 -0
  98. package/lib/Socket/groups.d.ts.map +1 -0
  99. package/lib/Socket/groups.js +459 -0
  100. package/lib/Socket/groups.js.map +1 -0
  101. package/lib/Socket/index.d.ts +245 -0
  102. package/lib/Socket/index.d.ts.map +1 -0
  103. package/lib/Socket/index.js +12 -0
  104. package/lib/Socket/index.js.map +1 -0
  105. package/lib/Socket/messages-recv.d.ts +187 -0
  106. package/lib/Socket/messages-recv.d.ts.map +1 -0
  107. package/lib/Socket/messages-recv.js +1681 -0
  108. package/lib/Socket/messages-recv.js.map +1 -0
  109. package/lib/Socket/messages-send.d.ts +183 -0
  110. package/lib/Socket/messages-send.d.ts.map +1 -0
  111. package/lib/Socket/messages-send.js +1635 -0
  112. package/lib/Socket/messages-send.js.map +1 -0
  113. package/lib/Socket/mex.d.ts +3 -0
  114. package/lib/Socket/mex.d.ts.map +1 -0
  115. package/lib/Socket/mex.js +42 -0
  116. package/lib/Socket/mex.js.map +1 -0
  117. package/lib/Socket/newsletter.d.ts +160 -0
  118. package/lib/Socket/newsletter.d.ts.map +1 -0
  119. package/lib/Socket/newsletter.js +270 -0
  120. package/lib/Socket/newsletter.js.map +1 -0
  121. package/lib/Socket/socket.d.ts +55 -0
  122. package/lib/Socket/socket.d.ts.map +1 -0
  123. package/lib/Socket/socket.js +944 -0
  124. package/lib/Socket/socket.js.map +1 -0
  125. package/lib/Socket/usync.js +76 -0
  126. package/lib/Store/index.js +4 -0
  127. package/lib/Store/make-cache-manager-store.js +77 -0
  128. package/lib/Store/make-in-memory-store.js +400 -0
  129. package/lib/Store/make-ordered-dictionary.js +78 -0
  130. package/lib/Store/object-repository.js +23 -0
  131. package/lib/Types/Auth.d.ts +116 -0
  132. package/lib/Types/Auth.d.ts.map +1 -0
  133. package/lib/Types/Auth.js +2 -0
  134. package/lib/Types/Auth.js.map +1 -0
  135. package/lib/Types/Bussines.d.ts +25 -0
  136. package/lib/Types/Bussines.d.ts.map +1 -0
  137. package/lib/Types/Bussines.js +2 -0
  138. package/lib/Types/Bussines.js.map +1 -0
  139. package/lib/Types/Call.d.ts +15 -0
  140. package/lib/Types/Call.d.ts.map +1 -0
  141. package/lib/Types/Call.js +2 -0
  142. package/lib/Types/Call.js.map +1 -0
  143. package/lib/Types/Chat.d.ts +123 -0
  144. package/lib/Types/Chat.d.ts.map +1 -0
  145. package/lib/Types/Chat.js +8 -0
  146. package/lib/Types/Chat.js.map +1 -0
  147. package/lib/Types/Contact.d.ts +24 -0
  148. package/lib/Types/Contact.d.ts.map +1 -0
  149. package/lib/Types/Contact.js +2 -0
  150. package/lib/Types/Contact.js.map +1 -0
  151. package/lib/Types/Events.d.ts +237 -0
  152. package/lib/Types/Events.d.ts.map +1 -0
  153. package/lib/Types/Events.js +2 -0
  154. package/lib/Types/Events.js.map +1 -0
  155. package/lib/Types/GroupMetadata.d.ts +67 -0
  156. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  157. package/lib/Types/GroupMetadata.js +2 -0
  158. package/lib/Types/GroupMetadata.js.map +1 -0
  159. package/lib/Types/Label.d.ts +47 -0
  160. package/lib/Types/Label.d.ts.map +1 -0
  161. package/lib/Types/Label.js +25 -0
  162. package/lib/Types/Label.js.map +1 -0
  163. package/lib/Types/LabelAssociation.d.ts +30 -0
  164. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  165. package/lib/Types/LabelAssociation.js +7 -0
  166. package/lib/Types/LabelAssociation.js.map +1 -0
  167. package/lib/Types/Message.d.ts +495 -0
  168. package/lib/Types/Message.d.ts.map +1 -0
  169. package/lib/Types/Message.js +11 -0
  170. package/lib/Types/Message.js.map +1 -0
  171. package/lib/Types/MexUpdates.js +9 -0
  172. package/lib/Types/Newsletter.d.ts +135 -0
  173. package/lib/Types/Newsletter.d.ts.map +1 -0
  174. package/lib/Types/Newsletter.js +43 -0
  175. package/lib/Types/Newsletter.js.map +1 -0
  176. package/lib/Types/Product.d.ts +79 -0
  177. package/lib/Types/Product.d.ts.map +1 -0
  178. package/lib/Types/Product.js +2 -0
  179. package/lib/Types/Product.js.map +1 -0
  180. package/lib/Types/Signal.d.ts +76 -0
  181. package/lib/Types/Signal.d.ts.map +1 -0
  182. package/lib/Types/Signal.js +2 -0
  183. package/lib/Types/Signal.js.map +1 -0
  184. package/lib/Types/Socket.d.ts +133 -0
  185. package/lib/Types/Socket.d.ts.map +1 -0
  186. package/lib/Types/Socket.js +3 -0
  187. package/lib/Types/Socket.js.map +1 -0
  188. package/lib/Types/State.d.ts +39 -0
  189. package/lib/Types/State.d.ts.map +1 -0
  190. package/lib/Types/State.js +13 -0
  191. package/lib/Types/State.js.map +1 -0
  192. package/lib/Types/USync.d.ts +26 -0
  193. package/lib/Types/USync.d.ts.map +1 -0
  194. package/lib/Types/USync.js +2 -0
  195. package/lib/Types/USync.js.map +1 -0
  196. package/lib/Types/index.d.ts +65 -0
  197. package/lib/Types/index.d.ts.map +1 -0
  198. package/lib/Types/index.js +27 -0
  199. package/lib/Types/index.js.map +1 -0
  200. package/lib/Utils/audioToBuffer.js +31 -0
  201. package/lib/Utils/auth-utils.d.ts +19 -0
  202. package/lib/Utils/auth-utils.d.ts.map +1 -0
  203. package/lib/Utils/auth-utils.js +290 -0
  204. package/lib/Utils/auth-utils.js.map +1 -0
  205. package/lib/Utils/baileys-event-stream.js +54 -0
  206. package/lib/Utils/browser-utils.d.ts +4 -0
  207. package/lib/Utils/browser-utils.d.ts.map +1 -0
  208. package/lib/Utils/browser-utils.js +41 -0
  209. package/lib/Utils/browser-utils.js.map +1 -0
  210. package/lib/Utils/business.d.ts +23 -0
  211. package/lib/Utils/business.d.ts.map +1 -0
  212. package/lib/Utils/business.js +231 -0
  213. package/lib/Utils/business.js.map +1 -0
  214. package/lib/Utils/chat-utils.d.ts +70 -0
  215. package/lib/Utils/chat-utils.d.ts.map +1 -0
  216. package/lib/Utils/chat-utils.js +812 -0
  217. package/lib/Utils/chat-utils.js.map +1 -0
  218. package/lib/Utils/crypto.d.ts +37 -0
  219. package/lib/Utils/crypto.d.ts.map +1 -0
  220. package/lib/Utils/crypto.js +118 -0
  221. package/lib/Utils/crypto.js.map +1 -0
  222. package/lib/Utils/decode-wa-message.d.ts +48 -0
  223. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  224. package/lib/Utils/decode-wa-message.js +283 -0
  225. package/lib/Utils/decode-wa-message.js.map +1 -0
  226. package/lib/Utils/event-buffer.d.ts +34 -0
  227. package/lib/Utils/event-buffer.d.ts.map +1 -0
  228. package/lib/Utils/event-buffer.js +574 -0
  229. package/lib/Utils/event-buffer.js.map +1 -0
  230. package/lib/Utils/generics.d.ts +91 -0
  231. package/lib/Utils/generics.d.ts.map +1 -0
  232. package/lib/Utils/generics.js +411 -0
  233. package/lib/Utils/generics.js.map +1 -0
  234. package/lib/Utils/history.d.ts +22 -0
  235. package/lib/Utils/history.d.ts.map +1 -0
  236. package/lib/Utils/history.js +131 -0
  237. package/lib/Utils/history.js.map +1 -0
  238. package/lib/Utils/identity-change-handler.d.ts +37 -0
  239. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  240. package/lib/Utils/identity-change-handler.js +49 -0
  241. package/lib/Utils/identity-change-handler.js.map +1 -0
  242. package/lib/Utils/index.d.ts +22 -0
  243. package/lib/Utils/index.d.ts.map +1 -0
  244. package/lib/Utils/index.js +27 -0
  245. package/lib/Utils/index.js.map +1 -0
  246. package/lib/Utils/link-preview.d.ts +21 -0
  247. package/lib/Utils/link-preview.d.ts.map +1 -0
  248. package/lib/Utils/link-preview.js +85 -0
  249. package/lib/Utils/link-preview.js.map +1 -0
  250. package/lib/Utils/logger.d.ts +13 -0
  251. package/lib/Utils/logger.d.ts.map +1 -0
  252. package/lib/Utils/logger.js +3 -0
  253. package/lib/Utils/logger.js.map +1 -0
  254. package/lib/Utils/lt-hash.d.ts +8 -0
  255. package/lib/Utils/lt-hash.d.ts.map +1 -0
  256. package/lib/Utils/lt-hash.js +8 -0
  257. package/lib/Utils/lt-hash.js.map +1 -0
  258. package/lib/Utils/make-mutex.d.ts +9 -0
  259. package/lib/Utils/make-mutex.d.ts.map +1 -0
  260. package/lib/Utils/make-mutex.js +33 -0
  261. package/lib/Utils/make-mutex.js.map +1 -0
  262. package/lib/Utils/message-retry-manager.d.ts +110 -0
  263. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  264. package/lib/Utils/message-retry-manager.js +225 -0
  265. package/lib/Utils/message-retry-manager.js.map +1 -0
  266. package/lib/Utils/messages-media.d.ts +130 -0
  267. package/lib/Utils/messages-media.d.ts.map +1 -0
  268. package/lib/Utils/messages-media.js +830 -0
  269. package/lib/Utils/messages-media.js.map +1 -0
  270. package/lib/Utils/messages-newsletter.d.ts +84 -0
  271. package/lib/Utils/messages-newsletter.js +316 -0
  272. package/lib/Utils/messages.d.ts +92 -0
  273. package/lib/Utils/messages.d.ts.map +1 -0
  274. package/lib/Utils/messages.js +1699 -0
  275. package/lib/Utils/messages.js.map +1 -0
  276. package/lib/Utils/noise-handler.d.ts +20 -0
  277. package/lib/Utils/noise-handler.d.ts.map +1 -0
  278. package/lib/Utils/noise-handler.js +201 -0
  279. package/lib/Utils/noise-handler.js.map +1 -0
  280. package/lib/Utils/pre-key-manager.d.ts +28 -0
  281. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  282. package/lib/Utils/pre-key-manager.js +106 -0
  283. package/lib/Utils/pre-key-manager.js.map +1 -0
  284. package/lib/Utils/process-message.d.ts +60 -0
  285. package/lib/Utils/process-message.d.ts.map +1 -0
  286. package/lib/Utils/process-message.js +528 -0
  287. package/lib/Utils/process-message.js.map +1 -0
  288. package/lib/Utils/reporting-utils.d.ts +11 -0
  289. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  290. package/lib/Utils/reporting-utils.js +258 -0
  291. package/lib/Utils/reporting-utils.js.map +1 -0
  292. package/lib/Utils/resolve-jid.d.ts +43 -0
  293. package/lib/Utils/resolve-jid.js +101 -0
  294. package/lib/Utils/signal.d.ts +34 -0
  295. package/lib/Utils/signal.d.ts.map +1 -0
  296. package/lib/Utils/signal.js +159 -0
  297. package/lib/Utils/signal.js.map +1 -0
  298. package/lib/Utils/streamToBuffer.js +17 -0
  299. package/lib/Utils/sync-action-utils.d.ts +19 -0
  300. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  301. package/lib/Utils/sync-action-utils.js +48 -0
  302. package/lib/Utils/sync-action-utils.js.map +1 -0
  303. package/lib/Utils/tc-token-utils.d.ts +12 -0
  304. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  305. package/lib/Utils/tc-token-utils.js +18 -0
  306. package/lib/Utils/tc-token-utils.js.map +1 -0
  307. package/lib/Utils/use-mongo-file-auth-state.js +77 -0
  308. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  309. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  310. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  311. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  312. package/lib/Utils/use-single-file-auth-state.js +74 -0
  313. package/lib/Utils/validate-connection.d.ts +11 -0
  314. package/lib/Utils/validate-connection.d.ts.map +1 -0
  315. package/lib/Utils/validate-connection.js +200 -0
  316. package/lib/Utils/validate-connection.js.map +1 -0
  317. package/lib/WABinary/constants.d.ts +28 -0
  318. package/lib/WABinary/constants.d.ts.map +1 -0
  319. package/lib/WABinary/constants.js +1301 -0
  320. package/lib/WABinary/constants.js.map +1 -0
  321. package/lib/WABinary/decode.d.ts +7 -0
  322. package/lib/WABinary/decode.d.ts.map +1 -0
  323. package/lib/WABinary/decode.js +262 -0
  324. package/lib/WABinary/decode.js.map +1 -0
  325. package/lib/WABinary/encode.d.ts +3 -0
  326. package/lib/WABinary/encode.d.ts.map +1 -0
  327. package/lib/WABinary/encode.js +220 -0
  328. package/lib/WABinary/encode.js.map +1 -0
  329. package/lib/WABinary/generic-utils.d.ts +15 -0
  330. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  331. package/lib/WABinary/generic-utils.js +128 -0
  332. package/lib/WABinary/generic-utils.js.map +1 -0
  333. package/lib/WABinary/index.d.ts +6 -0
  334. package/lib/WABinary/index.d.ts.map +1 -0
  335. package/lib/WABinary/index.js +7 -0
  336. package/lib/WABinary/index.js.map +1 -0
  337. package/lib/WABinary/jid-utils.d.ts +48 -0
  338. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  339. package/lib/WABinary/jid-utils.js +98 -0
  340. package/lib/WABinary/jid-utils.js.map +1 -0
  341. package/lib/WABinary/types.d.ts +19 -0
  342. package/lib/WABinary/types.d.ts.map +1 -0
  343. package/lib/WABinary/types.js +2 -0
  344. package/lib/WABinary/types.js.map +1 -0
  345. package/lib/WAM/BinaryInfo.d.ts +9 -0
  346. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  347. package/lib/WAM/BinaryInfo.js +10 -0
  348. package/lib/WAM/BinaryInfo.js.map +1 -0
  349. package/lib/WAM/constants.d.ts +40 -0
  350. package/lib/WAM/constants.d.ts.map +1 -0
  351. package/lib/WAM/constants.js +22853 -0
  352. package/lib/WAM/constants.js.map +1 -0
  353. package/lib/WAM/encode.d.ts +3 -0
  354. package/lib/WAM/encode.d.ts.map +1 -0
  355. package/lib/WAM/encode.js +150 -0
  356. package/lib/WAM/encode.js.map +1 -0
  357. package/lib/WAM/index.d.ts +4 -0
  358. package/lib/WAM/index.d.ts.map +1 -0
  359. package/lib/WAM/index.js +4 -0
  360. package/lib/WAM/index.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  362. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  364. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  366. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  368. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  370. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  372. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  374. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  376. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  378. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  380. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  382. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  384. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  385. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  386. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  387. package/lib/WAUSync/Protocols/index.js +6 -0
  388. package/lib/WAUSync/Protocols/index.js.map +1 -0
  389. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  390. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncQuery.js +94 -0
  392. package/lib/WAUSync/USyncQuery.js.map +1 -0
  393. package/lib/WAUSync/USyncUser.d.ts +13 -0
  394. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  395. package/lib/WAUSync/USyncUser.js +23 -0
  396. package/lib/WAUSync/USyncUser.js.map +1 -0
  397. package/lib/WAUSync/index.d.ts +4 -0
  398. package/lib/WAUSync/index.d.ts.map +1 -0
  399. package/lib/WAUSync/index.js +4 -0
  400. package/lib/WAUSync/index.js.map +1 -0
  401. package/lib/index.d.ts +12 -0
  402. package/lib/index.d.ts.map +1 -0
  403. package/lib/index.js +31 -0
  404. package/lib/index.js.map +1 -0
  405. package/package.json +94 -0
@@ -0,0 +1,1635 @@
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,
29
+ useClones: false
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();
35
+ let mediaConn;
36
+ const refreshMediaConn = async (forceGet = false) => {
37
+ const media = await mediaConn;
38
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
39
+ mediaConn = (async () => {
40
+ const result = await query({
41
+ tag: 'iq',
42
+ attrs: {
43
+ type: 'set',
44
+ xmlns: 'w:m',
45
+ to: S_WHATSAPP_NET
46
+ },
47
+ content: [{ tag: 'media_conn', attrs: {} }]
48
+ });
49
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
50
+ // TODO: explore full length of data that whatsapp provides
51
+ const node = {
52
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
53
+ hostname: attrs.hostname,
54
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
55
+ })),
56
+ auth: mediaConnNode.attrs.auth,
57
+ ttl: +mediaConnNode.attrs.ttl,
58
+ fetchDate: new Date()
59
+ };
60
+ logger.debug('fetched media conn');
61
+ return node;
62
+ })();
63
+ }
64
+ return mediaConn;
65
+ };
66
+ /**
67
+ * generic send receipt function
68
+ * used for receipts of phone call, read, delivery etc.
69
+ * */
70
+ const sendReceipt = async (jid, participant, messageIds, type) => {
71
+ if (!messageIds || messageIds.length === 0) {
72
+ throw new Boom('missing ids in receipt');
73
+ }
74
+ const node = {
75
+ tag: 'receipt',
76
+ attrs: {
77
+ id: messageIds[0]
78
+ }
79
+ };
80
+ const isReadReceipt = type === 'read' || type === 'read-self';
81
+ if (isReadReceipt) {
82
+ node.attrs.t = unixTimestampSeconds().toString();
83
+ }
84
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
85
+ node.attrs.recipient = jid;
86
+ node.attrs.to = participant;
87
+ }
88
+ else {
89
+ node.attrs.to = jid;
90
+ if (participant) {
91
+ node.attrs.participant = participant;
92
+ }
93
+ }
94
+ if (type) {
95
+ node.attrs.type = type;
96
+ }
97
+ const remainingMessageIds = messageIds.slice(1);
98
+ if (remainingMessageIds.length) {
99
+ node.content = [
100
+ {
101
+ tag: 'list',
102
+ attrs: {},
103
+ content: remainingMessageIds.map(id => ({
104
+ tag: 'item',
105
+ attrs: { id }
106
+ }))
107
+ }
108
+ ];
109
+ }
110
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
111
+ await sendNode(node);
112
+ };
113
+ /** Correctly bulk send receipts to multiple chats, participants */
114
+ const sendReceipts = async (keys, type) => {
115
+ const recps = aggregateMessageKeysNotFromMe(keys);
116
+ for (const { jid, participant, messageIds } of recps) {
117
+ await sendReceipt(jid, participant, messageIds, type);
118
+ }
119
+ };
120
+ /** Bulk read messages. Keys can be from different chats & participants */
121
+ const readMessages = async (keys) => {
122
+ const privacySettings = await fetchPrivacySettings();
123
+ // based on privacy settings, we have to change the read type
124
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
125
+ await sendReceipts(keys, readType);
126
+ };
127
+ /** Fetch all the devices we've to send a message to */
128
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
129
+ const deviceResults = [];
130
+ if (!useCache) {
131
+ logger.debug('not using cache for devices');
132
+ }
133
+ const toFetch = [];
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) {
158
+ if (useCache) {
159
+ const devices = mgetDevices?.[user] ||
160
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
161
+ if (devices) {
162
+ const devicesWithJid = devices.map(d => ({
163
+ ...d,
164
+ jid: jidEncode(d.user, d.server, d.device)
165
+ }));
166
+ deviceResults.push(...devicesWithJid);
167
+ logger.trace({ user }, 'using cache for devices');
168
+ }
169
+ else {
170
+ toFetch.push(jid);
171
+ }
172
+ }
173
+ else {
174
+ toFetch.push(jid);
175
+ }
176
+ }
177
+ if (!toFetch.length) {
178
+ return deviceResults;
179
+ }
180
+ const requestedLidUsers = new Set();
181
+ for (const jid of toFetch) {
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
191
+ }
192
+ const result = await sock.executeUSyncQuery(query);
193
+ if (result) {
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);
211
+ const deviceMap = {};
212
+ for (const item of extracted) {
213
+ deviceMap[item.user] = deviceMap[item.user] || [];
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
+ }
251
+ }
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
+ }
260
+ }
261
+ }
262
+ return deviceResults;
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
+ };
289
+ const assertSessions = async (jids, force) => {
290
+ let didFetchNewSession = false;
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;
309
+ }
310
+ }
311
+ jidsRequiringFetch.push(jid);
312
+ }
313
+ if (jidsRequiringFetch.length) {
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');
320
+ const result = await query({
321
+ tag: 'iq',
322
+ attrs: {
323
+ xmlns: 'encrypt',
324
+ type: 'get',
325
+ to: S_WHATSAPP_NET
326
+ },
327
+ content: [
328
+ {
329
+ tag: 'key',
330
+ attrs: {},
331
+ content: wireJids.map(jid => {
332
+ const attrs = { jid };
333
+ if (force)
334
+ attrs.reason = 'identity';
335
+ return { tag: 'user', attrs };
336
+ })
337
+ }
338
+ ]
339
+ });
340
+ await parseAndInjectE2ESessions(result, signalRepository);
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
+ }
347
+ }
348
+ return didFetchNewSession;
349
+ };
350
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
351
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
352
+ if (!authState.creds.me?.id) {
353
+ throw new Boom('Not authenticated');
354
+ }
355
+ const protocolMessage = {
356
+ protocolMessage: {
357
+ peerDataOperationRequestMessage: pdoMessage,
358
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
359
+ }
360
+ };
361
+ const meJid = jidNormalizedUser(authState.creds.me.id);
362
+ const msgId = await relayMessage(meJid, protocolMessage, {
363
+ additionalAttributes: {
364
+ category: 'peer',
365
+ push_priority: 'high_force'
366
+ },
367
+ additionalNodes: [
368
+ {
369
+ tag: 'meta',
370
+ attrs: { appdata: 'default' }
371
+ }
372
+ ]
373
+ });
374
+ return msgId;
375
+ };
376
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
377
+ if (!recipientJids.length) {
378
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
379
+ }
380
+ const patched = await patchMessageBeforeSending(message, recipientJids);
381
+ const patchedMessages = Array.isArray(patched)
382
+ ? patched
383
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
384
+ let shouldIncludeDeviceIdentity = false;
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
+ }
434
+ return { nodes, shouldIncludeDeviceIdentity };
435
+ };
436
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
437
+ const meId = authState.creds.me.id;
438
+ const meLid = authState.creds.me?.lid;
439
+ const isRetryResend = Boolean(participant?.jid);
440
+ let shouldIncludeDeviceIdentity = isRetryResend;
441
+ const statusJid = 'status@broadcast';
442
+ const { user, server } = jidDecode(jid);
443
+ const isGroup = server === 'g.us';
444
+ const isStatus = jid === statusJid;
445
+ const isLid = server === 'lid';
446
+ const isNewsletter = server === 'newsletter';
447
+ const isGroupOrStatus = isGroup || isStatus;
448
+ const finalJid = jid;
449
+ msgId = msgId || generateMessageIDV2(meId);
450
+ useUserDevicesCache = useUserDevicesCache !== false;
451
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
452
+ const participants = [];
453
+ const destinationJid = !isStatus ? finalJid : statusJid;
454
+ const binaryNodeContent = [];
455
+ const devices = [];
456
+ let reportingMessage;
457
+ const meMsg = {
458
+ deviceSentMessage: {
459
+ destinationJid,
460
+ message
461
+ },
462
+ messageContextInfo: message.messageContextInfo
463
+ };
464
+ const extraAttrs = {};
465
+ if (participant) {
466
+ if (!isGroup && !isStatus) {
467
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
468
+ }
469
+ const { user, device } = jidDecode(participant.jid);
470
+ devices.push({
471
+ user,
472
+ device,
473
+ jid: participant.jid
474
+ });
475
+ }
476
+ await authState.keys.transaction(async () => {
477
+ const mediaType = getMediaType(message);
478
+ if (mediaType) {
479
+ extraAttrs['mediatype'] = mediaType;
480
+ }
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
580
+ }
581
+ if (isGroupOrStatus && !isRetryResend) {
582
+ const [groupData, senderKeyMap] = await Promise.all([
583
+ (async () => {
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)) {
586
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
587
+ }
588
+ else if (!isStatus) {
589
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
590
+ }
591
+ return groupData;
592
+ })(),
593
+ (async () => {
594
+ if (!participant && !isStatus) {
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?
598
+ return result[jid] || {};
599
+ }
600
+ return {};
601
+ })()
602
+ ]);
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
757
+ };
758
+ message = { interactiveMessage };
759
+ }
760
+ }
761
+ // ── End Group Interactive Message Compatibility Patch ──────────
762
+ const patched = await patchMessageBeforeSending(message);
763
+ if (Array.isArray(patched)) {
764
+ throw new Boom('Per-jid patching is not supported in groups');
765
+ }
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;
770
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
771
+ group: destinationJid,
772
+ data: bytes,
773
+ meId: groupSenderIdentity
774
+ });
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;
787
+ }
788
+ }
789
+ if (senderKeyRecipients.length) {
790
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
791
+ const senderKeyMsg = {
792
+ senderKeyDistributionMessage: {
793
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
794
+ groupId: destinationJid
795
+ }
796
+ };
797
+ const senderKeySessionTargets = senderKeyRecipients;
798
+ await assertSessions(senderKeySessionTargets);
799
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
800
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
801
+ participants.push(...result.nodes);
802
+ }
803
+ binaryNodeContent.push({
804
+ tag: 'enc',
805
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
806
+ content: ciphertext
807
+ });
808
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
809
+ }
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');
817
+ }
818
+ else {
819
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
820
+ }
821
+ const { user: ownUser } = jidDecode(ownId);
822
+ if (!participant) {
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
+ });
843
+ }
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');
858
+ }
859
+ }
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;
873
+ if (isMe) {
874
+ meRecipients.push(jid);
875
+ }
876
+ else {
877
+ otherRecipients.push(jid);
878
+ }
879
+ allRecipients.push(jid);
880
+ }
881
+ await assertSessions(allRecipients);
882
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
883
+ // For own devices: use DSM if available (1:1 chats only)
884
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
885
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
886
+ ]);
887
+ participants.push(...meNodes);
888
+ participants.push(...otherNodes);
889
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
890
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
891
+ }
892
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
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
+ }
919
+ if (participants.length) {
920
+ if (additionalAttributes?.['category'] === 'peer') {
921
+ const peerNode = participants[0]?.content?.[0];
922
+ if (peerNode) {
923
+ binaryNodeContent.push(peerNode); // push only enc
924
+ }
925
+ }
926
+ else {
927
+ binaryNodeContent.push({
928
+ tag: 'participants',
929
+ attrs: {},
930
+ content: participants
931
+ });
932
+ }
933
+ }
934
+ const stanza = {
935
+ tag: 'message',
936
+ attrs: {
937
+ id: msgId,
938
+ to: destinationJid,
939
+ type: getMessageType(message),
940
+ ...(additionalAttributes || {})
941
+ },
942
+ content: binaryNodeContent
943
+ };
944
+ // if the participant to send to is explicitly specified (generally retry recp)
945
+ // ensure the message is only sent to that person
946
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
947
+ if (participant) {
948
+ if (isJidGroup(destinationJid)) {
949
+ stanza.attrs.to = destinationJid;
950
+ stanza.attrs.participant = participant.jid;
951
+ }
952
+ else if (areJidsSameUser(participant.jid, meId)) {
953
+ stanza.attrs.to = participant.jid;
954
+ stanza.attrs.recipient = destinationJid;
955
+ }
956
+ else {
957
+ stanza.attrs.to = participant.jid;
958
+ }
959
+ }
960
+ else {
961
+ stanza.attrs.to = destinationJid;
962
+ }
963
+ if (shouldIncludeDeviceIdentity) {
964
+ ;
965
+ stanza.content.push({
966
+ tag: 'device-identity',
967
+ attrs: {},
968
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
969
+ });
970
+ logger.debug({ jid }, 'adding device identity');
971
+ }
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
+ }
994
+ }
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
+ }
1016
+ }
1017
+ } else if (additionalNodes && additionalNodes.length > 0) {
1018
+ ;
1019
+ stanza.content.push(...additionalNodes);
1020
+ }
1021
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1022
+ await sendNode(stanza);
1023
+ // Add message to retry cache if enabled
1024
+ if (messageRetryManager && !participant) {
1025
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1026
+ }
1027
+ }, meId);
1028
+ return msgId;
1029
+ };
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';
1035
+ }
1036
+ const normalizedMessage = normalizeMessageContent(message);
1037
+ if (!normalizedMessage)
1038
+ return 'text';
1039
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
1040
+ return 'reaction';
1041
+ }
1042
+ if (normalizedMessage.pollCreationMessage ||
1043
+ normalizedMessage.pollCreationMessageV2 ||
1044
+ normalizedMessage.pollCreationMessageV3 ||
1045
+ normalizedMessage.pollUpdateMessage) {
1046
+ return 'poll';
1047
+ }
1048
+ if (normalizedMessage.eventMessage) {
1049
+ return 'event';
1050
+ }
1051
+ if (normalizedMessage.interactiveMessage) {
1052
+ return 'text';
1053
+ }
1054
+ if (getMediaType(normalizedMessage) !== '') {
1055
+ return 'media';
1056
+ }
1057
+ return 'text';
1058
+ };
1059
+ const getMediaType = (message) => {
1060
+ if (message.imageMessage) {
1061
+ return 'image';
1062
+ }
1063
+ else if (message.videoMessage) {
1064
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1065
+ }
1066
+ else if (message.ptvMessage) {
1067
+ return 'video';
1068
+ }
1069
+ else if (message.audioMessage) {
1070
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1071
+ }
1072
+ else if (message.contactMessage) {
1073
+ return 'vcard';
1074
+ }
1075
+ else if (message.documentMessage) {
1076
+ return 'document';
1077
+ }
1078
+ else if (message.contactsArrayMessage) {
1079
+ return 'contact_array';
1080
+ }
1081
+ else if (message.liveLocationMessage) {
1082
+ return 'livelocation';
1083
+ }
1084
+ else if (message.stickerMessage) {
1085
+ return 'sticker';
1086
+ }
1087
+ else if (message.stickerPackMessage) {
1088
+ return 'sticker_pack';
1089
+ }
1090
+ else if (message.listMessage) {
1091
+ return 'list';
1092
+ }
1093
+ else if (message.listResponseMessage) {
1094
+ return 'list_response';
1095
+ }
1096
+ else if (message.buttonsResponseMessage) {
1097
+ return 'buttons_response';
1098
+ }
1099
+ else if (message.orderMessage) {
1100
+ return 'order';
1101
+ }
1102
+ else if (message.productMessage) {
1103
+ return 'product';
1104
+ }
1105
+ else if (message.interactiveResponseMessage) {
1106
+ return 'native_flow_response';
1107
+ }
1108
+ else if (message.groupInviteMessage) {
1109
+ return 'url';
1110
+ }
1111
+ return '';
1112
+ };
1113
+ const getPrivacyTokens = async (jids) => {
1114
+ const t = unixTimestampSeconds().toString();
1115
+ const result = await query({
1116
+ tag: 'iq',
1117
+ attrs: {
1118
+ to: S_WHATSAPP_NET,
1119
+ type: 'set',
1120
+ xmlns: 'privacy'
1121
+ },
1122
+ content: [
1123
+ {
1124
+ tag: 'tokens',
1125
+ attrs: {},
1126
+ content: jids.map(jid => ({
1127
+ tag: 'token',
1128
+ attrs: {
1129
+ jid: jidNormalizedUser(jid),
1130
+ t,
1131
+ type: 'trusted_contact'
1132
+ }
1133
+ }))
1134
+ }
1135
+ ]
1136
+ });
1137
+ return result;
1138
+ };
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 ───────────────────────────────────────────────
1199
+ return {
1200
+ ...sock,
1201
+ getPrivacyTokens,
1202
+ assertSessions,
1203
+ relayMessage,
1204
+ sendReceipt,
1205
+ sendReceipts,
1206
+ readMessages,
1207
+ refreshMediaConn,
1208
+ waUploadToServer,
1209
+ fetchPrivacySettings,
1210
+ sendPeerDataOperationMessage,
1211
+ createParticipantNodes,
1212
+ getUSyncDevices,
1213
+ messageRetryManager,
1214
+ updateMemberLabel,
1215
+ updateMediaMessage: async (message) => {
1216
+ const content = assertMediaContent(message.message);
1217
+ const mediaKey = content.mediaKey;
1218
+ const meId = authState.creds.me.id;
1219
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1220
+ let error = undefined;
1221
+ await Promise.all([
1222
+ sendNode(node),
1223
+ waitForMsgMediaUpdate(async (update) => {
1224
+ const result = update.find(c => c.key.id === message.key.id);
1225
+ if (result) {
1226
+ if (result.error) {
1227
+ error = result.error;
1228
+ }
1229
+ else {
1230
+ try {
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
+ });
1238
+ }
1239
+ content.directPath = media.directPath;
1240
+ content.url = getUrlFromDirectPath(content.directPath);
1241
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1242
+ }
1243
+ catch (err) {
1244
+ error = err;
1245
+ }
1246
+ }
1247
+ return true;
1248
+ }
1249
+ })
1250
+ ]);
1251
+ if (error) {
1252
+ throw error;
1253
+ }
1254
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1255
+ return message;
1256
+ },
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));
1284
+ }
1285
+ }
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;
1344
+ }
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}`);
1393
+ }
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
+ };
1413
+ }
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
+ };
1421
+ });
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;
1453
+ }
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;
1457
+ }
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;
1476
+ }
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;
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 };
1491
+ }
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);
1521
+ }
1522
+ else {
1523
+ let mediaHandle;
1524
+ const fullMsg = await generateWAMessage(jid, content, {
1525
+ logger,
1526
+ userJid,
1527
+ getUrlInfo: text => getUrlInfo(text, {
1528
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1529
+ fetchOpts: {
1530
+ timeout: 3000,
1531
+ ...(httpRequestOptions || {})
1532
+ },
1533
+ logger,
1534
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1535
+ }),
1536
+ //TODO: CACHE
1537
+ getProfilePicUrl: sock.profilePictureUrl,
1538
+ getCallLink: sock.createCallLink,
1539
+ newsletter: _isNewsletterJid(jid),
1540
+ upload: async (encFilePath, opts) => {
1541
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: _isNewsletterJid(jid) });
1542
+ mediaHandle = up.handle;
1543
+ return up;
1544
+ },
1545
+ mediaCache: config.mediaCache,
1546
+ options: config.options,
1547
+ messageId: generateMessageIDV2(sock.user?.id),
1548
+ ...options
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;
1570
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1571
+ const isEditMsg = 'edit' in content && !!content.edit;
1572
+ const isPinMsg = 'pin' in content && !!content.pin;
1573
+ const isPollMessage = 'poll' in content && !!content.poll;
1574
+ const additionalAttributes = {};
1575
+ const additionalNodes = [];
1576
+ // required for delete
1577
+ if (isDeleteMsg) {
1578
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1579
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1580
+ additionalAttributes.edit = '8';
1581
+ }
1582
+ else {
1583
+ additionalAttributes.edit = '7';
1584
+ }
1585
+ }
1586
+ else if (isEditMsg) {
1587
+ additionalAttributes.edit = '1';
1588
+ }
1589
+ else if (isPinMsg) {
1590
+ additionalAttributes.edit = '2';
1591
+ }
1592
+ else if (isPollMessage) {
1593
+ additionalNodes.push({
1594
+ tag: 'meta',
1595
+ attrs: {
1596
+ polltype: 'creation'
1597
+ }
1598
+ });
1599
+ }
1600
+ else if (isEventMsg) {
1601
+ additionalNodes.push({
1602
+ tag: 'meta',
1603
+ attrs: {
1604
+ event_type: 'creation'
1605
+ }
1606
+ });
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
+ }
1614
+ if (mediaHandle) {
1615
+ additionalAttributes['media_id'] = mediaHandle;
1616
+ }
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
+ });
1625
+ if (config.emitOwnEvents) {
1626
+ process.nextTick(async () => {
1627
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1628
+ });
1629
+ }
1630
+ return fullMsg;
1631
+ }
1632
+ }
1633
+ };
1634
+ };
1635
+ //# sourceMappingURL=messages-send.js.map