@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,830 @@
1
+ import { once } from 'events';
2
+ import { Boom } from '@hapi/boom';
3
+ import * as Crypto from 'crypto';
4
+ import { createReadStream, createWriteStream, promises as fs } from 'fs';
5
+ import { tmpdir } from 'os';
6
+ import { join } from 'path';
7
+ import { Readable, Transform } from 'stream';
8
+ import { URL } from 'url';
9
+ import { proto } from '../../WAProto/index.js';
10
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from '../Defaults/index.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
12
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
13
+ import { generateMessageIDV2 } from './generics.js';
14
+ const getTmpFilesDirectory = () => tmpdir();
15
+ const getImageProcessingLibrary = async () => {
16
+ //@ts-ignore
17
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
18
+ if (sharp) {
19
+ return { sharp };
20
+ }
21
+ if (jimp) {
22
+ return { jimp };
23
+ }
24
+ throw new Boom('No image processing library available');
25
+ };
26
+ export const hkdfInfoKey = (type) => {
27
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
28
+ return `WhatsApp ${hkdfInfo} Keys`;
29
+ };
30
+ export const getRawMediaUploadData = async (media, mediaType, logger) => {
31
+ const { stream } = await getStream(media);
32
+
33
+ const hasher = Crypto.createHash('sha256');
34
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
35
+ const fileWriteStream = createWriteStream(filePath);
36
+ let fileLength = 0;
37
+ try {
38
+ for await (const data of stream) {
39
+ fileLength += data.length;
40
+ hasher.update(data);
41
+ if (!fileWriteStream.write(data)) {
42
+ await once(fileWriteStream, 'drain');
43
+ }
44
+ }
45
+ fileWriteStream.end();
46
+ await once(fileWriteStream, 'finish');
47
+ stream.destroy();
48
+ const fileSha256 = hasher.digest();
49
+
50
+ return {
51
+ filePath: filePath,
52
+ fileSha256,
53
+ fileLength
54
+ };
55
+ }
56
+ catch (error) {
57
+ fileWriteStream.destroy();
58
+ stream.destroy();
59
+ try {
60
+ await fs.unlink(filePath);
61
+ }
62
+ catch {
63
+ //
64
+ }
65
+ throw error;
66
+ }
67
+ };
68
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
69
+ export async function getMediaKeys(buffer, mediaType) {
70
+ if (!buffer) {
71
+ throw new Boom('Cannot derive from empty media key');
72
+ }
73
+ if (typeof buffer === 'string') {
74
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
75
+ }
76
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
77
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
78
+ return {
79
+ iv: expandedMediaKey.slice(0, 16),
80
+ cipherKey: expandedMediaKey.slice(16, 48),
81
+ macKey: expandedMediaKey.slice(48, 80)
82
+ };
83
+ }
84
+
85
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
86
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
87
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
88
+ if (bufferOrFilePath instanceof Readable) {
89
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
90
+ }
91
+ const lib = await getImageProcessingLibrary();
92
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
93
+ const img = lib.sharp.default(bufferOrFilePath);
94
+ const dimensions = await img.metadata();
95
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
96
+ return {
97
+ buffer,
98
+ original: {
99
+ width: dimensions.width,
100
+ height: dimensions.height
101
+ }
102
+ };
103
+ }
104
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
105
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
106
+ const dimensions = {
107
+ width: jimp.width,
108
+ height: jimp.height
109
+ };
110
+ const buffer = await jimp
111
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
112
+ .getBuffer('image/jpeg', { quality: 50 });
113
+ return {
114
+ buffer,
115
+ original: dimensions
116
+ };
117
+ }
118
+ else {
119
+ throw new Boom('No image processing library available');
120
+ }
121
+ };
122
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
123
+ export const generateProfilePicture = async (mediaUpload, dimensions) => {
124
+ let buffer;
125
+ const { width: w = 640, height: h = 640 } = dimensions || {};
126
+ if (Buffer.isBuffer(mediaUpload)) {
127
+ buffer = mediaUpload;
128
+ }
129
+ else {
130
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
131
+ const { stream } = await getStream(mediaUpload);
132
+ // Convert the resulting stream to a buffer
133
+ buffer = await toBuffer(stream);
134
+ }
135
+ const lib = await getImageProcessingLibrary();
136
+ let img;
137
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
138
+ img = lib.sharp
139
+ .default(buffer)
140
+ .resize(w, h)
141
+ .jpeg({
142
+ quality: 50
143
+ })
144
+ .toBuffer();
145
+ }
146
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
147
+ const jimp = await lib.jimp.Jimp.read(buffer);
148
+ const min = Math.min(jimp.width, jimp.height);
149
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
150
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
151
+ }
152
+ else {
153
+ throw new Boom('No image processing library available');
154
+ }
155
+ return {
156
+ img: await img
157
+ };
158
+ };
159
+ /** gets the SHA256 of the given media message */
160
+ export const mediaMessageSHA256B64 = (message) => {
161
+ const media = Object.values(message)[0];
162
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
163
+ };
164
+ export async function getAudioDuration(buffer, mimeType) {
165
+ const musicMetadata = await import('music-metadata');
166
+ let metadata;
167
+ const options = {
168
+ duration: true,
169
+ ...(mimeType ? { mimeType } : {})
170
+ };
171
+ if (Buffer.isBuffer(buffer)) {
172
+ metadata = await musicMetadata.parseBuffer(buffer, mimeType || undefined, options);
173
+ }
174
+ else if (typeof buffer === 'string') {
175
+ // parseFile tidak support mimeType langsung, tapi kita bisa baca sebagai buffer
176
+ // supaya mimeType hint bisa dipass — penting untuk m4a/aac yang nama filenya tanpa ekstensi
177
+ try {
178
+ metadata = await musicMetadata.parseFile(buffer, options);
179
+ } catch (_) {
180
+ // fallback: baca file sebagai buffer lalu parse dengan mimeType
181
+ const { readFileSync } = await import('fs');
182
+ const buf = readFileSync(buffer);
183
+ metadata = await musicMetadata.parseBuffer(buf, mimeType || undefined, options);
184
+ }
185
+ }
186
+ else {
187
+ metadata = await musicMetadata.parseStream(buffer, mimeType || undefined, options);
188
+ }
189
+ const dur = metadata.format.duration;
190
+ // Jangan return NaN/undefined — WhatsApp akan tampilkan "Loading..." kalau seconds invalid
191
+ return (typeof dur === 'number' && !isNaN(dur) && isFinite(dur)) ? Math.round(dur) : 0;
192
+ }
193
+ /**
194
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
195
+ */
196
+ export async function getAudioWaveform(buffer, logger) {
197
+ try {
198
+ // @ts-ignore
199
+ const { default: decoder } = await import('audio-decode');
200
+ let audioData;
201
+ if (Buffer.isBuffer(buffer)) {
202
+ audioData = buffer;
203
+ }
204
+ else if (typeof buffer === 'string') {
205
+ const rStream = createReadStream(buffer);
206
+ audioData = await toBuffer(rStream);
207
+ }
208
+ else {
209
+ audioData = await toBuffer(buffer);
210
+ }
211
+ // Skip audio-decode for large buffers (> 3MB)
212
+ if (audioData.length > 3 * 1024 * 1024) {
213
+ return undefined;
214
+ }
215
+ const audioBuffer = await decoder(audioData);
216
+ const rawData = audioBuffer.getChannelData(0);
217
+ const samples = 64;
218
+ const blockSize = Math.floor(rawData.length / samples);
219
+ const filteredData = [];
220
+ for (let i = 0; i < samples; i++) {
221
+ const blockStart = blockSize * i;
222
+ let sum = 0;
223
+ for (let j = 0; j < blockSize; j++) {
224
+ sum = sum + Math.abs(rawData[blockStart + j]);
225
+ }
226
+ filteredData.push(sum / blockSize);
227
+ }
228
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
229
+ const normalizedData = filteredData.map(n => n * multiplier);
230
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
231
+ return waveform;
232
+ }
233
+ catch (e) {
234
+ }
235
+ }
236
+
237
+ export const toReadable = (buffer) => {
238
+ const readable = new Readable({ read: () => { }, highWaterMark: 64 * 1024 });
239
+ readable.push(buffer);
240
+ readable.push(null);
241
+ return readable;
242
+ };
243
+ export const toBuffer = async (stream) => {
244
+ const chunks = [];
245
+ for await (const chunk of stream) {
246
+ chunks.push(chunk);
247
+ }
248
+ stream.destroy();
249
+ return Buffer.concat(chunks);
250
+ };
251
+
252
+
253
+
254
+ export const getStream = async (item, opts) => {
255
+ if (Buffer.isBuffer(item)) {
256
+ return { stream: toReadable(item), type: 'buffer' };
257
+ }
258
+ if ('stream' in item) {
259
+ return { stream: item.stream, type: 'readable' };
260
+ }
261
+ const urlStr = item.url.toString();
262
+ if (urlStr.startsWith('data:')) {
263
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
264
+ return { stream: toReadable(buffer), type: 'buffer' };
265
+ }
266
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
267
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
268
+ }
269
+ return { stream: createReadStream(item.url), type: 'file' };
270
+ };
271
+ /** generates a thumbnail for a given media, if required */
272
+ export async function generateThumbnail(file, mediaType, options) {
273
+ let thumbnail;
274
+ let originalImageDimensions;
275
+ if (mediaType === 'image') {
276
+ const { buffer, original } = await extractImageThumb(file);
277
+ thumbnail = buffer.toString('base64');
278
+ if (original.width && original.height) {
279
+ originalImageDimensions = {
280
+ width: original.width,
281
+ height: original.height
282
+ };
283
+ }
284
+ }
285
+ else if (mediaType === 'video') {
286
+ // Video thumbnail generation skipped (ffmpeg removed)
287
+ }
288
+ return {
289
+ thumbnail,
290
+ originalImageDimensions
291
+ };
292
+ }
293
+ export const getHttpStream = async (url, options = {}) => {
294
+ const response = await fetch(url.toString(), {
295
+ dispatcher: options.dispatcher,
296
+ method: 'GET',
297
+ headers: options.headers
298
+ });
299
+ if (!response.ok) {
300
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
301
+ }
302
+ // @ts-ignore Node18+ Readable.fromWeb exists
303
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
304
+ };
305
+
306
+ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
307
+ const { stream, type } = await getStream(media, opts);
308
+ let finalStream = stream;
309
+ let opusConverted = false;
310
+
311
+ const mediaKey = Crypto.randomBytes(32);
312
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
313
+ const encWriteStream = new Readable({ read: () => {}, highWaterMark: 64 * 1024 });
314
+ let bodyPath;
315
+ let writeStream;
316
+ let didSaveToTmpPath = false;
317
+
318
+ if (type === 'file') {
319
+ bodyPath = media.url?.toString?.() || media.url;
320
+ } else if (saveOriginalFileIfRequired) {
321
+ bodyPath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2());
322
+ writeStream = createWriteStream(bodyPath);
323
+ didSaveToTmpPath = true;
324
+ }
325
+
326
+ let fileLength = 0;
327
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
328
+ let hmac = Crypto.createHmac('sha256', macKey).update(iv);
329
+ let sha256Plain = Crypto.createHash('sha256');
330
+ let sha256Enc = Crypto.createHash('sha256');
331
+
332
+ const onChunk = (buff) => {
333
+ sha256Enc = sha256Enc.update(buff);
334
+ hmac = hmac.update(buff);
335
+ encWriteStream.push(buff);
336
+ };
337
+
338
+ try {
339
+ for await (const data of finalStream) {
340
+ fileLength += data.length;
341
+ if (type === 'remote' &&
342
+ opts?.maxContentLength &&
343
+ fileLength + data.length > opts.maxContentLength) {
344
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
345
+ data: { media, type }
346
+ });
347
+ }
348
+ sha256Plain = sha256Plain.update(data);
349
+ if (writeStream) {
350
+ if (!writeStream.write(data)) {
351
+ await once(writeStream, 'drain');
352
+ }
353
+ }
354
+ onChunk(aes.update(data));
355
+ }
356
+
357
+ onChunk(aes.final());
358
+ const mac = hmac.digest().slice(0, 10);
359
+ sha256Enc = sha256Enc.update(mac);
360
+ const fileSha256 = sha256Plain.digest();
361
+ const fileEncSha256 = sha256Enc.digest();
362
+
363
+ encWriteStream.push(mac);
364
+ encWriteStream.push(null);
365
+ writeStream?.end();
366
+ if (writeStream) await once(writeStream, 'finish');
367
+ finalStream.destroy();
368
+
369
+ return {
370
+ mediaKey,
371
+ encWriteStream,
372
+ bodyPath,
373
+ mac,
374
+ fileEncSha256,
375
+ fileSha256,
376
+ fileLength,
377
+ didSaveToTmpPath,
378
+ opusConverted
379
+ };
380
+ } catch (error) {
381
+ encWriteStream.destroy();
382
+ writeStream?.destroy();
383
+ aes.destroy();
384
+ hmac.destroy();
385
+ sha256Plain.destroy();
386
+ sha256Enc.destroy();
387
+ stream.destroy();
388
+ if (didSaveToTmpPath) {
389
+ try { await fs.unlink(bodyPath); } catch (_) {}
390
+ }
391
+ throw error;
392
+ }
393
+ };
394
+ const DEF_HOST = 'mmg.whatsapp.net';
395
+ const AES_CHUNK_SIZE = 16;
396
+ const toSmallestChunkSize = (num) => {
397
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
398
+ };
399
+ export const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
400
+ export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
401
+ const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
402
+ const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
403
+ if (!downloadUrl) {
404
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
405
+ }
406
+ const keys = await getMediaKeys(mediaKey, type);
407
+ return downloadEncryptedContent(downloadUrl, keys, opts);
408
+ };
409
+ /**
410
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
411
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
412
+ * */
413
+ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
414
+ let bytesFetched = 0;
415
+ let startChunk = 0;
416
+ let firstBlockIsIV = false;
417
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
418
+ if (startByte) {
419
+ const chunk = toSmallestChunkSize(startByte || 0);
420
+ if (chunk) {
421
+ startChunk = chunk - AES_CHUNK_SIZE;
422
+ bytesFetched = chunk;
423
+ firstBlockIsIV = true;
424
+ }
425
+ }
426
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
427
+ const headersInit = options?.headers ? options.headers : undefined;
428
+ const headers = {
429
+ ...(headersInit
430
+ ? Array.isArray(headersInit)
431
+ ? Object.fromEntries(headersInit)
432
+ : headersInit
433
+ : {}),
434
+ Origin: DEFAULT_ORIGIN
435
+ };
436
+ if (startChunk || endChunk) {
437
+ headers.Range = `bytes=${startChunk}-`;
438
+ if (endChunk) {
439
+ headers.Range += endChunk;
440
+ }
441
+ }
442
+ // download the message
443
+ const fetched = await getHttpStream(downloadUrl, {
444
+ ...(options || {}),
445
+ headers
446
+ });
447
+ let remainingBytes = Buffer.from([]);
448
+ let aes;
449
+ const pushBytes = (bytes, push) => {
450
+ if (startByte || endByte) {
451
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
452
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
453
+ push(bytes.slice(start, end));
454
+ bytesFetched += bytes.length;
455
+ }
456
+ else {
457
+ push(bytes);
458
+ }
459
+ };
460
+ const output = new Transform({
461
+ transform(chunk, _, callback) {
462
+ let data = Buffer.concat([remainingBytes, chunk]);
463
+ const decryptLength = toSmallestChunkSize(data.length);
464
+ remainingBytes = data.slice(decryptLength);
465
+ data = data.slice(0, decryptLength);
466
+ if (!aes) {
467
+ let ivValue = iv;
468
+ if (firstBlockIsIV) {
469
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
470
+ data = data.slice(AES_CHUNK_SIZE);
471
+ }
472
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
473
+ // if an end byte that is not EOF is specified
474
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
475
+ if (endByte) {
476
+ aes.setAutoPadding(false);
477
+ }
478
+ }
479
+ try {
480
+ pushBytes(aes.update(data), b => this.push(b));
481
+ callback();
482
+ }
483
+ catch (error) {
484
+ callback(error);
485
+ }
486
+ },
487
+ final(callback) {
488
+ try {
489
+ pushBytes(aes.final(), b => this.push(b));
490
+ callback();
491
+ }
492
+ catch (error) {
493
+ callback(error);
494
+ }
495
+ }
496
+ });
497
+ return fetched.pipe(output, { end: true });
498
+ };
499
+ export function extensionForMediaMessage(message) {
500
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
501
+ const type = Object.keys(message)[0];
502
+ let extension;
503
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
504
+ extension = '.jpeg';
505
+ }
506
+ else {
507
+ const messageContent = message[type];
508
+ extension = getExtension(messageContent.mimetype);
509
+ }
510
+ return extension;
511
+ }
512
+ const isNodeRuntime = () => {
513
+ return (typeof process !== 'undefined' &&
514
+ process.versions?.node !== null &&
515
+ typeof process.versions.bun === 'undefined' &&
516
+ typeof globalThis.Deno === 'undefined');
517
+ };
518
+ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
519
+ if (redirectCount > 5) {
520
+ throw new Error('Too many redirects');
521
+ }
522
+ const parsedUrl = new URL(url);
523
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
524
+ // Get file size for Content-Length header (required for Node.js streaming)
525
+ const fileStats = await fs.stat(filePath);
526
+ const fileSize = fileStats.size;
527
+ return new Promise((resolve, reject) => {
528
+ const req = httpModule.request({
529
+ hostname: parsedUrl.hostname,
530
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
531
+ path: parsedUrl.pathname + parsedUrl.search,
532
+ method: 'POST',
533
+ headers: {
534
+ ...headers,
535
+ 'Content-Length': fileSize
536
+ },
537
+ agent,
538
+ timeout: timeoutMs
539
+ }, res => {
540
+ // Handle redirects (3xx)
541
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
542
+ res.resume(); // Consume response to free resources
543
+ const newUrl = new URL(res.headers.location, url).toString();
544
+ resolve(uploadWithNodeHttp({
545
+ url: newUrl,
546
+ filePath,
547
+ headers,
548
+ timeoutMs,
549
+ agent
550
+ }, redirectCount + 1));
551
+ return;
552
+ }
553
+ let body = '';
554
+ res.on('data', chunk => (body += chunk));
555
+ res.on('end', () => {
556
+ try {
557
+ resolve(JSON.parse(body));
558
+ }
559
+ catch {
560
+ resolve(undefined);
561
+ }
562
+ });
563
+ });
564
+ req.on('error', reject);
565
+ req.on('timeout', () => {
566
+ req.destroy();
567
+ reject(new Error('Upload timeout'));
568
+ });
569
+ const stream = createReadStream(filePath);
570
+ stream.pipe(req);
571
+ stream.on('error', err => {
572
+ req.destroy();
573
+ reject(err);
574
+ });
575
+ });
576
+ };
577
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
578
+ // Convert Node.js Readable to Web ReadableStream
579
+ const nodeStream = createReadStream(filePath);
580
+ const webStream = Readable.toWeb(nodeStream);
581
+ const response = await fetch(url, {
582
+ dispatcher: agent,
583
+ method: 'POST',
584
+ body: webStream,
585
+ headers,
586
+ duplex: 'half',
587
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
588
+ });
589
+ try {
590
+ return (await response.json());
591
+ }
592
+ catch {
593
+ return undefined;
594
+ }
595
+ };
596
+ /**
597
+ * Uploads media to WhatsApp servers.
598
+ *
599
+ * ## Why we have two upload implementations:
600
+ *
601
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
602
+ * the entire request body in memory before sending, even when using streams.
603
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
604
+ * See: https://github.com/nodejs/undici/issues/4058
605
+ *
606
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
607
+ * buffering, so we can use the web-standard Fetch API there.
608
+ *
609
+ * ## Future considerations:
610
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
611
+ * across all runtimes. Monitor the GitHub issue for updates.
612
+ */
613
+ const uploadMedia = async (params, logger) => {
614
+ if (isNodeRuntime()) {
615
+ return uploadWithNodeHttp(params);
616
+ }
617
+ else {
618
+ return uploadWithFetch(params);
619
+ }
620
+ };
621
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
622
+ return async (streamOrPath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
623
+ // send a query JSON to obtain the url & auth token to upload our media
624
+ let uploadInfo = await refreshMediaConn(false);
625
+ let urls;
626
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
627
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
628
+ // Prepare common headers
629
+ const customHeaders = (() => {
630
+ const hdrs = options?.headers;
631
+ if (!hdrs)
632
+ return {};
633
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
634
+ })();
635
+ const headers = {
636
+ ...customHeaders,
637
+ 'Content-Type': 'application/octet-stream',
638
+ Origin: DEFAULT_ORIGIN
639
+ };
640
+ // Collect buffer from Readable stream or read from file path
641
+ let reqBuffer;
642
+ if (Buffer.isBuffer(streamOrPath)) {
643
+ reqBuffer = streamOrPath;
644
+ } else if (typeof streamOrPath === 'string') {
645
+ reqBuffer = await fs.readFile(streamOrPath);
646
+ } else {
647
+ // Readable stream
648
+ const chunks = [];
649
+ for await (const chunk of streamOrPath) chunks.push(chunk);
650
+ reqBuffer = Buffer.concat(chunks);
651
+ }
652
+ // Newsletter uses different upload path
653
+ let mediaPath = MEDIA_PATH_MAP[mediaType];
654
+ if (newsletter) {
655
+ mediaPath = mediaPath?.replace('/mms/', '/newsletter/newsletter-');
656
+ }
657
+ for (const { hostname, maxContentLengthBytes } of hosts) {
658
+ const auth = encodeURIComponent(uploadInfo.auth);
659
+ const url = `https://${hostname}${mediaPath}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
660
+
661
+ let result;
662
+ try {
663
+ // Upload buffer directly like wiley (avoids file I/O issues)
664
+ const axios = (await import('axios')).default;
665
+ const body = await axios.post(url, reqBuffer, {
666
+ ...options,
667
+ headers: {
668
+ ...headers,
669
+ },
670
+ httpsAgent: fetchAgent,
671
+ timeout: timeoutMs,
672
+ responseType: 'json',
673
+ maxBodyLength: Infinity,
674
+ maxContentLength: Infinity,
675
+ });
676
+ result = body.data;
677
+
678
+ if (result?.url || result?.direct_path) {
679
+ urls = {
680
+ mediaUrl: result.url,
681
+ directPath: result.direct_path,
682
+ handle: result.handle,
683
+ meta_hmac: result.meta_hmac,
684
+ fbid: result.fbid,
685
+ ts: result.ts
686
+ };
687
+ break;
688
+ }
689
+ else {
690
+ uploadInfo = await refreshMediaConn(true);
691
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
692
+ }
693
+ }
694
+ catch (error) {
695
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
696
+
697
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
698
+ }
699
+ }
700
+ if (!urls) {
701
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
702
+ }
703
+ return urls;
704
+ };
705
+ };
706
+ const getMediaRetryKey = (mediaKey) => {
707
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
708
+ };
709
+ /**
710
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
711
+ */
712
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
713
+ const recp = { stanzaId: key.id };
714
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
715
+ const iv = Crypto.randomBytes(12);
716
+ const retryKey = getMediaRetryKey(mediaKey);
717
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
718
+ const req = {
719
+ tag: 'receipt',
720
+ attrs: {
721
+ id: key.id,
722
+ to: jidNormalizedUser(meId),
723
+ type: 'server-error'
724
+ },
725
+ content: [
726
+ // this encrypt node is actually pretty useless
727
+ // the media is returned even without this node
728
+ // keeping it here to maintain parity with WA Web
729
+ {
730
+ tag: 'encrypt',
731
+ attrs: {},
732
+ content: [
733
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
734
+ { tag: 'enc_iv', attrs: {}, content: iv }
735
+ ]
736
+ },
737
+ {
738
+ tag: 'rmr',
739
+ attrs: {
740
+ jid: key.remoteJid,
741
+ from_me: (!!key.fromMe).toString(),
742
+ // @ts-ignore
743
+ participant: key.participant || undefined
744
+ }
745
+ }
746
+ ]
747
+ };
748
+ return req;
749
+ };
750
+ export const decodeMediaRetryNode = (node) => {
751
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
752
+ const event = {
753
+ key: {
754
+ id: node.attrs.id,
755
+ remoteJid: rmrNode.attrs.jid,
756
+ fromMe: rmrNode.attrs.from_me === 'true',
757
+ participant: rmrNode.attrs.participant
758
+ }
759
+ };
760
+ const errorNode = getBinaryNodeChild(node, 'error');
761
+ if (errorNode) {
762
+ const errorCode = +errorNode.attrs.code;
763
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
764
+ data: errorNode.attrs,
765
+ statusCode: getStatusCodeForMediaRetry(errorCode)
766
+ });
767
+ }
768
+ else {
769
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
770
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
771
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
772
+ if (ciphertext && iv) {
773
+ event.media = { ciphertext, iv };
774
+ }
775
+ else {
776
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
777
+ }
778
+ }
779
+ return event;
780
+ };
781
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
782
+ const retryKey = getMediaRetryKey(mediaKey);
783
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
784
+ return proto.MediaRetryNotification.decode(plaintext);
785
+ };
786
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
787
+ const MEDIA_RETRY_STATUS_MAP = {
788
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
789
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
790
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
791
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
792
+ };
793
+
794
+ export const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
795
+ const { stream, type } = await getStream(media, opts);
796
+ let buffer = await toBuffer(stream);
797
+
798
+ let opusConverted = false;
799
+
800
+ let bodyPath;
801
+ let didSaveToTmpPath = false;
802
+ try {
803
+ if (type === 'file') {
804
+ bodyPath = media.url?.toString?.() || media.url;
805
+ } else if (saveOriginalFileIfRequired) {
806
+ bodyPath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2());
807
+ const { writeFileSync } = await import('fs');
808
+ writeFileSync(bodyPath, buffer);
809
+ didSaveToTmpPath = true;
810
+ }
811
+ const fileLength = buffer.length;
812
+ const fileSha256 = Crypto.createHash('sha256').update(buffer).digest();
813
+ return {
814
+ mediaKey: undefined,
815
+ encWriteStream: buffer,
816
+ fileLength,
817
+ fileSha256,
818
+ fileEncSha256: undefined,
819
+ bodyPath,
820
+ didSaveToTmpPath,
821
+ opusConverted
822
+ };
823
+ } catch (error) {
824
+ if (didSaveToTmpPath && bodyPath) {
825
+ try { await fs.unlink(bodyPath); } catch (_) {}
826
+ }
827
+ throw error;
828
+ }
829
+ };
830
+ //# sourceMappingURL=messages-media.js.map