@eduh_dev021/baileys 0.0.0-stage → 1.1.0

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 (526) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +1843 -2
  3. package/WAProto/index.d.ts +22220 -0
  4. package/WAProto/index.js +5 -0
  5. package/cjs/WAProto/index.d.ts +22220 -0
  6. package/cjs/WAProto/index.js +60125 -0
  7. package/cjs/engine-requirements.js +12 -0
  8. package/cjs/lib/Addon/cache.js +179 -0
  9. package/cjs/lib/Addon/crc32.js +41 -0
  10. package/cjs/lib/Addon/file-type.js +217 -0
  11. package/cjs/lib/Addon/get-file.js +99 -0
  12. package/cjs/lib/Addon/http-error.d.ts +18 -0
  13. package/cjs/lib/Addon/http-error.js +66 -0
  14. package/cjs/lib/Addon/index.d.ts +96 -0
  15. package/cjs/lib/Addon/index.js +58 -0
  16. package/cjs/lib/Addon/keyed-db.d.ts +14 -0
  17. package/cjs/lib/Addon/keyed-db.js +264 -0
  18. package/cjs/lib/Addon/link-preview.d.ts +15 -0
  19. package/cjs/lib/Addon/link-preview.js +104 -0
  20. package/cjs/lib/Addon/media-info.js +98 -0
  21. package/cjs/lib/Addon/mutex.js +78 -0
  22. package/cjs/lib/Addon/qr.js +464 -0
  23. package/cjs/lib/Addon/queue.js +54 -0
  24. package/cjs/lib/Addon/waveform.js +130 -0
  25. package/cjs/lib/Addon/zip.js +136 -0
  26. package/cjs/lib/Defaults/index.d.ts +184 -0
  27. package/cjs/lib/Defaults/index.js +292 -0
  28. package/cjs/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  29. package/cjs/lib/Signal/Group/ciphertext-message.js +37 -0
  30. package/cjs/lib/Signal/Group/group-cipher.d.ts +10 -0
  31. package/cjs/lib/Signal/Group/group-cipher.js +105 -0
  32. package/cjs/lib/Signal/Group/group-session-builder.d.ts +7 -0
  33. package/cjs/lib/Signal/Group/group-session-builder.js +65 -0
  34. package/cjs/lib/Signal/Group/index.d.ts +11 -0
  35. package/cjs/lib/Signal/Group/index.js +67 -0
  36. package/cjs/lib/Signal/Group/keyhelper.d.ts +6 -0
  37. package/cjs/lib/Signal/Group/keyhelper.js +47 -0
  38. package/cjs/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  39. package/cjs/lib/Signal/Group/sender-chain-key.js +51 -0
  40. package/cjs/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  41. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +80 -0
  42. package/cjs/lib/Signal/Group/sender-key-message.d.ts +18 -0
  43. package/cjs/lib/Signal/Group/sender-key-message.js +87 -0
  44. package/cjs/lib/Signal/Group/sender-key-name.d.ts +11 -0
  45. package/cjs/lib/Signal/Group/sender-key-name.js +73 -0
  46. package/cjs/lib/Signal/Group/sender-key-record.d.ts +12 -0
  47. package/cjs/lib/Signal/Group/sender-key-record.js +66 -0
  48. package/cjs/lib/Signal/Group/sender-key-state.d.ts +16 -0
  49. package/cjs/lib/Signal/Group/sender-key-state.js +106 -0
  50. package/cjs/lib/Signal/Group/sender-message-key.d.ts +11 -0
  51. package/cjs/lib/Signal/Group/sender-message-key.js +51 -0
  52. package/cjs/lib/Signal/libsignal.d.ts +54 -0
  53. package/cjs/lib/Signal/libsignal.js +421 -0
  54. package/cjs/lib/Signal/lid-mapping.d.ts +20 -0
  55. package/cjs/lib/Signal/lid-mapping.js +292 -0
  56. package/cjs/lib/Socket/Client/index.d.ts +2 -0
  57. package/cjs/lib/Socket/Client/index.js +23 -0
  58. package/cjs/lib/Socket/Client/types.d.ts +5 -0
  59. package/cjs/lib/Socket/Client/types.js +36 -0
  60. package/cjs/lib/Socket/Client/websocket.d.ts +12 -0
  61. package/cjs/lib/Socket/Client/websocket.js +143 -0
  62. package/cjs/lib/Socket/business.d.ts +387 -0
  63. package/cjs/lib/Socket/business.js +402 -0
  64. package/cjs/lib/Socket/chats.d.ts +144 -0
  65. package/cjs/lib/Socket/chats.js +1118 -0
  66. package/cjs/lib/Socket/communities.d.ts +554 -0
  67. package/cjs/lib/Socket/communities.js +456 -0
  68. package/cjs/lib/Socket/groups.d.ts +286 -0
  69. package/cjs/lib/Socket/groups.js +366 -0
  70. package/cjs/lib/Socket/index.d.ts +522 -0
  71. package/cjs/lib/Socket/index.js +32 -0
  72. package/cjs/lib/Socket/messages-recv.d.ts +326 -0
  73. package/cjs/lib/Socket/messages-recv.js +1670 -0
  74. package/cjs/lib/Socket/messages-send.d.ts +321 -0
  75. package/cjs/lib/Socket/messages-send.js +1252 -0
  76. package/cjs/lib/Socket/mex.d.ts +1 -0
  77. package/cjs/lib/Socket/mex.js +65 -0
  78. package/cjs/lib/Socket/newsletter.d.ts +283 -0
  79. package/cjs/lib/Socket/newsletter.js +243 -0
  80. package/cjs/lib/Socket/socket.d.ts +61 -0
  81. package/cjs/lib/Socket/socket.js +908 -0
  82. package/cjs/lib/Store/index.d.ts +3 -0
  83. package/cjs/lib/Store/index.js +25 -0
  84. package/cjs/lib/Store/make-in-memory-store.d.ts +63 -0
  85. package/cjs/lib/Store/make-in-memory-store.js +431 -0
  86. package/cjs/lib/Store/make-ordered-dictionary.d.ts +12 -0
  87. package/cjs/lib/Store/make-ordered-dictionary.js +101 -0
  88. package/cjs/lib/Store/object-repository.d.ts +10 -0
  89. package/cjs/lib/Store/object-repository.js +49 -0
  90. package/cjs/lib/Transport/crypto.d.ts +6 -0
  91. package/cjs/lib/Transport/crypto.js +107 -0
  92. package/cjs/lib/Transport/curve.d.ts +8 -0
  93. package/cjs/lib/Transport/curve.js +94 -0
  94. package/cjs/lib/Transport/index.d.ts +16 -0
  95. package/cjs/lib/Transport/index.js +67 -0
  96. package/cjs/lib/Transport/internals.d.ts +57 -0
  97. package/cjs/lib/Transport/internals.js +203 -0
  98. package/cjs/lib/Transport/session-builder.d.ts +40 -0
  99. package/cjs/lib/Transport/session-builder.js +169 -0
  100. package/cjs/lib/Transport/session-cipher.d.ts +26 -0
  101. package/cjs/lib/Transport/session-cipher.js +328 -0
  102. package/cjs/lib/Transport/session-record.d.ts +55 -0
  103. package/cjs/lib/Transport/session-record.js +289 -0
  104. package/cjs/lib/Types/Auth.d.ts +1 -0
  105. package/cjs/lib/Types/Auth.js +15 -0
  106. package/cjs/lib/Types/Bussines.d.ts +1 -0
  107. package/cjs/lib/Types/Bussines.js +15 -0
  108. package/cjs/lib/Types/Call.d.ts +1 -0
  109. package/cjs/lib/Types/Call.js +15 -0
  110. package/cjs/lib/Types/Chat.d.ts +1 -0
  111. package/cjs/lib/Types/Chat.js +33 -0
  112. package/cjs/lib/Types/Contact.d.ts +1 -0
  113. package/cjs/lib/Types/Contact.js +15 -0
  114. package/cjs/lib/Types/Events.d.ts +1 -0
  115. package/cjs/lib/Types/Events.js +1 -0
  116. package/cjs/lib/Types/GroupMetadata.d.ts +1 -0
  117. package/cjs/lib/Types/GroupMetadata.js +15 -0
  118. package/cjs/lib/Types/Label.d.ts +2 -0
  119. package/cjs/lib/Types/Label.js +49 -0
  120. package/cjs/lib/Types/LabelAssociation.d.ts +2 -0
  121. package/cjs/lib/Types/LabelAssociation.js +31 -0
  122. package/cjs/lib/Types/Message.d.ts +11 -0
  123. package/cjs/lib/Types/Message.js +58 -0
  124. package/cjs/lib/Types/Mex.d.ts +2 -0
  125. package/cjs/lib/Types/Mex.js +66 -0
  126. package/cjs/lib/Types/Product.d.ts +1 -0
  127. package/cjs/lib/Types/Product.js +15 -0
  128. package/cjs/lib/Types/RichType.d.ts +2 -0
  129. package/cjs/lib/Types/RichType.js +50 -0
  130. package/cjs/lib/Types/Signal.d.ts +1 -0
  131. package/cjs/lib/Types/Signal.js +1 -0
  132. package/cjs/lib/Types/Socket.d.ts +1 -0
  133. package/cjs/lib/Types/Socket.js +1 -0
  134. package/cjs/lib/Types/State.d.ts +5 -0
  135. package/cjs/lib/Types/State.js +83 -0
  136. package/cjs/lib/Types/USync.d.ts +1 -0
  137. package/cjs/lib/Types/USync.js +1 -0
  138. package/cjs/lib/Types/index.d.ts +13 -0
  139. package/cjs/lib/Types/index.js +64 -0
  140. package/cjs/lib/Utils/auth-utils.d.ts +58 -0
  141. package/cjs/lib/Utils/auth-utils.js +275 -0
  142. package/cjs/lib/Utils/browser-utils.d.ts +9 -0
  143. package/cjs/lib/Utils/browser-utils.js +56 -0
  144. package/cjs/lib/Utils/business.d.ts +49 -0
  145. package/cjs/lib/Utils/business.js +259 -0
  146. package/cjs/lib/Utils/chat-utils.d.ts +408 -0
  147. package/cjs/lib/Utils/chat-utils.js +821 -0
  148. package/cjs/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  149. package/cjs/lib/Utils/companion-reg-client-utils.js +71 -0
  150. package/cjs/lib/Utils/crypto.d.ts +39 -0
  151. package/cjs/lib/Utils/crypto.js +155 -0
  152. package/cjs/lib/Utils/decode-wa-message.d.ts +83 -0
  153. package/cjs/lib/Utils/decode-wa-message.js +316 -0
  154. package/cjs/lib/Utils/event-buffer.d.ts +12 -0
  155. package/cjs/lib/Utils/event-buffer.js +605 -0
  156. package/cjs/lib/Utils/generics.d.ts +63 -0
  157. package/cjs/lib/Utils/generics.js +440 -0
  158. package/cjs/lib/Utils/history.d.ts +75 -0
  159. package/cjs/lib/Utils/history.js +153 -0
  160. package/cjs/lib/Utils/identity-change-handler.d.ts +13 -0
  161. package/cjs/lib/Utils/identity-change-handler.js +73 -0
  162. package/cjs/lib/Utils/index.d.ts +24 -0
  163. package/cjs/lib/Utils/index.js +67 -0
  164. package/cjs/lib/Utils/link-preview.d.ts +13 -0
  165. package/cjs/lib/Utils/link-preview.js +87 -0
  166. package/cjs/lib/Utils/logger.d.ts +12 -0
  167. package/cjs/lib/Utils/logger.js +40 -0
  168. package/cjs/lib/Utils/lt-hash.d.ts +6 -0
  169. package/cjs/lib/Utils/lt-hash.js +28 -0
  170. package/cjs/lib/Utils/make-mutex.d.ts +6 -0
  171. package/cjs/lib/Utils/make-mutex.js +58 -0
  172. package/cjs/lib/Utils/message-retry-manager.d.ts +79 -0
  173. package/cjs/lib/Utils/message-retry-manager.js +274 -0
  174. package/cjs/lib/Utils/messages-media.d.ts +134 -0
  175. package/cjs/lib/Utils/messages-media.js +799 -0
  176. package/cjs/lib/Utils/messages.d.ts +47 -0
  177. package/cjs/lib/Utils/messages.js +1667 -0
  178. package/cjs/lib/Utils/noise-handler.d.ts +20 -0
  179. package/cjs/lib/Utils/noise-handler.js +223 -0
  180. package/cjs/lib/Utils/offline-node-processor.d.ts +10 -0
  181. package/cjs/lib/Utils/offline-node-processor.js +60 -0
  182. package/cjs/lib/Utils/pre-key-manager.d.ts +25 -0
  183. package/cjs/lib/Utils/pre-key-manager.js +116 -0
  184. package/cjs/lib/Utils/process-message.d.ts +83 -0
  185. package/cjs/lib/Utils/process-message.js +607 -0
  186. package/cjs/lib/Utils/reporting-utils.d.ts +12 -0
  187. package/cjs/lib/Utils/reporting-utils.js +282 -0
  188. package/cjs/lib/Utils/rich-message-utils.d.ts +48 -0
  189. package/cjs/lib/Utils/rich-message-utils.js +381 -0
  190. package/cjs/lib/Utils/signal.d.ts +82 -0
  191. package/cjs/lib/Utils/signal.js +232 -0
  192. package/cjs/lib/Utils/stanza-ack.d.ts +16 -0
  193. package/cjs/lib/Utils/stanza-ack.js +53 -0
  194. package/cjs/lib/Utils/sync-action-utils.d.ts +2 -0
  195. package/cjs/lib/Utils/sync-action-utils.js +68 -0
  196. package/cjs/lib/Utils/tc-token-utils.d.ts +29 -0
  197. package/cjs/lib/Utils/tc-token-utils.js +182 -0
  198. package/cjs/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  199. package/cjs/lib/Utils/use-multi-file-auth-state.js +135 -0
  200. package/cjs/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  201. package/cjs/lib/Utils/use-single-file-auth-state.js +115 -0
  202. package/cjs/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  203. package/cjs/lib/Utils/use-sqlite-auth-state.js +140 -0
  204. package/cjs/lib/Utils/validate-connection.d.ts +44 -0
  205. package/cjs/lib/Utils/validate-connection.js +229 -0
  206. package/cjs/lib/WABinary/constants.d.ts +61 -0
  207. package/cjs/lib/WABinary/constants.js +1992 -0
  208. package/cjs/lib/WABinary/decode.d.ts +9 -0
  209. package/cjs/lib/WABinary/decode.js +292 -0
  210. package/cjs/lib/WABinary/encode.d.ts +2 -0
  211. package/cjs/lib/WABinary/encode.js +240 -0
  212. package/cjs/lib/WABinary/generic-utils.d.ts +79 -0
  213. package/cjs/lib/WABinary/generic-utils.js +252 -0
  214. package/cjs/lib/WABinary/index.d.ts +5 -0
  215. package/cjs/lib/WABinary/index.js +29 -0
  216. package/cjs/lib/WABinary/jid-utils.d.ts +28 -0
  217. package/cjs/lib/WABinary/jid-utils.js +151 -0
  218. package/cjs/lib/WABinary/types.d.ts +1 -0
  219. package/cjs/lib/WABinary/types.js +23 -0
  220. package/cjs/lib/WACrypto/appstate-keys.js +39 -0
  221. package/cjs/lib/WACrypto/curves/constants.js +37 -0
  222. package/cjs/lib/WACrypto/hkdf.js +38 -0
  223. package/cjs/lib/WACrypto/index.js +51 -0
  224. package/cjs/lib/WACrypto/lthash.js +59 -0
  225. package/cjs/lib/WACrypto/math/constants.js +53 -0
  226. package/cjs/lib/WACrypto/math/edwards.js +206 -0
  227. package/cjs/lib/WACrypto/math/fe.js +449 -0
  228. package/cjs/lib/WACrypto/math/le.js +44 -0
  229. package/cjs/lib/WACrypto/math/mod.js +36 -0
  230. package/cjs/lib/WACrypto/util/bytes.js +348 -0
  231. package/cjs/lib/WACrypto/x25519.js +157 -0
  232. package/cjs/lib/WACrypto/xeddsa.js +134 -0
  233. package/cjs/lib/WAM/BinaryInfo.d.ts +7 -0
  234. package/cjs/lib/WAM/BinaryInfo.js +35 -0
  235. package/cjs/lib/WAM/constants.d.ts +34926 -0
  236. package/cjs/lib/WAM/constants.js +22890 -0
  237. package/cjs/lib/WAM/encode.d.ts +1 -0
  238. package/cjs/lib/WAM/encode.js +162 -0
  239. package/cjs/lib/WAM/index.d.ts +3 -0
  240. package/cjs/lib/WAM/index.js +25 -0
  241. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  242. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +77 -0
  243. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  244. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +76 -0
  245. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  246. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +52 -0
  247. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  248. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +61 -0
  249. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  250. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +50 -0
  251. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  252. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +76 -0
  253. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  254. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +53 -0
  255. package/cjs/lib/WAUSync/Protocols/index.d.ts +5 -0
  256. package/cjs/lib/WAUSync/Protocols/index.js +29 -0
  257. package/cjs/lib/WAUSync/USyncQuery.d.ts +20 -0
  258. package/cjs/lib/WAUSync/USyncQuery.js +113 -0
  259. package/cjs/lib/WAUSync/USyncUser.d.ts +16 -0
  260. package/cjs/lib/WAUSync/USyncUser.js +56 -0
  261. package/cjs/lib/WAUSync/index.d.ts +3 -0
  262. package/cjs/lib/WAUSync/index.js +25 -0
  263. package/cjs/lib/index.d.ts +11 -0
  264. package/cjs/lib/index.js +56 -0
  265. package/cjs/package.json +3 -0
  266. package/engine-requirements.js +12 -0
  267. package/lib/Addon/cache.js +201 -0
  268. package/lib/Addon/crc32.js +21 -0
  269. package/lib/Addon/file-type.js +198 -0
  270. package/lib/Addon/get-file.js +98 -0
  271. package/lib/Addon/http-error.d.ts +18 -0
  272. package/lib/Addon/http-error.js +40 -0
  273. package/lib/Addon/index.d.ts +96 -0
  274. package/lib/Addon/index.js +26 -0
  275. package/lib/Addon/keyed-db.d.ts +14 -0
  276. package/lib/Addon/keyed-db.js +241 -0
  277. package/lib/Addon/link-preview.d.ts +15 -0
  278. package/lib/Addon/link-preview.js +79 -0
  279. package/lib/Addon/media-info.js +96 -0
  280. package/lib/Addon/mutex.js +76 -0
  281. package/lib/Addon/qr.js +531 -0
  282. package/lib/Addon/queue.js +44 -0
  283. package/lib/Addon/waveform.js +135 -0
  284. package/lib/Addon/zip.js +144 -0
  285. package/lib/Defaults/index.d.ts +184 -0
  286. package/lib/Defaults/index.js +181 -0
  287. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  288. package/lib/Signal/Group/ciphertext-message.js +11 -0
  289. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  290. package/lib/Signal/Group/group-cipher.js +81 -0
  291. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  292. package/lib/Signal/Group/group-session-builder.js +29 -0
  293. package/lib/Signal/Group/index.d.ts +11 -0
  294. package/lib/Signal/Group/index.js +11 -0
  295. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  296. package/lib/Signal/Group/keyhelper.js +17 -0
  297. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  298. package/lib/Signal/Group/sender-chain-key.js +25 -0
  299. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  300. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  301. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  302. package/lib/Signal/Group/sender-key-message.js +65 -0
  303. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  304. package/lib/Signal/Group/sender-key-name.js +47 -0
  305. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  306. package/lib/Signal/Group/sender-key-record.js +40 -0
  307. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  308. package/lib/Signal/Group/sender-key-state.js +83 -0
  309. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  310. package/lib/Signal/Group/sender-message-key.js +25 -0
  311. package/lib/Signal/libsignal.d.ts +54 -0
  312. package/lib/Signal/libsignal.js +426 -0
  313. package/lib/Signal/lid-mapping.d.ts +20 -0
  314. package/lib/Signal/lid-mapping.js +274 -0
  315. package/lib/Socket/Client/index.d.ts +2 -0
  316. package/lib/Socket/Client/index.js +2 -0
  317. package/lib/Socket/Client/types.d.ts +5 -0
  318. package/lib/Socket/Client/types.js +10 -0
  319. package/lib/Socket/Client/websocket.d.ts +12 -0
  320. package/lib/Socket/Client/websocket.js +119 -0
  321. package/lib/Socket/business.d.ts +387 -0
  322. package/lib/Socket/business.js +379 -0
  323. package/lib/Socket/chats.d.ts +144 -0
  324. package/lib/Socket/chats.js +1216 -0
  325. package/lib/Socket/communities.d.ts +554 -0
  326. package/lib/Socket/communities.js +431 -0
  327. package/lib/Socket/groups.d.ts +286 -0
  328. package/lib/Socket/groups.js +347 -0
  329. package/lib/Socket/index.d.ts +522 -0
  330. package/lib/Socket/index.js +11 -0
  331. package/lib/Socket/messages-recv.d.ts +326 -0
  332. package/lib/Socket/messages-recv.js +1822 -0
  333. package/lib/Socket/messages-send.d.ts +321 -0
  334. package/lib/Socket/messages-send.js +1378 -0
  335. package/lib/Socket/mex.d.ts +1 -0
  336. package/lib/Socket/mex.js +41 -0
  337. package/lib/Socket/newsletter.d.ts +283 -0
  338. package/lib/Socket/newsletter.js +225 -0
  339. package/lib/Socket/socket.d.ts +61 -0
  340. package/lib/Socket/socket.js +992 -0
  341. package/lib/Store/index.d.ts +3 -0
  342. package/lib/Store/index.js +3 -0
  343. package/lib/Store/make-in-memory-store.d.ts +63 -0
  344. package/lib/Store/make-in-memory-store.js +419 -0
  345. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  346. package/lib/Store/make-ordered-dictionary.js +78 -0
  347. package/lib/Store/object-repository.d.ts +10 -0
  348. package/lib/Store/object-repository.js +23 -0
  349. package/lib/Transport/crypto.d.ts +6 -0
  350. package/lib/Transport/crypto.js +61 -0
  351. package/lib/Transport/curve.d.ts +8 -0
  352. package/lib/Transport/curve.js +66 -0
  353. package/lib/Transport/index.d.ts +16 -0
  354. package/lib/Transport/index.js +9 -0
  355. package/lib/Transport/internals.d.ts +57 -0
  356. package/lib/Transport/internals.js +155 -0
  357. package/lib/Transport/session-builder.d.ts +40 -0
  358. package/lib/Transport/session-builder.js +143 -0
  359. package/lib/Transport/session-cipher.d.ts +26 -0
  360. package/lib/Transport/session-cipher.js +301 -0
  361. package/lib/Transport/session-record.d.ts +55 -0
  362. package/lib/Transport/session-record.js +272 -0
  363. package/lib/Types/Auth.d.ts +1 -0
  364. package/lib/Types/Auth.js +1 -0
  365. package/lib/Types/Bussines.d.ts +1 -0
  366. package/lib/Types/Bussines.js +1 -0
  367. package/lib/Types/Call.d.ts +1 -0
  368. package/lib/Types/Call.js +1 -0
  369. package/lib/Types/Chat.d.ts +1 -0
  370. package/lib/Types/Chat.js +7 -0
  371. package/lib/Types/Contact.d.ts +1 -0
  372. package/lib/Types/Contact.js +1 -0
  373. package/lib/Types/Events.d.ts +1 -0
  374. package/lib/Types/Events.js +1 -0
  375. package/lib/Types/GroupMetadata.d.ts +1 -0
  376. package/lib/Types/GroupMetadata.js +1 -0
  377. package/lib/Types/Label.d.ts +2 -0
  378. package/lib/Types/Label.js +24 -0
  379. package/lib/Types/LabelAssociation.d.ts +2 -0
  380. package/lib/Types/LabelAssociation.js +6 -0
  381. package/lib/Types/Message.d.ts +11 -0
  382. package/lib/Types/Message.js +17 -0
  383. package/lib/Types/Mex.d.ts +2 -0
  384. package/lib/Types/Mex.js +38 -0
  385. package/lib/Types/Product.d.ts +1 -0
  386. package/lib/Types/Product.js +1 -0
  387. package/lib/Types/RichType.d.ts +2 -0
  388. package/lib/Types/RichType.js +22 -0
  389. package/lib/Types/Signal.d.ts +1 -0
  390. package/lib/Types/Signal.js +1 -0
  391. package/lib/Types/Socket.d.ts +1 -0
  392. package/lib/Types/Socket.js +1 -0
  393. package/lib/Types/State.d.ts +5 -0
  394. package/lib/Types/State.js +54 -0
  395. package/lib/Types/USync.d.ts +1 -0
  396. package/lib/Types/USync.js +1 -0
  397. package/lib/Types/index.d.ts +13 -0
  398. package/lib/Types/index.js +25 -0
  399. package/lib/Utils/auth-utils.d.ts +58 -0
  400. package/lib/Utils/auth-utils.js +316 -0
  401. package/lib/Utils/browser-utils.d.ts +9 -0
  402. package/lib/Utils/browser-utils.js +28 -0
  403. package/lib/Utils/business.d.ts +49 -0
  404. package/lib/Utils/business.js +230 -0
  405. package/lib/Utils/chat-utils.d.ts +408 -0
  406. package/lib/Utils/chat-utils.js +871 -0
  407. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  408. package/lib/Utils/companion-reg-client-utils.js +39 -0
  409. package/lib/Utils/crypto.d.ts +39 -0
  410. package/lib/Utils/crypto.js +117 -0
  411. package/lib/Utils/decode-wa-message.d.ts +83 -0
  412. package/lib/Utils/decode-wa-message.js +316 -0
  413. package/lib/Utils/event-buffer.d.ts +12 -0
  414. package/lib/Utils/event-buffer.js +621 -0
  415. package/lib/Utils/generics.d.ts +63 -0
  416. package/lib/Utils/generics.js +394 -0
  417. package/lib/Utils/history.d.ts +75 -0
  418. package/lib/Utils/history.js +133 -0
  419. package/lib/Utils/identity-change-handler.d.ts +13 -0
  420. package/lib/Utils/identity-change-handler.js +48 -0
  421. package/lib/Utils/index.d.ts +24 -0
  422. package/lib/Utils/index.js +24 -0
  423. package/lib/Utils/link-preview.d.ts +13 -0
  424. package/lib/Utils/link-preview.js +73 -0
  425. package/lib/Utils/logger.d.ts +12 -0
  426. package/lib/Utils/logger.js +12 -0
  427. package/lib/Utils/lt-hash.d.ts +6 -0
  428. package/lib/Utils/lt-hash.js +7 -0
  429. package/lib/Utils/make-mutex.d.ts +6 -0
  430. package/lib/Utils/make-mutex.js +32 -0
  431. package/lib/Utils/message-retry-manager.d.ts +79 -0
  432. package/lib/Utils/message-retry-manager.js +259 -0
  433. package/lib/Utils/messages-media.d.ts +134 -0
  434. package/lib/Utils/messages-media.js +802 -0
  435. package/lib/Utils/messages.d.ts +47 -0
  436. package/lib/Utils/messages.js +1907 -0
  437. package/lib/Utils/noise-handler.d.ts +20 -0
  438. package/lib/Utils/noise-handler.js +200 -0
  439. package/lib/Utils/offline-node-processor.d.ts +10 -0
  440. package/lib/Utils/offline-node-processor.js +40 -0
  441. package/lib/Utils/pre-key-manager.d.ts +25 -0
  442. package/lib/Utils/pre-key-manager.js +105 -0
  443. package/lib/Utils/process-message.d.ts +83 -0
  444. package/lib/Utils/process-message.js +748 -0
  445. package/lib/Utils/reporting-utils.d.ts +12 -0
  446. package/lib/Utils/reporting-utils.js +257 -0
  447. package/lib/Utils/rich-message-utils.d.ts +48 -0
  448. package/lib/Utils/rich-message-utils.js +366 -0
  449. package/lib/Utils/signal.d.ts +82 -0
  450. package/lib/Utils/signal.js +200 -0
  451. package/lib/Utils/stanza-ack.d.ts +16 -0
  452. package/lib/Utils/stanza-ack.js +37 -0
  453. package/lib/Utils/sync-action-utils.d.ts +2 -0
  454. package/lib/Utils/sync-action-utils.js +48 -0
  455. package/lib/Utils/tc-token-utils.d.ts +29 -0
  456. package/lib/Utils/tc-token-utils.js +163 -0
  457. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  458. package/lib/Utils/use-multi-file-auth-state.js +116 -0
  459. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  460. package/lib/Utils/use-single-file-auth-state.js +94 -0
  461. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  462. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  463. package/lib/Utils/validate-connection.d.ts +44 -0
  464. package/lib/Utils/validate-connection.js +210 -0
  465. package/lib/WABinary/constants.d.ts +61 -0
  466. package/lib/WABinary/constants.js +1466 -0
  467. package/lib/WABinary/decode.d.ts +9 -0
  468. package/lib/WABinary/decode.js +261 -0
  469. package/lib/WABinary/encode.d.ts +2 -0
  470. package/lib/WABinary/encode.js +219 -0
  471. package/lib/WABinary/generic-utils.d.ts +79 -0
  472. package/lib/WABinary/generic-utils.js +226 -0
  473. package/lib/WABinary/index.d.ts +5 -0
  474. package/lib/WABinary/index.js +5 -0
  475. package/lib/WABinary/jid-utils.d.ts +28 -0
  476. package/lib/WABinary/jid-utils.js +95 -0
  477. package/lib/WABinary/types.d.ts +1 -0
  478. package/lib/WABinary/types.js +1 -0
  479. package/lib/WACrypto/appstate-keys.js +26 -0
  480. package/lib/WACrypto/curves/constants.js +12 -0
  481. package/lib/WACrypto/hkdf.js +27 -0
  482. package/lib/WACrypto/index.js +20 -0
  483. package/lib/WACrypto/lthash.js +54 -0
  484. package/lib/WACrypto/math/constants.js +24 -0
  485. package/lib/WACrypto/math/edwards.js +194 -0
  486. package/lib/WACrypto/math/fe.js +698 -0
  487. package/lib/WACrypto/math/le.js +23 -0
  488. package/lib/WACrypto/math/mod.js +15 -0
  489. package/lib/WACrypto/util/bytes.js +339 -0
  490. package/lib/WACrypto/x25519.js +145 -0
  491. package/lib/WACrypto/xeddsa.js +92 -0
  492. package/lib/WAM/BinaryInfo.d.ts +7 -0
  493. package/lib/WAM/BinaryInfo.js +9 -0
  494. package/lib/WAM/constants.d.ts +34926 -0
  495. package/lib/WAM/constants.js +22852 -0
  496. package/lib/WAM/encode.d.ts +1 -0
  497. package/lib/WAM/encode.js +149 -0
  498. package/lib/WAM/index.d.ts +3 -0
  499. package/lib/WAM/index.js +3 -0
  500. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  501. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  502. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  503. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  504. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  505. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  506. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  507. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  508. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  509. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  510. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  511. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  512. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  513. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  514. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  515. package/lib/WAUSync/Protocols/index.js +5 -0
  516. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  517. package/lib/WAUSync/USyncQuery.js +97 -0
  518. package/lib/WAUSync/USyncUser.d.ts +16 -0
  519. package/lib/WAUSync/USyncUser.js +30 -0
  520. package/lib/WAUSync/index.d.ts +3 -0
  521. package/lib/WAUSync/index.js +3 -0
  522. package/lib/index.d.ts +11 -0
  523. package/lib/index.js +11 -0
  524. package/package.json +74 -5
  525. package/tests/addon-test.mjs +162 -0
  526. package/tests/differential-test.mjs +90 -0
package/README.md CHANGED
@@ -1,3 +1,1844 @@
1
- # Temporary Holding Version
1
+ # @eduh_dev021/baileys
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ![npm version](https://img.shields.io/npm/v/@eduh_dev021/baileys)
4
+ ![node version](https://img.shields.io/node/v/@eduh_dev021/baileys)
5
+ ![license](https://img.shields.io/npm/l/@eduh_dev021/baileys)
6
+ ![downloads](https://img.shields.io/npm/dm/@eduh_dev021/baileys)
7
+ ![builds](https://img.shields.io/badge/builds-ESM%20%2B%20CJS-blue)
8
+
9
+ **A complete, production-grade WhatsApp Web library for Node.js.** No browser. No WhatsApp Business API. No WASM binaries. **Zero runtime dependencies.** Connect with a QR code or a pairing code and automate everything WhatsApp can do: text, media, stickers, albums, interactive buttons, carousels, native flows, rich messages, polls, events, groups, communities, channels, business tools and more.
10
+
11
+ Built as a drop-in replacement for the Baileys v7 API — if your code works with Baileys-style libraries, it works here by changing only the import line. Every internal dependency (crypto, QR, ZIP, media probing, caching, locking) is implemented in pure JavaScript inside the package, so `npm install` pulls no binaries and no transitive packages.
12
+
13
+ ```bash
14
+ npm install @eduh_dev021/baileys
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Table of contents
20
+
21
+ - [Features](#features)
22
+ - [Requirements](#requirements)
23
+ - [Installation](#installation)
24
+ - [Quick start](#quick-start-connect-to-whatsapp)
25
+ - [Saving your session (auth state)](#saving-your-session-auth-state)
26
+ - [JSON folder](#usemultifileauthstatefolder--json-folder)
27
+ - [Single JSON file](#usesinglefileauthstatefilename--one-json-file)
28
+ - [SQLite](#usesqliteauthstatedbpath-owneddatabase--sqlite)
29
+ - [Any other database (MySQL, PostgreSQL, MongoDB, Redis...)](#any-other-database-mysql-postgresql-mongodb-redis)
30
+ - [The store (`makeInMemoryStore`)](#the-store-makeinmemorystore)
31
+ - [Persisting to JSON](#persisting-the-store-to-a-json-file)
32
+ - [Persisting to SQL / any database](#persisting-the-store-to-sql-or-any-other-database)
33
+ - [Store API](#everything-the-store-offers)
34
+ - [Socket configuration](#socket-configuration-makewasocket-options)
35
+ - [WhatsApp IDs (JID and LID)](#whatsapp-ids-jid-and-lid)
36
+ - [Sending messages](#sending-messages)
37
+ - [Text and formatting](#text)
38
+ - [Rich messages (code blocks, tables, LaTeX)](#rich-messages-code-blocks-tables-latex)
39
+ - [Media](#sending-media)
40
+ - [Sticker packs and albums](#sticker-pack)
41
+ - [Interactive: buttons, lists, template, native flow, carousel](#interactive-messages)
42
+ - [Other message options (AI icon, spoiler, view once...)](#other-message-options)
43
+ - [Status mentions](#status-mentions)
44
+ - [Commerce: product, order, invoice, payments](#commerce-messages)
45
+ - [Polls](#poll)
46
+ - [Phone number and privacy messages](#phone-number-and-privacy-messages)
47
+ - [Modifying messages](#modifying-messages)
48
+ - [Receiving messages and downloading media](#receiving-messages-and-downloading-media)
49
+ - [Events](#everything-you-can-listen-to-events)
50
+ - [Socket method reference](#complete-socket-method-reference)
51
+ - [Practical guides](#practical-guides)
52
+ - [Find User ID (PN/LID)](#find-user-id-pnlid)
53
+ - [Image processing](#image-processing)
54
+ - [Add-on utilities](#add-on-utilities)
55
+ - [Export reference](#complete-export-reference)
56
+ - [Common problems](#common-problems)
57
+ - [License](#license)
58
+
59
+ ## Features
60
+
61
+ | Area | What you get |
62
+ | --- | --- |
63
+ | **Connection** | QR code or pairing code login, auto-reconnect handling, pre-key rotation, session recreation |
64
+ | **Messages** | Text with formatting, mentions (`@jid` and @all), link previews, replies, forwards, edits, deletes, reactions, pins, view-once |
65
+ | **Rich messages** | Code blocks with syntax highlighting, tables, LaTeX, inline images, content carousels — rendered natively by WhatsApp |
66
+ | **Interactive** | Buttons, lists, hydrated templates, native flows (single select, offers, bottom sheets), carousels with cards |
67
+ | **Media** | Images, videos, voice notes (PTT), documents, stickers, sticker packs (up to 60), albums |
68
+ | **Commerce** | Products, orders, invoices, payment requests, payment invites, storefronts |
69
+ | **Polls** | Create polls, receive votes, aggregate results, send result snapshots |
70
+ | **Groups** | Create, invite codes, participants, settings, join requests, ephemeral timers |
71
+ | **Communities** | Create, link/unlink groups, member management, invite codes |
72
+ | **Channels** | Create and manage newsletters, reactions, subscribers, admin tools |
73
+ | **Calls** | Reject calls, create call links, call privacy |
74
+ | **Presence** | Online/typing/recording status, read receipts |
75
+ | **Privacy** | Full control of every privacy setting via API |
76
+ | **Storage** | Auth state in JSON folder / single file / SQLite / your own database; in-memory store with JSON or SQL persistence |
77
+ | **Built-in utilities** | QR generator (terminal + PNG), ZIP builder, file-type detection, media probing, audio waveform, TTL cache, mutex, task queue — all self-contained |
78
+ | **Developer experience** | 100% TypeScript, ESM + CommonJS builds, zero WASM binaries, zero runtime dependencies, no native code required |
79
+
80
+ ## Requirements
81
+
82
+ - **Node.js 20 or newer** (Node 22/24 recommended — SQLite auth state needs 22.13+ for the built-in driver)
83
+ - **ffmpeg + ffprobe** on the system PATH for video/audio thumbnails, waveforms and animated stickers
84
+
85
+ Optional peer dependencies, installed only if you use the related feature:
86
+
87
+ | Package | Needed for |
88
+ | --- | --- |
89
+ | `ws` | WebSocket client on Node.js below 22 (install unless you are sure you don't need it) |
90
+ | `sharp` / `jimp` / `@napi-rs/image` | Thumbnail and image processing (install at least one) |
91
+ | `better-sqlite3` | `useSqliteAuthState` on Node.js below 22.13 |
92
+
93
+ Simplest setup for most users:
94
+
95
+ ```bash
96
+ npm install @eduh_dev021/baileys ws sharp
97
+ ```
98
+
99
+ ## Installation
100
+
101
+ ```bash
102
+ # npm
103
+ npm install @eduh_dev021/baileys
104
+
105
+ # yarn
106
+ yarn add @eduh_dev021/baileys
107
+
108
+ # pnpm
109
+ pnpm add @eduh_dev021/baileys
110
+
111
+ # bun
112
+ bun add @eduh_dev021/baileys
113
+ ```
114
+
115
+ ### Importing
116
+
117
+ ```javascript
118
+ // --- ESM (import)
119
+ import { makeWASocket } from '@eduh_dev021/baileys'
120
+
121
+ // --- CommonJS (require)
122
+ const { makeWASocket } = require('@eduh_dev021/baileys')
123
+ ```
124
+
125
+ `makeWASocket` is also the default export, so `import makeWASocket from '@eduh_dev021/baileys'` works too. TypeScript types ship inside the package.
126
+
127
+ ## Quick start: connect to WhatsApp
128
+
129
+ This complete example connects using a **pairing code** and answers incoming messages automatically:
130
+
131
+ ```javascript
132
+ import {
133
+ makeWASocket,
134
+ useMultiFileAuthState,
135
+ delay,
136
+ DisconnectReason
137
+ } from '@eduh_dev021/baileys'
138
+
139
+ const myPhoneNumber = '5511999999999' // your number, country code + DDD, no + or spaces
140
+
141
+ const connectToWhatsApp = async () => {
142
+ const { state, saveCreds } = await useMultiFileAuthState('session')
143
+
144
+ const sock = makeWASocket({
145
+ auth: state,
146
+ printQRInTerminal: true // prints the pairing QR in the terminal (built-in, no extra package)
147
+ })
148
+
149
+ sock.ev.on('creds.update', saveCreds)
150
+
151
+ sock.ev.on('connection.update', async (update) => {
152
+ const { connection, lastDisconnect, qr } = update
153
+
154
+ if (qr && !sock.authState.creds.registered) {
155
+ await delay(1500)
156
+ const code = await sock.requestPairingCode(myPhoneNumber)
157
+ console.log('Pairing code:', code)
158
+ }
159
+
160
+ if (connection === 'close') {
161
+ const shouldReconnect =
162
+ lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut
163
+ if (shouldReconnect) connectToWhatsApp()
164
+ }
165
+
166
+ if (connection === 'open') {
167
+ console.log('Connected to WhatsApp!')
168
+ }
169
+ })
170
+
171
+ sock.ev.on('messages.upsert', async ({ messages }) => {
172
+ for (const message of messages) {
173
+ if (!message.message) continue // ignore status and empty messages
174
+ await sock.sendMessage(message.key.remoteJid, { text: 'Hello! 👋' })
175
+ }
176
+ })
177
+ }
178
+
179
+ connectToWhatsApp()
180
+ ```
181
+
182
+ The first run asks WhatsApp for a pairing code. Type it on your phone (Linked devices → Link a device → **Link with phone number instead**). After that, the `session` folder keeps you logged in.
183
+
184
+ Prefer a QR code? Just remove the pairing-code block and set `printQRInTerminal: true` — the QR generator is built into the package, no extra install needed. A custom, easier-to-type pairing code is also supported:
185
+
186
+ ```javascript
187
+ await sock.requestPairingCode(myPhoneNumber, 'MYBOT123')
188
+ ```
189
+
190
+ ---
191
+
192
+ # Saving your session (auth state)
193
+
194
+ The auth state holds your login credentials and encryption keys. Three ready-made storages are included — JSON (folder), JSON (single file) and SQLite — plus a simple interface you can implement to store everything in **any other database**: MySQL, PostgreSQL, MongoDB, Redis, DynamoDB, whatever you like.
195
+
196
+ | Helper | Storage | Needs extra package? | Best for |
197
+ | --- | --- | --- | --- |
198
+ | `useMultiFileAuthState` | one JSON file per key, inside a folder | No | General use (most common) |
199
+ | `useSingleFileAuthState` | everything in one JSON file | No | Simple bots, easy backup |
200
+ | `useSqliteAuthState` | an SQLite database | No on Node 22.13+/Bun; `better-sqlite3` otherwise | Performance and reliability |
201
+ | your own adapter | any database | your DB driver | Big bots, existing infrastructure |
202
+
203
+ All of them return an object with `state` and `saveCreds`. Always connect `saveCreds` to the `creds.update` event — that is what keeps the session saved between restarts:
204
+
205
+ ```javascript
206
+ sock.ev.on('creds.update', saveCreds)
207
+ ```
208
+
209
+ ### `useMultiFileAuthState(folder)` — JSON folder
210
+
211
+ ```javascript
212
+ import { useMultiFileAuthState } from '@eduh_dev021/baileys'
213
+
214
+ const { state, saveCreds } = await useMultiFileAuthState('session')
215
+ ```
216
+
217
+ Saves the credentials and each set of Signal keys as separate JSON files inside `session/`. Easy to inspect and back up.
218
+
219
+ ### `useSingleFileAuthState(fileName)` — one JSON file
220
+
221
+ ```javascript
222
+ import { useSingleFileAuthState } from '@eduh_dev021/baileys'
223
+
224
+ const { state, saveCreds, flush } = await useSingleFileAuthState('session.json')
225
+ ```
226
+
227
+ Everything lives in a single file. Writes are **debounced and atomic** (written to a `.temp` file first, then renamed), so the file never gets corrupted if the process dies. A corrupted file found at startup is automatically renamed to `session.json.corrupt` and a fresh session starts.
228
+
229
+ Two extras:
230
+
231
+ - `await flush()` forces the pending write to disk right away — call it on process exit (`process.on('SIGINT', ...)`) so nothing is lost.
232
+ - If two sockets use the same file name, they share one mutex automatically, so concurrent writes are safe.
233
+
234
+ ### `useSqliteAuthState(dbPath?, ownedDatabase?)` — SQLite
235
+
236
+ ```javascript
237
+ import { useSqliteAuthState } from '@eduh_dev021/baileys'
238
+
239
+ const { state, saveCreds, close } = await useSqliteAuthState('session.db')
240
+ ```
241
+
242
+ Credentials go to a `creds` table and each Signal key to a `signal_keys` table (WAL mode, synchronous prepared statements, transactional writes). The driver is picked automatically:
243
+
244
+ 1. **Bun** → `bun:sqlite`
245
+ 2. **Node.js ≥ 22.13** → `node:sqlite` (built into Node, nothing to install)
246
+ 3. Otherwise → `better-sqlite3` (install it: `npm install better-sqlite3`)
247
+
248
+ Useful options:
249
+
250
+ ```javascript
251
+ // 1) Open (or create) a database file — the common case
252
+ const s1 = await useSqliteAuthState('session.db')
253
+
254
+ // 2) Use a database you already opened (shared with the rest of your app)
255
+ import Database from 'better-sqlite3'
256
+ const myDb = new Database('app.db')
257
+ const s2 = await useSqliteAuthState(undefined, myDb)
258
+
259
+ // 3) Release the file when you are done
260
+ s1.close()
261
+ ```
262
+
263
+ Returns `{ state, saveCreds, close }`.
264
+
265
+ ### Any other database (MySQL, PostgreSQL, MongoDB, Redis...)
266
+
267
+ The auth state is just a plain object:
268
+
269
+ ```javascript
270
+ {
271
+ creds: { ... }, // login credentials
272
+ keys: {
273
+ get: (type, ids) => ({ ... }), // read keys
274
+ set: (data) => { ... } // write keys
275
+ }
276
+ }
277
+ ```
278
+
279
+ So any storage works if you implement `get`/`set`. Keys are plain JSON serialized with the exported `BufferJSON` helpers (which turn Buffers into JSON-safe objects). Below is a complete, ready-to-copy adapter — replace the `myDb` calls with your MySQL/PostgreSQL/MongoDB/Redis client:
280
+
281
+ ```javascript
282
+ import {
283
+ makeWASocket,
284
+ initAuthCreds,
285
+ BufferJSON,
286
+ proto
287
+ } from '@eduh_dev021/baileys'
288
+
289
+ async function useMyDatabaseAuthState() {
290
+ // -- replace these 4 functions with your database calls ---------------
291
+ const readCreds = async () => {
292
+ // e.g. MySQL: SELECT data FROM baileys_creds WHERE key = '__creds__'
293
+ const row = await myDb.getCredsRow()
294
+ return row ? JSON.parse(row.data, BufferJSON.reviver) : null
295
+ }
296
+ const writeCreds = async (json) => {
297
+ // e.g. MySQL: INSERT ... ON DUPLICATE KEY UPDATE
298
+ await myDb.saveCredsRow(JSON.stringify(json, BufferJSON.replacer))
299
+ }
300
+ const readKey = async (type, id) => {
301
+ // e.g. MySQL: SELECT data FROM baileys_keys WHERE type = ? AND id = ?
302
+ const row = await myDb.getKeyRow(type, id)
303
+ return row ? JSON.parse(row.data, BufferJSON.reviver) : null
304
+ }
305
+ const writeKey = async (type, id, value) => {
306
+ // value === null means "delete this key"
307
+ await myDb.saveKeyRow(type, id, value === null ? null : JSON.stringify(value, BufferJSON.replacer))
308
+ }
309
+ // ----------------------------------------------------------------------
310
+
311
+ const creds = (await readCreds()) || initAuthCreds()
312
+
313
+ return {
314
+ state: {
315
+ creds,
316
+ keys: {
317
+ get: async (type, ids) => {
318
+ const data = {}
319
+ for (const id of ids) {
320
+ const value = await readKey(type, id)
321
+ if (!value) continue
322
+ data[id] = type === 'app-state-sync-key'
323
+ ? proto.Message.AppStateSyncKeyData.fromObject(value)
324
+ : value
325
+ }
326
+ return data
327
+ },
328
+ set: async (data) => {
329
+ for (const type in data) {
330
+ for (const id in data[type]) {
331
+ await writeKey(type, id, data[type][id] || null)
332
+ }
333
+ }
334
+ }
335
+ }
336
+ },
337
+ saveCreds: () => writeCreds(creds)
338
+ }
339
+ }
340
+
341
+ // usage — identical to the built-in helpers
342
+ const { state, saveCreds } = await useMyDatabaseAuthState()
343
+ const sock = makeWASocket({ auth: state })
344
+ sock.ev.on('creds.update', saveCreds)
345
+ ```
346
+
347
+ Notes:
348
+
349
+ - The key `type` values you will see: `pre-key`, `session`, `sender-key`, `sender-key-name`, `app-state-sync-key` and `app-state-sync-version-*`. Store them all the same way — the `type` column is just part of the primary key.
350
+ - Wrap `set` in a transaction if your database supports it — it writes several keys at once.
351
+ - Prefer `makeCacheableSignalKeyStore(state.keys, logger)` in `set`-heavy setups; it caches reads in memory and batches writes (this is what `makeWASocket` does internally when you pass a raw state).
352
+
353
+ ### Logging out / removing the session
354
+
355
+ ```javascript
356
+ await sock.logout() // logs out from WhatsApp
357
+ // then delete the storage yourself: rm -rf session/ (or DROP the tables / the file)
358
+ ```
359
+
360
+ ---
361
+
362
+ # The store: `makeInMemoryStore`
363
+
364
+ The library itself does not keep a list of your chats, contacts or messages — WhatsApp does not provide one. The built-in **in-memory store** listens to all events and builds a queryable state from them: chats, messages, contacts, group metadata, labels and presences.
365
+
366
+ ```javascript
367
+ import { makeWASocket, makeInMemoryStore, useMultiFileAuthState } from '@eduh_dev021/baileys'
368
+
369
+ const { state, saveCreds } = await useMultiFileAuthState('session')
370
+ const sock = makeWASocket({ auth: state })
371
+
372
+ const store = makeInMemoryStore({ socket: sock })
373
+ store.bind(sock.ev) // starts collecting — call this once, right after connecting
374
+ ```
375
+
376
+ ### Persisting the store to a JSON file
377
+
378
+ The store can save and reload all of its content as JSON with two functions: **`writeToFile`** and **`readFromFile`**. Combine them with an interval for automatic saving:
379
+
380
+ ```javascript
381
+ const store = makeInMemoryStore({ socket: sock })
382
+ store.bind(sock.ev)
383
+
384
+ // reload what was saved last time (does nothing if the file doesn't exist yet)
385
+ store.readFromFile('./baileys_store.json')
386
+
387
+ // save every 10 seconds
388
+ setInterval(() => {
389
+ store.writeToFile('./baileys_store.json')
390
+ }, 10_000)
391
+
392
+ // also save once on exit
393
+ process.on('SIGINT', () => {
394
+ store.writeToFile('./baileys_store.json')
395
+ process.exit(0)
396
+ })
397
+ ```
398
+
399
+ ### Persisting the store to SQL or any other database
400
+
401
+ `store.toJSON()` returns the whole store as a plain JSON object, and `store.fromJSON(json)` loads it back. That means the store content is just a JSON document you can put **anywhere**: a MySQL `LONGTEXT` column, a PostgreSQL `JSONB` column, MongoDB, Redis, S3... Save it periodically and load it on startup:
402
+
403
+ ```javascript
404
+ // example with node:sqlite (built into Node 22.13+; same idea for MySQL/Postgres/Mongo)
405
+ import { DatabaseSync } from 'node:sqlite'
406
+ import { makeInMemoryStore } from '@eduh_dev021/baileys'
407
+
408
+ const db = new DatabaseSync('store.db')
409
+ db.exec(`CREATE TABLE IF NOT EXISTS store_data (
410
+ id INTEGER PRIMARY KEY CHECK (id = 1),
411
+ data TEXT NOT NULL
412
+ )`)
413
+
414
+ const loadJson = () => db.prepare('SELECT data FROM store_data WHERE id = 1').get()?.data
415
+ const saveJson = (json) =>
416
+ db.prepare('INSERT OR REPLACE INTO store_data (id, data) VALUES (1, ?)')
417
+ .run(JSON.stringify(json))
418
+
419
+ const store = makeInMemoryStore({ socket: sock })
420
+ store.bind(sock.ev)
421
+
422
+ // restore
423
+ const saved = loadJson()
424
+ if (saved) store.fromJSON(saved)
425
+
426
+ // save every 10 seconds
427
+ setInterval(() => saveJson(store.toJSON()), 10_000)
428
+ ```
429
+
430
+ The JSON document has this shape (same as `toJSON()` returns):
431
+
432
+ ```javascript
433
+ {
434
+ chats: [ ... ], // chat list
435
+ contacts: { '<jid>': {...} }, // known contacts
436
+ messages: { '<jid>': [ ... ] },// stored messages per chat
437
+ labels: { ... }, // WhatsApp labels
438
+ labelAssociations: [ ... ] // which chat/message has which label
439
+ }
440
+ ```
441
+
442
+ ### Everything the store offers
443
+
444
+ ```javascript
445
+ store.chats // KeyedDB of chats — store.chats.all() returns the array
446
+ store.contacts // { jid: contact }
447
+ store.messages // { jid: ordered message list }
448
+ store.groupMetadata // { jid: group metadata }
449
+ store.presences // { jid: presence data }
450
+ store.state // last connection.update received
451
+ store.labels // all labels (ObjectRepository)
452
+ store.labelAssociations
453
+
454
+ store.bind(ev) // connect to sock.ev (required)
455
+ store.loadMessages(jid, count, cursor?) // last `count` messages of a chat, oldest→newest; cursor = { before: key } for pagination
456
+ store.loadMessage(jid, id) // one message by id
457
+ store.mostRecentMessage(jid) // latest message of a chat
458
+ store.fetchImageUrl(jid, sock) // profile picture URL (cached)
459
+ store.fetchGroupMetadata(jid, sock) // group metadata (cached)
460
+ store.fetchMessageReceipts(key) // delivery/read receipts of a message
461
+ store.getLabels() // all labels
462
+ store.getChatLabels(chatId) // labels applied to a chat
463
+ store.getMessageLabels(messageId) // labels applied to a message
464
+ store.toJSON() // full snapshot as JSON object
465
+ store.fromJSON(json) // restore from a snapshot
466
+ store.writeToFile(path) // snapshot → JSON file
467
+ store.readFromFile(path) // JSON file → store (no-op if missing)
468
+ ```
469
+
470
+ Two notes:
471
+
472
+ - `loadMessages` only returns messages the store has **already seen** — it never queries the server. Fresh sessions start empty and fill up as history sync arrives.
473
+ - Keeping every chat and message in memory can use a lot of RAM on busy bots. If that becomes a problem, save snapshots on your own schedule with a limited `messages` list, or build custom storage from the events you receive.
474
+
475
+ ### Store options
476
+
477
+ ```javascript
478
+ const store = makeInMemoryStore({
479
+ socket: sock, // lets the store fetch profile pictures automatically
480
+ chatKey: waChatKey(true), // how chats are ordered (default: pinned > unpinned > timestamp)
481
+ logger // custom pino logger
482
+ })
483
+ ```
484
+
485
+ ---
486
+
487
+ # Socket configuration (`makeWASocket` options)
488
+
489
+ All options are optional except `auth` (well, even it is optional — but without a saved state you cannot stay logged in). Defaults come from `DEFAULT_CONNECTION_CONFIG`, also exported.
490
+
491
+ ```javascript
492
+ import makeWASocket, {
493
+ Browsers,
494
+ fetchLatestBaileysVersion
495
+ } from '@eduh_dev021/baileys'
496
+
497
+ const { version } = await fetchLatestBaileysVersion()
498
+
499
+ const sock = makeWASocket({
500
+ // --- connection ---------------------------------------------------------
501
+ version, // WA Web version to announce (fetchLatestBaileysVersion)
502
+ browser: Browsers.macOS('Chrome'), // device shown in linked devices
503
+ auth: state, // auth state (see "Saving your session")
504
+ waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat', // server endpoint
505
+ connectTimeoutMs: 60_000, // default timeout for internal awaits
506
+ defaultQueryTimeoutMs: undefined, // timeout for query() calls
507
+ keepAliveIntervalMs: 30_000, // ping interval
508
+ emitOwnEvents: true, // also emit events for your own messages
509
+ fireInitQueries: true, // send the initial queries at startup
510
+
511
+ // --- behaviour ----------------------------------------------------------
512
+ syncFullHistory: false, // ask WhatsApp for ALL history (heavy)
513
+ shouldSyncHistoryMessage: () => true, // filter which history messages to accept
514
+ markOnlineOnConnect: true, // show you "online" while connected (false = you appear offline)
515
+ generateHighQualityLinkPreview: false, // better link previews, more processing
516
+ linkPreviewImageThumbnailWidth: 1920, // link preview width
517
+ enableAutoSessionRecreation: true, // auto-rebuild the Signal session on errors
518
+ enableRecentMessageCache: true, // cache recent messages for retry decryption
519
+ maxMsgRetryCount: 5, // max decryption retries per message
520
+ retryRequestDelayMs: 250, // base delay between retries
521
+
522
+ // --- features you must provide ------------------------------------------
523
+ getMessage: async (key) => undefined, // return the original message for retries (from your store/DB)
524
+ cachedGroupMetadata: async (jid) => undefined, // serve group metadata from your cache
525
+ shouldIgnoreJid: (jid) => false, // ignore certain chats entirely
526
+ patchMessageBeforeSending: (msg) => msg, // transform the message before it is serialized
527
+ printQRInTerminal: false, // print QR in terminal (built-in generator)
528
+
529
+ // --- caches (all optional; plug your own Map-like objects) ---------------
530
+ mediaCache, // link-preview media cache
531
+ msgRetryCounterCache, // retry counters
532
+ callOfferCache, // pending call offers
533
+ userDevicesCache, // user device lists
534
+ placeholderResendCache, // placeholder resend state
535
+
536
+ // --- advanced -------------------------------------------------------------
537
+ logger, // pino logger (default: silent)
538
+ options: {}, // default options for media uploads (headers, agent)
539
+ customUploadHosts: [], // extra upload hosts
540
+ transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
541
+ appStateMacVerification: { patch: true, snapshot: true },
542
+ makeSignalRepository, // custom Signal repository factory
543
+ qrTimeout: 60_000 // how long to keep requesting QR codes
544
+ })
545
+ ```
546
+
547
+ `Browsers` helps you build the `browser` array: `Browsers.macOS('Chrome')`, `Browsers.ubuntu('Chrome')`, `Browsers.windows('Chrome')`, `Browsers.baileys('...')`, `Browsers.appropriate(...)`. Avoid `Browsers.android(...)` — it is experimental and may misbehave.
548
+
549
+ ---
550
+
551
+ # WhatsApp IDs (JID and LID)
552
+
553
+ Every chat and user is addressed by an ID. WhatsApp uses two addressing systems:
554
+
555
+ - **JID (Jabber ID)** — the classic phone-number-based address.
556
+ - **LID (Local ID)** — a newer privacy-preserving identifier. WhatsApp is migrating accounts to LIDs; the library handles the mapping automatically (`lid-mapping.update` event) and accepts either form when sending.
557
+
558
+ | Target | ID format | Example |
559
+ | --- | --- | --- |
560
+ | Person (JID) | `[country code][number]@s.whatsapp.net` | `5511999999999@s.whatsapp.net` |
561
+ | Person (LID) | `[number]@lid` | `102345678912345@lid` |
562
+ | Group | `[id]@g.us` | `120363025857034293@g.us` |
563
+ | Channel (newsletter) | `[id]@newsletter` | `120363025857034293@newsletter` |
564
+ | Status / stories | fixed | `status@broadcast` |
565
+ | Broadcast list | `[creation timestamp]@broadcast` | `1677860500@broadcast` |
566
+ | Meta AI bot | `[number]@bot` | `13135550002@bot` |
567
+ | Official business | `[number]@business` | — |
568
+
569
+ The ID must contain **numbers only** — no `+`, spaces, dashes or parentheses, and always with the country code.
570
+
571
+ Useful helpers (all exported): `jidNormalizedUser` (canonical form), `jidDecode`/`jidEncode`, `areJidsSameUser` (compares a PN against its LID), `isJidGroup`, `isJidNewsletter`, `isLidUser`, `isPnUser`, `isJidBot`, `isJidMetaAI`, `isJidBroadcast`. To check whether a number exists on WhatsApp, use `sock.onWhatsApp(number)`.
572
+
573
+ When you receive a message, `msg.key.remoteJid` carries the sender ID and `msg.key.participant` the author inside groups. Both may arrive as LID — resolve the phone number with `sock.findUserId(...)` (see [Practical guides](#find-user-id-pnlid)).
574
+
575
+ ---
576
+
577
+ # Sending messages
578
+
579
+ Everything below is `await sock.sendMessage(jid, content, extraOptions?)`.
580
+
581
+ A `jid` looks like:
582
+
583
+ - `5511999999999@s.whatsapp.net` — a person
584
+ - `120363...@g.us` — a group
585
+ - `123456789@newsletter` — a channel (newsletter)
586
+ - `status@broadcast` — status/stories
587
+
588
+ Helpers to build and check JIDs: `jidNormalizedUser`, `jidDecode`, `jidEncode`, `areJidsSameUser`, `isJidGroup`, `isJidNewsletter`, `isJidBroadcast`, `isJidStatusBroadcast`, `isJidBot`, `isJidMetaAI`, `isLidUser`, `isPnUser`.
589
+
590
+ Check if a number has WhatsApp before talking to it:
591
+
592
+ ```javascript
593
+ const [result] = await sock.onWhatsApp('5511999999999')
594
+ if (result?.exists) console.log('has WhatsApp:', result.jid)
595
+ ```
596
+
597
+ The third argument of `sendMessage` carries send options: `{ quoted, edit, ephemeralExpiration, mediaUpload, ... }`. In the examples, `receivedMessage` is a message object you got from `messages.upsert`.
598
+
599
+ ## Text
600
+
601
+ ```javascript
602
+ await sock.sendMessage(jid, { text: 'Hello from my bot!' })
603
+ ```
604
+
605
+ With formatting and a link preview:
606
+
607
+ ```javascript
608
+ await sock.sendMessage(jid, {
609
+ text: '*bold* _italic_ ~strikethrough~ ```code```\nhttps://example.com'
610
+ })
611
+ ```
612
+
613
+ Replying to a specific message:
614
+
615
+ ```javascript
616
+ await sock.sendMessage(jid, { text: 'Great message!' }, { quoted: receivedMessage })
617
+ ```
618
+
619
+ Mentions — individual or everyone:
620
+
621
+ ```javascript
622
+ await sock.sendMessage(jid, {
623
+ text: 'Hey @5511999999999, look at this!',
624
+ mentions: ['5511999999999@s.whatsapp.net']
625
+ })
626
+
627
+ // mention everyone without listing them
628
+ await sock.sendMessage(jid, { text: 'Attention, everyone!', mentionAll: true })
629
+ ```
630
+
631
+ ## Rich messages (code blocks, tables, LaTeX)
632
+
633
+ Send WhatsApp's native "AI-style" rich messages — code blocks with syntax highlighting, content carousels, LaTeX and citation links:
634
+
635
+ ```javascript
636
+ // a syntax-highlighted code block
637
+ await sock.sendMessage(jid, {
638
+ code: 'const hello = () => console.log("hi!")',
639
+ language: 'javascript'
640
+ })
641
+
642
+ // a rich composite: header, code, table, image, LaTeX and footer
643
+ await sock.sendMessage(jid, {
644
+ title: 'Bot report',
645
+ richResponse: [
646
+ { text: 'Uptime: 24h, 0 errors.' },
647
+ { code: 'for (i = 0; i < 10; i++) print(i)', language: 'python' },
648
+ { table: [{ name: 'Alice', score: 10 }, { name: 'Bob', score: 9 }], title: 'Scores' },
649
+ { inlineImage: 'https://example.com/chart.png', imageText: 'Traffic chart', alignment: 'CENTER' },
650
+ { latex: ['E = mc^2'], text: 'Relativity' }
651
+ ],
652
+ headerText: '📊 Daily summary',
653
+ footerText: 'Generated by my bot'
654
+ })
655
+
656
+ // citation-style links
657
+ await sock.sendMessage(jid, {
658
+ links: [
659
+ { text: 'Source of the news', url: 'https://example.com/article' }
660
+ ],
661
+ contentText: 'The article above says everything.'
662
+ })
663
+ ```
664
+
665
+ ## Sending media
666
+
667
+ For media, pass a **Buffer**, a **local file path**, or a **URL** in the `url` field of each type.
668
+
669
+ ```javascript
670
+ // image
671
+ await sock.sendMessage(jid, { image: { url: './photo.jpg' }, caption: 'Check this out!' })
672
+
673
+ // video (gifPlayback: true renders as looping GIF preview)
674
+ await sock.sendMessage(jid, { video: { url: './clip.mp4' }, caption: 'Watch this', gifPlayback: false })
675
+
676
+ // video note (round, like the phone app)
677
+ await sock.sendMessage(jid, { ptv: true, video: { url: './note.mp4' } })
678
+
679
+ // voice note (ptt: true shows the waveform bubble)
680
+ await sock.sendMessage(jid, {
681
+ audio: { url: './voice.ogg' },
682
+ mimetype: 'audio/ogg; codecs=opus',
683
+ ptt: true
684
+ })
685
+
686
+ // document
687
+ await sock.sendMessage(jid, {
688
+ document: { url: './report.pdf' },
689
+ mimetype: 'application/pdf',
690
+ fileName: 'Quarterly report.pdf'
691
+ })
692
+
693
+ // single sticker
694
+ await sock.sendMessage(jid, { sticker: { url: './funny.webp' } })
695
+ ```
696
+
697
+ ### Sticker pack
698
+
699
+ Send a whole sticker pack in one message (up to 60 stickers — WhatsApp's limit):
700
+
701
+ ```javascript
702
+ import fs from 'node:fs'
703
+
704
+ await sock.sendMessage(jid, {
705
+ stickers: [
706
+ { sticker: fs.readFileSync('./s1.webp'), emoji: '😎' },
707
+ { sticker: fs.readFileSync('./s2.webp'), emoji: '🎉' }
708
+ ],
709
+ cover: fs.readFileSync('./cover.webp'), // required
710
+ name: 'My Pack',
711
+ publisher: 'My Bot',
712
+ description: 'Stickers made by my bot'
713
+ })
714
+ ```
715
+
716
+ ### Album
717
+
718
+ Send an album (2+ media) as one collection message:
719
+
720
+ ```javascript
721
+ await sock.sendMessage(jid, {
722
+ album: [
723
+ { image: { url: './photo1.jpg' }, caption: 'First' },
724
+ { image: { url: './photo2.jpg' }, caption: 'Second' },
725
+ { video: { url: './clip.mp4' }, caption: 'And a video' }
726
+ ]
727
+ })
728
+ ```
729
+
730
+ The value must be an **array** with at least two image/video items; each item is a normal media payload with its own caption.
731
+
732
+ ## Contact, location, event
733
+
734
+ ```javascript
735
+ // one contact (or contactsArrayMessage for several — pass an array in `contacts`)
736
+ await sock.sendMessage(jid, {
737
+ contacts: {
738
+ displayName: 'Maria',
739
+ contacts: [{ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:Maria\nTEL;type=CELL:+5511999999999\nEND:VCARD' }]
740
+ }
741
+ })
742
+
743
+ // location
744
+ await sock.sendMessage(jid, {
745
+ location: { degreesLatitude: -23.5505, degreesLongitude: -46.6333 }
746
+ })
747
+
748
+ // calendar event (dates are JavaScript Date objects)
749
+ await sock.sendMessage(jid, {
750
+ event: {
751
+ name: 'Team meeting',
752
+ description: 'Weekly sync',
753
+ startDate: new Date(Date.now() + 3_600_000),
754
+ endDate: new Date(Date.now() + 7_200_000),
755
+ isCancelled: false,
756
+ extraGuestsAllowed: true,
757
+ call: 'video' // optional: also creates a WhatsApp call link
758
+ }
759
+ })
760
+ ```
761
+
762
+ ## Other message options
763
+
764
+ All the extra toggles below are plain fields on the message content:
765
+
766
+ ```javascript
767
+ import fs from 'node:fs'
768
+
769
+ // AI icon — shows the Meta AI badge next to the message (private chats only)
770
+ await sock.sendMessage(jid, {
771
+ image: { url: './photo.jpg' },
772
+ caption: 'Answered by AI',
773
+ ai: true
774
+ })
775
+
776
+ // spoiler — blurs the media until the user taps it
777
+ await sock.sendMessage(jid, {
778
+ image: { url: './surprise.jpg' },
779
+ caption: 'Tap to reveal',
780
+ spoiler: true
781
+ })
782
+
783
+ // view once — media disappears after being opened (three protocol variants)
784
+ await sock.sendMessage(jid, { image: { url: './secret.jpg' }, viewOnce: true })
785
+ await sock.sendMessage(jid, { image: { url: './secret.jpg' }, viewOnceV2: true })
786
+ await sock.sendMessage(jid, { image: { url: './secret.jpg' }, viewOnceV2Extension: true })
787
+
788
+ // ephemeral — wraps the message in the chat's disappearing timer
789
+ await sock.sendMessage(jid, { text: 'This one expires', ephemeral: true })
790
+
791
+ // group status — posts to the group's status instead of the chat timeline (groups only)
792
+ await sock.sendMessage(groupJid, {
793
+ image: { url: './news.jpg' },
794
+ caption: 'Group announcement',
795
+ groupStatus: true
796
+ })
797
+
798
+ // lottie sticker — animated sticker backed by a Lottie file
799
+ await sock.sendMessage(jid, { sticker: { url: './animated.webp' }, isLottie: true })
800
+
801
+ // secure Meta service label — flags the message for business labeling
802
+ await sock.sendMessage(jid, { text: 'Categorized message', secureMetaServiceLabel: true })
803
+
804
+ // raw — build the full proto yourself and send it untouched (advanced)
805
+ await sock.sendMessage(jid, {
806
+ extendedTextMessage: {
807
+ text: 'Built manually from the raw WhatsApp proto structure',
808
+ contextInfo: {
809
+ externalAdReply: {
810
+ title: 'My bot',
811
+ thumbnail: fs.readFileSync('./thumb.jpg'),
812
+ sourceApp: 'whatsapp',
813
+ showAdAttribution: true,
814
+ mediaType: 1
815
+ }
816
+ }
817
+ },
818
+ raw: true
819
+ }, { quoted: receivedMessage })
820
+ ```
821
+
822
+ Notes:
823
+
824
+ - `viewOnce`/`viewOnceV2`/`viewOnceV2Extension` are three generations of the same protocol feature; `viewOnceV2` is what current WhatsApp clients send.
825
+ - `ephemeral: true` wraps an individual message in the chat's configured disappearing duration — the chat itself must have a timer set (`disappearingMessagesInChat` or `sock.groupToggleEphemeral`).
826
+ - `ai: true` only renders the AI badge in private chats.
827
+ - `groupStatus: true` only works in groups.
828
+
829
+ ## Status mentions
830
+
831
+ Sending to `status@broadcast` posts a status. Pass `mentions` and the library automatically notifies each mentioned contact (the protocol `statusMentionMessage`), so the status shows up for them with a mention marker:
832
+
833
+ ```javascript
834
+ await sock.sendMessage('status@broadcast', {
835
+ image: { url: './promo.jpg' },
836
+ caption: 'Big news for @5511999999999 and @5511888888888!',
837
+ mentions: ['5511999999999@s.whatsapp.net', '5511888888888@s.whatsapp.net'],
838
+ backgroundColor: '#7CFC00',
839
+ font: 1
840
+ })
841
+ ```
842
+
843
+ When you send the status to an **array of jids**, each contact receives the mention notification as well:
844
+
845
+ ```javascript
846
+ await sock.sendMessage(['5511999999999@s.whatsapp.net', '5511888888888@s.whatsapp.net'], {
847
+ text: 'Check out my status!'
848
+ })
849
+ ```
850
+
851
+ ## Commerce messages
852
+
853
+ ```javascript
854
+ // product card
855
+ await sock.sendMessage(jid, {
856
+ product: {
857
+ productImage: imageBuffer,
858
+ productId: '123456789',
859
+ title: 'Nice shoes',
860
+ description: 'Size 42, blue',
861
+ currencyCode: 'BRL',
862
+ priceAmount1000: 29990, // price × 1000
863
+ retailerId: 'store-001',
864
+ url: 'https://mystore.com/item/123456789'
865
+ }
866
+ })
867
+
868
+ // order (thumbnail must be a Buffer)
869
+ import fs from 'node:fs'
870
+ await sock.sendMessage(jid, {
871
+ orderText: 'Order #123 — 2 items',
872
+ thumbnail: fs.readFileSync('./thumb.jpg'),
873
+ orderTitle: 'My Store',
874
+ totalAmount1000: 29990,
875
+ totalCurrencyCode: 'BRL',
876
+ itemCount: 2
877
+ })
878
+
879
+ // invoice note (must accompany an image or document message)
880
+ await sock.sendMessage(jid, {
881
+ document: { url: './invoice.pdf' },
882
+ mimetype: 'application/pdf',
883
+ invoiceNote: 'Invoice #42 for services'
884
+ })
885
+
886
+ // payment request (note: only text or sticker messages can be the note)
887
+ await sock.sendMessage(jid, {
888
+ requestPaymentFrom: '5511999999999@s.whatsapp.net',
889
+ text: 'Please pay for the service',
890
+ amount1000: 50000,
891
+ currencyCodeIso4217: 'BRL'
892
+ })
893
+
894
+ // payment invite
895
+ await sock.sendMessage(jid, { paymentInviteServiceType: 'fbpay' })
896
+ ```
897
+
898
+ ## Poll
899
+
900
+ ```javascript
901
+ // create a poll
902
+ await sock.sendMessage(jid, {
903
+ poll: {
904
+ name: 'Pizza or burger?',
905
+ values: ['Pizza', 'Burger'],
906
+ selectableCount: 1
907
+ }
908
+ })
909
+
910
+ // send a result snapshot (e.g. after aggregating votes yourself)
911
+ await sock.sendMessage(jid, {
912
+ pollResult: {
913
+ name: 'Pizza or burger?',
914
+ votes: [
915
+ { name: 'Pizza', voteCount: 12 },
916
+ { name: 'Burger', voteCount: 3 }
917
+ ]
918
+ }
919
+ })
920
+ ```
921
+
922
+ To **read votes as they arrive**, listen to `messages.update` and use `getAggregateVotesInPollMessage` (shown in the events section).
923
+
924
+ ## Phone number and privacy messages
925
+
926
+ ```javascript
927
+ // protocol-type messages (no content, they toggle things on the chat)
928
+ await sock.sendMessage(jid, { sharePhoneNumber: true }) // share your number with the contact
929
+ await sock.sendMessage(jid, { requestPhoneNumber: true }) // ask the contact to share theirs
930
+ await sock.sendMessage(jid, { disappearingMessagesInChat: 604800 }) // seconds: 0/off, 86400, 604800, 7776000
931
+ await sock.sendMessage(jid, { limitSharing: true }) // restrict forwarding of this chat's content
932
+
933
+ // send any raw proto content you build yourself (advanced)
934
+ await sock.sendMessage(jid, { raw: myMessageProto })
935
+ ```
936
+
937
+ ## Interactive messages
938
+
939
+ > Compatibility note from the protocol: hydrated templates render on WhatsApp Web/Desktop and iOS; on Android they currently appear only in newsletters. Plain buttons and lists work everywhere.
940
+
941
+ ### Buttons
942
+
943
+ Three button styles, selected by the fields you provide:
944
+
945
+ ```javascript
946
+ // 1) simple response buttons
947
+ await sock.sendMessage(jid, {
948
+ text: 'What do you want to do?',
949
+ footer: 'My bot',
950
+ buttons: [
951
+ { id: '#help', text: 'Help' },
952
+ { id: '#menu', text: 'Menu' }
953
+ ]
954
+ })
955
+
956
+ // 2) a button that opens a single-select list
957
+ await sock.sendMessage(jid, {
958
+ text: 'Pick a city',
959
+ buttons: [{
960
+ text: 'Cities',
961
+ sections: [
962
+ { title: 'South', rows: [{ title: 'Curitiba', id: 'city-cwb' }, { title: 'Floripa', id: 'city-fln' }] },
963
+ { title: 'North', rows: [{ title: 'Manaus', id: 'city-mao' }] }
964
+ ]
965
+ }]
966
+ })
967
+
968
+ // 3) native-flow buttons (catalog, copy code, call, etc.)
969
+ await sock.sendMessage(jid, {
970
+ text: 'Limited offer!',
971
+ footer: 'My Store',
972
+ nativeFlow: [
973
+ { name: 'cta_copy', paramsJson: JSON.stringify({ display_text: 'Copy code', copy_code: 'PROMO10' }) },
974
+ { name: 'cta_url', paramsJson: JSON.stringify({ display_text: 'Visit site', url: 'https://example.com' }) }
975
+ ],
976
+ offerText: '10% OFF', // optional: renders the "limited time offer" panel
977
+ offerCode: 'PROMO10',
978
+ offerUrl: 'https://example.com'
979
+ })
980
+ ```
981
+
982
+ ### List (classic section list)
983
+
984
+ ```javascript
985
+ await sock.sendMessage(jid, {
986
+ text: 'Pick an option',
987
+ title: 'Options',
988
+ footer: 'My bot',
989
+ buttonText: 'Choose',
990
+ sections: [{
991
+ title: 'Main',
992
+ rows: [
993
+ { title: 'Help', id: '#help', description: 'How to use' },
994
+ { title: 'Menu', id: '#menu', description: 'Show the menu' }
995
+ ]
996
+ }]
997
+ })
998
+ ```
999
+
1000
+ ### Template buttons (hydrated template)
1001
+
1002
+ ```javascript
1003
+ await sock.sendMessage(jid, {
1004
+ text: 'Welcome! Choose an action:',
1005
+ footer: 'My bot',
1006
+ templateButtons: [
1007
+ { index: 0, id: '#help', text: 'Help' },
1008
+ { index: 1, url: 'https://example.com', text: 'Visit us' },
1009
+ { index: 2, call: '+5511999999999', text: 'Call us' }
1010
+ ]
1011
+ })
1012
+ ```
1013
+
1014
+ ### Carousel (cards)
1015
+
1016
+ ```javascript
1017
+ await sock.sendMessage(jid, {
1018
+ text: 'Check our products',
1019
+ footer: 'My Store',
1020
+ cards: [
1021
+ {
1022
+ image: { url: './product1.jpg' },
1023
+ body: 'Great shoes',
1024
+ footer: 'R$ 299,90',
1025
+ nativeFlow: [
1026
+ { name: 'cta_url', paramsJson: JSON.stringify({ display_text: 'Buy', url: 'https://mystore.com/1' }) }
1027
+ ]
1028
+ },
1029
+ {
1030
+ image: { url: './product2.jpg' },
1031
+ body: 'Blue shirt',
1032
+ footer: 'R$ 99,90',
1033
+ nativeFlow: [
1034
+ { name: 'cta_url', paramsJson: JSON.stringify({ display_text: 'Buy', url: 'https://mystore.com/2' }) }
1035
+ ]
1036
+ }
1037
+ ]
1038
+ })
1039
+ ```
1040
+
1041
+ ### Button, list and flow replies
1042
+
1043
+ Send the "response" message a user would send after tapping — useful when relaying flows or building tests:
1044
+
1045
+ ```javascript
1046
+ // response to a simple/template button
1047
+ await sock.sendMessage(jid, { buttonReply: { id: '#help', displayText: 'Help', index: 0 }, type: 'template' })
1048
+ await sock.sendMessage(jid, { buttonReply: { id: '#help', displayText: 'Help' }, type: 'plain' })
1049
+
1050
+ // response to a list row
1051
+ await sock.sendMessage(jid, { listReply: { id: '#menu', title: 'Menu', description: 'Show the menu' } })
1052
+
1053
+ // response to a native-flow interaction
1054
+ await sock.sendMessage(jid, {
1055
+ flowReply: { name: 'menu', paramsJson: JSON.stringify({ choice: 'pizza' }), text: 'Chosen!' }
1056
+ })
1057
+ ```
1058
+
1059
+ ### Ad replies (link cards)
1060
+
1061
+ Attach a rich link card to (almost) any message — `thumbnail` must be a Buffer:
1062
+
1063
+ ```javascript
1064
+ import fs from 'node:fs'
1065
+
1066
+ await sock.sendMessage(jid, {
1067
+ text: 'Read this!',
1068
+ externalAdReply: {
1069
+ title: 'My article',
1070
+ body: 'A great read',
1071
+ url: 'https://example.com/article',
1072
+ thumbnail: fs.readFileSync('./thumb.jpg'),
1073
+ mediaType: 1,
1074
+ largeThumbnail: true,
1075
+ sourceUrl: 'https://example.com/article'
1076
+ }
1077
+ })
1078
+ ```
1079
+
1080
+ ## Modifying messages
1081
+
1082
+ ```javascript
1083
+ // delete for everyone
1084
+ await sock.sendMessage(jid, { delete: receivedMessage.key })
1085
+
1086
+ // delete only for yourself
1087
+ await sock.sendMessage(jid, { delete: { ...receivedMessage.key, fromMe: false, participant: sock.user.id } })
1088
+
1089
+ // edit a sent message
1090
+ await sock.sendMessage(jid, { text: 'Corrected text' }, { edit: sentMessage.key })
1091
+
1092
+ // reaction
1093
+ await sock.sendMessage(jid, { react: { text: '👍', key: receivedMessage.key } })
1094
+
1095
+ // pin (time in seconds: 86400 = 1 day, 604800 = 1 week; type 0 unpins)
1096
+ await sock.sendMessage(jid, { pin: { type: 1, key: receivedMessage.key, time: 86400 } })
1097
+
1098
+ // keep a message in the chat
1099
+ await sock.sendMessage(jid, { keep: { type: 1, key: receivedMessage.key, time: 0 } })
1100
+
1101
+ // forward
1102
+ await sock.sendMessage(jid, { forward: receivedMessage })
1103
+ ```
1104
+
1105
+ ---
1106
+
1107
+ # Receiving messages and downloading media
1108
+
1109
+ ```javascript
1110
+ import { getContentType, normalizeMessageContent } from '@eduh_dev021/baileys'
1111
+
1112
+ sock.ev.on('messages.upsert', async ({ messages, type }) => {
1113
+ // type: 'notify' (new messages), 'append' (history), etc.
1114
+ for (const msg of messages) {
1115
+ if (!msg.message) continue
1116
+ const content = normalizeMessageContent(msg.message) // unwraps view-once, ephemeral, replies, forwards
1117
+ const contentType = getContentType(content) // 'conversation', 'imageMessage', ...
1118
+ console.log('from:', msg.key.remoteJid, 'type:', contentType)
1119
+
1120
+ const body =
1121
+ content.conversation ||
1122
+ content.extendedTextMessage?.text ||
1123
+ content.imageMessage?.caption ||
1124
+ ''
1125
+ }
1126
+ })
1127
+ ```
1128
+
1129
+ ### Download any media
1130
+
1131
+ ```javascript
1132
+ import { downloadContentFromMessage } from '@eduh_dev021/baileys'
1133
+
1134
+ async function mediaToBuffer(messageContent, mediaType) {
1135
+ // mediaType: 'image' | 'video' | 'audio' | 'document' | 'sticker' | ...
1136
+ const stream = await downloadContentFromMessage(messageContent, mediaType)
1137
+ const chunks = []
1138
+ for await (const chunk of stream) chunks.push(chunk)
1139
+ return Buffer.concat(chunks)
1140
+ }
1141
+
1142
+ // example: save an image someone sent
1143
+ sock.ev.on('messages.upsert', async ({ messages }) => {
1144
+ const msg = messages[0]
1145
+ if (msg.message?.imageMessage) {
1146
+ const buffer = await mediaToBuffer(msg.message.imageMessage, 'image')
1147
+ require('fs').writeFileSync('./download.jpg', buffer)
1148
+ }
1149
+ })
1150
+ ```
1151
+
1152
+ One-shot helper for a whole message object:
1153
+
1154
+ ```javascript
1155
+ import { downloadMediaMessage } from '@eduh_dev021/baileys'
1156
+
1157
+ const buffer = await downloadMediaMessage(msg, 'buffer', {}, {
1158
+ reuploadRequest: sock.updateMediaMessage // auto re-request if the media expired
1159
+ })
1160
+ ```
1161
+
1162
+ If a download fails because WhatsApp expired the media, `sock.updateMediaMessage(msg)` re-requests it and updates the message object.
1163
+
1164
+ ### Reading poll votes
1165
+
1166
+ ```javascript
1167
+ import { getAggregateVotesInPollMessage } from '@eduh_dev021/baileys'
1168
+
1169
+ sock.ev.on('messages.update', (updates) => {
1170
+ for (const { key, update } of updates) {
1171
+ if (update.pollUpdates) {
1172
+ const poll = /* the original poll message, from your store */
1173
+ const votes = getAggregateVotesInPollMessage({
1174
+ message: poll?.message,
1175
+ pollUpdates: update.pollUpdates
1176
+ })
1177
+ console.log('poll votes:', votes)
1178
+ }
1179
+ }
1180
+ })
1181
+ ```
1182
+
1183
+ ---
1184
+
1185
+ # Everything you can listen to (events)
1186
+
1187
+ All events fire on `sock.ev` (`sock.ev.on(event, handler)`). The full list, grouped:
1188
+
1189
+ ### Connection and session
1190
+
1191
+ | Event | When it fires |
1192
+ | --- | --- |
1193
+ | `connection.update` | Connection state changed (`connecting`, `open`, `close`, QR received, logged out) |
1194
+ | `creds.update` | Login credentials changed — save them here with `saveCreds` |
1195
+
1196
+ ### Messages
1197
+
1198
+ | Event | When it fires |
1199
+ | --- | --- |
1200
+ | `messages.upsert` | New message arrived (`type: 'notify'`) or history was loaded (`type: 'append'`) |
1201
+ | `messages.update` | Message edited, status changed (delivered/read), poll vote, media re-upload |
1202
+ | `messages.delete` | Message removed (for a chat or by keys) |
1203
+ | `messages.reaction` | Reaction added/removed on a message |
1204
+ | `messages.media-update` | Media message updated (e.g. re-upload result) |
1205
+ | `message-receipt.update` | Delivery/read receipts (bulk) |
1206
+ | `messaging-history.set` | History sync batch: chats, contacts, messages |
1207
+ | `messaging-history.status` | History sync progress state |
1208
+
1209
+ ### Chats and contacts
1210
+
1211
+ | Event | When it fires |
1212
+ | --- | --- |
1213
+ | `chats.upsert` | New chat appeared |
1214
+ | `chats.update` | Chat changed (unread count, pinned, archived, muted...) |
1215
+ | `chats.delete` | Chat deleted |
1216
+ | `chats.lock` | Chat lock (protected chats) changed |
1217
+ | `contacts.upsert` | New/updated contacts |
1218
+ | `contacts.update` | Contact info changed (photo, name) |
1219
+ | `settings.update` | Account settings changed (e.g. push name) |
1220
+ | `blocklist.update` | Someone was blocked/unblocked |
1221
+ | `presence.update` | Contact online/typing/recording status |
1222
+ | `lid-mapping.update` | Phone-number ↔ LID mapping updated |
1223
+ | `message-capping.update` | Per-chat message capping settings changed |
1224
+
1225
+ ### Groups and calls
1226
+
1227
+ | Event | When it fires |
1228
+ | --- | --- |
1229
+ | `groups.upsert` | You were added to a group |
1230
+ | `groups.update` | Group info changed (subject, photo, settings) |
1231
+ | `group-participants.update` | Someone joined/left/promoted/demoted |
1232
+ | `group.join-request` | Someone requested to join a group |
1233
+ | `call` | Incoming call offer — accept or `sock.rejectCall` |
1234
+
1235
+ ### Newsletters (channels)
1236
+
1237
+ | Event | When it fires |
1238
+ | --- | --- |
1239
+ | `newsletter-participants.update` | Subscriber count changed |
1240
+ | `newsletter-settings.update` | Channel settings changed |
1241
+ | `newsletter.reaction` | Reaction on a channel post |
1242
+ | `newsletter.view` | Message viewed in the channel |
1243
+
1244
+ ### Labels
1245
+
1246
+ | Event | When it fires |
1247
+ | --- | --- |
1248
+ | `labels.edit` | A label was created/edited/deleted |
1249
+ | `labels.association` | A label was applied/removed on a chat or message |
1250
+
1251
+ Example — reject calls and log typing:
1252
+
1253
+ ```javascript
1254
+ sock.ev.on('call', async (calls) => {
1255
+ for (const call of calls) {
1256
+ if (call.status === 'offer') await sock.rejectCall(call.id, call.from)
1257
+ }
1258
+ })
1259
+
1260
+ sock.ev.on('presence.update', ({ id, presences }) => {
1261
+ for (const jid in presences) {
1262
+ const p = presences[jid]
1263
+ if (p.lastKnownPresence === 'composing') console.log(jid, 'is typing in', id)
1264
+ }
1265
+ })
1266
+ ```
1267
+
1268
+ ---
1269
+
1270
+ # Complete socket method reference
1271
+
1272
+ Everything below is a method on the socket object returned by `makeWASocket`.
1273
+
1274
+ ### Connection and pairing
1275
+
1276
+ | Method | What it does |
1277
+ | --- | --- |
1278
+ | `sock.ev` | Event emitter — all events above |
1279
+ | `sock.authState` | Current `creds` and `keys` |
1280
+ | `sock.user` | Your logged-in user (`id`, `name`, `lid`) |
1281
+ | `sock.ws` | The underlying WebSocket client |
1282
+ | `sock.requestPairingCode(phone, customCode?)` | Get a pairing code for a phone number |
1283
+ | `sock.logout()` | Log out and invalidate the session |
1284
+ | `sock.end(error?)` | Close the connection |
1285
+ | `sock.query(node)` | Send a raw protocol query and await the response |
1286
+ | `sock.sendNode(node)` | Send a raw node without waiting |
1287
+ | `sock.waitForConnectionUpdate(check)` | Wait until a connection condition is true |
1288
+ | `sock.onUnexpectedError(error)` | Report an error to the socket error handler |
1289
+
1290
+ ### Presence, profile and privacy
1291
+
1292
+ | Method | What it does |
1293
+ | --- | --- |
1294
+ | `sock.sendPresenceUpdate(type, toJid?)` | `available`, `unavailable`, `composing`, `recording`, `paused` |
1295
+ | `sock.presenceSubscribe(jid)` | Receive presence updates of a contact |
1296
+ | `sock.updateProfileName(name)` | Change your profile name |
1297
+ | `sock.updateProfileStatus(status)` | Change your about/status text |
1298
+ | `sock.updateProfilePicture(jid, image?)` | Set a new photo (`Buffer`); `undefined` removes it |
1299
+ | `sock.removeProfilePicture(jid)` | Remove your profile photo |
1300
+ | `sock.profilePictureUrl(jid, type?)` | Get the picture URL (`'preview'` or `'image'`) |
1301
+ | `sock.fetchStatus(jid)` | Read someone's about text |
1302
+ | `sock.fetchBlocklist()` | List blocked numbers |
1303
+ | `sock.updateBlockStatus(jid, action)` | `'block'` or `'unblock'` |
1304
+ | `sock.fetchPrivacySettings(disposable?)` | Read your privacy settings |
1305
+ | `sock.updateLastSeenPrivacy(value)` | who sees last seen: `'all'` / `'contacts'` / `'contact_blacklist'` / `'none'` |
1306
+ | `sock.updateOnlinePrivacy(value)` | who sees you online |
1307
+ | `sock.updateProfilePicturePrivacy(value)` | who sees your photo |
1308
+ | `sock.updateStatusPrivacy(value)` | who sees your status |
1309
+ | `sock.updateReadReceiptsPrivacy(value)` | who sees read receipts |
1310
+ | `sock.updateGroupsAddPrivacy(value)` | who can add you to groups |
1311
+ | `sock.updateCallPrivacy(value)` | who can call you |
1312
+ | `sock.updateMessagesPrivacy(value)` | who can message you |
1313
+ | `sock.updateDisableLinkPreviewsPrivacy(value)` | link previews on/off |
1314
+ | `sock.updateDefaultDisappearingMode({ ephemeralDuration })` | default disappearing timer |
1315
+
1316
+ ### Chats
1317
+
1318
+ | Method | What it does |
1319
+ | --- | --- |
1320
+ | `sock.chatModify(mod, jid)` | Change a chat — see below |
1321
+ | `sock.fetchDisappearingDuration(jid)` | Current disappearing timer of a chat |
1322
+ | `sock.fetchNewChatMessageCap(jid)` | Message capping info for a chat |
1323
+ | `sock.fetchAccountReachoutTimelock()` | Account reachout timelock state |
1324
+ | `sock.findUserId(...)` | Resolve a user id (LID helpers) |
1325
+ | `sock.addOrEditContact(jid, contact)` | Save a contact locally |
1326
+ | `sock.removeContact(jid)` | Remove a saved contact |
1327
+ | `sock.addChatLabel(jid, labelId)` / `sock.removeChatLabel(jid, labelId)` | Label a chat |
1328
+ | `sock.addMessageLabel(jid, labelId, messageId)` / `sock.removeMessageLabel(...)` | Label a message |
1329
+ | `sock.star(jid, messages, starred)` | Star/unstar messages |
1330
+ | `sock.addOrEditQuickReply(...)` / `sock.removeQuickReply(...)` | Manage quick replies |
1331
+ | `sock.cleanDirtyBits(type, from?)` | Sync dirty state |
1332
+
1333
+ Supported `chatModify` actions (`mod` object):
1334
+
1335
+ ```javascript
1336
+ await sock.chatModify({ archive: true }, jid) // archive / unarchive (false)
1337
+ await sock.chatModify({ mute: Date.now() + 86400_000 }, jid) // mute until a timestamp (ms); 0 = unmute
1338
+ await sock.chatModify({ pin: true }, jid) // pin / unpin
1339
+ await sock.chatModify({ markRead: false, readMessages: [key] }, jid) // mark read/unread
1340
+ await sock.chatModify({ clear: true }, jid) // clear messages
1341
+ await sock.chatModify({ delete: true }, jid) // delete the chat
1342
+ await sock.chatModify({ deleteForMe: { keyIds: [key.id], timestamp: Date.now() } }, jid)
1343
+ await sock.chatModify({ star: { messages: [{ id: key.id, star: true }], timestamp: Date.now() } }, jid)
1344
+ await sock.chatModify({ contact: { name: 'Maria' } }, jid) // save contact
1345
+ await sock.chatModify({ disableLinkPreviews: true }, jid)
1346
+ await sock.chatModify({ pushNameSetting: 'Name' }, jid)
1347
+ await sock.chatModify({ quickReply: { ... } }, jid)
1348
+ await sock.chatModify({ addChatLabel: labelId }, jid)
1349
+ await sock.chatModify({ removeChatLabel: labelId }, jid)
1350
+ await sock.chatModify({ addMessageLabel: labelId }, jid) // + message/messageKey fields
1351
+ await sock.chatModify({ removeMessageLabel: labelId }, jid)
1352
+ ```
1353
+
1354
+ ### Media and uploads
1355
+
1356
+ | Method | What it does |
1357
+ | --- | --- |
1358
+ | `sock.getMediaHost(...)` | Resolve a media upload host |
1359
+ | `sock.updateMediaMessage(message)` | Re-request expired media and update the message |
1360
+ | `sock.uploadPreKeys(count?)` | Upload new pre-keys to the server |
1361
+ | `sock.rotateSignedPreKey(...)` | Rotate your signed pre-key |
1362
+
1363
+ ### Groups
1364
+
1365
+ | Method | What it does |
1366
+ | --- | --- |
1367
+ | `sock.groupCreate(subject, participants)` | Create a group |
1368
+ | `sock.groupLeave(jid)` | Leave a group |
1369
+ | `sock.groupUpdateSubject(jid, subject)` | Rename |
1370
+ | `sock.groupUpdateDescription(jid, description)` | Change description |
1371
+ | `sock.groupParticipantsUpdate(jid, jids, action)` | `'add'`, `'remove'`, `'promote'`, `'demote'` |
1372
+ | `sock.groupRequestParticipantsList(jid)` | Pending join requests |
1373
+ | `sock.groupRequestParticipantsUpdate(jid, jids, action)` | `'approve'` or `'reject'` |
1374
+ | `sock.groupInviteCode(jid)` | Current invite code |
1375
+ | `sock.groupRevokeInvite(jid)` | Reset the invite code |
1376
+ | `sock.groupAcceptInvite(code)` | Join by invite code |
1377
+ | `sock.groupGetInviteInfo(code)` | Info about an invite code |
1378
+ | `sock.groupAcceptInviteV4(jid, code)` | Join using an invite message |
1379
+ | `sock.groupRevokeInviteV4(jid, code)` | Revoke a sent invite |
1380
+ | `sock.groupToggleEphemeral(jid, duration)` | Disappearing messages timer (0 = off) |
1381
+ | `sock.groupSettingUpdate(jid, setting)` | `'announcement'`, `'not_announcement'`, `'locked'`, `'unlocked'` |
1382
+ | `sock.groupMemberAddMode(jid, mode)` | `'admin_add'` or `'all_member_add'` |
1383
+ | `sock.groupJoinApprovalMode(jid, mode)` | `'on'` or `'off'` |
1384
+ | `sock.groupMetadata(jid)` | Full group info |
1385
+
1386
+ ### Communities (groups with linked groups)
1387
+
1388
+ | Method | What it does |
1389
+ | --- | --- |
1390
+ | `sock.communityCreate(name, description?)` | Create a community |
1391
+ | `sock.communityCreateGroup(...)` | Create a group inside a community |
1392
+ | `sock.communityLeave(id)` | Leave/delete |
1393
+ | `sock.communityUpdateSubject(id, subject)` | Rename |
1394
+ | `sock.communityUpdateDescription(id, description)` | Change description |
1395
+ | `sock.communityLinkGroup(id, groupJid)` | Link a group to the community |
1396
+ | `sock.communityUnlinkGroup(id, groupJid)` | Unlink |
1397
+ | `sock.communityFetchLinkedGroups(id)` | List linked groups |
1398
+ | `sock.communityParticipantsUpdate(id, jids, action)` | Manage members |
1399
+ | `sock.communityRequestParticipantsList/Update(...)` | Manage join requests |
1400
+ | `sock.communityInviteCode(id)` / `sock.communityRevokeInvite(id)` | Invite codes |
1401
+ | `sock.communityAcceptInvite(code)` / `sock.communityAcceptInviteV4(...)` | Join |
1402
+ | `sock.communityGetInviteInfo(code)` / `sock.communityRevokeInviteV4(...)` | Invite info |
1403
+ | `sock.communityToggleEphemeral(id, duration)` | Disappearing messages |
1404
+ | `sock.communitySettingUpdate(id, setting)` | Announcement mode |
1405
+ | `sock.communityMemberAddMode(id, mode)` | Who can add members |
1406
+ | `sock.communityJoinApprovalMode(id, mode)` | Approval mode |
1407
+ | `sock.addressingMode(id)` | Community addressing mode |
1408
+
1409
+ ### Newsletters (channels)
1410
+
1411
+ | Method | What it does |
1412
+ | --- | --- |
1413
+ | `sock.newsletterCreate(name, description?)` | Create a channel |
1414
+ | `sock.newsletterDelete(id)` | Delete a channel |
1415
+ | `sock.newsletterUpdateName(id, name)` | Rename |
1416
+ | `sock.newsletterUpdateDescription(id, description)` | Change description |
1417
+ | `sock.newsletterUpdatePicture(id, picture)` | Set picture |
1418
+ | `sock.newsletterRemovePicture(id)` | Remove picture |
1419
+ | `sock.newsletterFollow(id)` | Follow a channel |
1420
+ | `sock.newsletterUnfollow(id)` | Unfollow |
1421
+ | `sock.newsletterMute(id)` / `sock.newsletterUnmute(id)` | Mute/unmute |
1422
+ | `sock.newsletterMetadata(type, key)` | `'invite'` or `'jid'` lookup |
1423
+ | `sock.newsletterSubscribed(id)` | Subscription state |
1424
+ | `sock.newsletterSubscribers(id)` | Subscriber list |
1425
+ | `sock.newsletterAdminCount(id)` | Number of admins |
1426
+ | `sock.newsletterChangeOwner(id, jid)` | Transfer ownership |
1427
+ | `sock.newsletterDemote(id, jid)` | Demote an admin |
1428
+ | `sock.newsletterReactMessage(id, messageId, emoji)` | React to a post |
1429
+ | `sock.newsletterFetchMessages(type, key, count?)` | Fetch posts |
1430
+ | `sock.subscribeNewsletterUpdates(id)` | Live updates for a channel |
1431
+
1432
+ ### Business, calls and advanced queries
1433
+
1434
+ | Method | What it does |
1435
+ | --- | --- |
1436
+ | `sock.getBusinessProfile(jid)` | Business profile info |
1437
+ | `sock.updateBusinessProfile(profile)` | Update your business profile |
1438
+ | `sock.rejectCall(callId, callFrom)` | Reject an incoming call |
1439
+ | `sock.createCallLink(...)` | Create a WhatsApp call link |
1440
+ | `sock.getBotListV2(...)` | List Meta AI bots |
1441
+ | `sock.executeUSyncQuery(query)` | Run a USync query (users, devices, status, LIDs) |
1442
+ | `sock.onWhatsApp(numbers)` | Check which numbers have WhatsApp |
1443
+ | `sock.serverProps` | Server properties |
1444
+ | `sock.resyncAppState(patches, isInitial)` | Force an app-state re-sync |
1445
+ | `sock.fetchMessageHistory(count)` | Request more history |
1446
+ | `sock.requestPlaceholderResend(messageKey)` | Force placeholder resend for undecrypted messages |
1447
+ | `sock.getCachedMessage(messageKey)` | Read the recent-message cache |
1448
+ | `sock.messageRetryManager` | The retry manager instance |
1449
+ | `sock.sendRetryRequest(...)` / `sock.sendMessageAck(...)` | Low-level receipt/ack helpers |
1450
+ | `sock.upsertMessage(...)` | Inject a message locally (advanced) |
1451
+ | `sock.appPatch(...)` | Apply an app-state patch (advanced) |
1452
+ | `sock.sendWAMBuffer(...)` / `sock.wamBuffer` | WhatsApp Analytics events (advanced) |
1453
+ | `sock.digestKeyBundle(...)` | Process a server key bundle |
1454
+ | `sock.sendUnifiedSession(...)` | Unified session ping (advanced) |
1455
+
1456
+ ---
1457
+
1458
+ # Practical guides
1459
+
1460
+ ## Find User ID (PN/LID)
1461
+
1462
+ `sock.findUserId(id)` resolves the two addresses of a user — phone number (PN) and local ID (LID). The input may be either form; the result always has the same shape:
1463
+
1464
+ ```javascript
1465
+ // from a phone-number jid
1466
+ const ids = await sock.findUserId('5511999999999@s.whatsapp.net')
1467
+
1468
+ // from a lid
1469
+ const ids2 = await sock.findUserId('102345678912345@lid')
1470
+
1471
+ console.log(ids)
1472
+ // {
1473
+ // phoneNumber: '5511999999999@s.whatsapp.net',
1474
+ // lid: '102345678912345@lid'
1475
+ // }
1476
+ // (a field is undefined when WhatsApp has no mapping for it)
1477
+ ```
1478
+
1479
+ The input must contain numbers only (no `+`, dashes or parentheses) and include the country code. This is the recommended way to normalize senders inside `messages.upsert` handlers when WhatsApp delivers LID-based keys.
1480
+
1481
+ ## Image processing
1482
+
1483
+ The library picks the best installed image library automatically — `sharp`, then `@napi-rs/image`, then `jimp` — through `getImageProcessingLibrary()`:
1484
+
1485
+ ```javascript
1486
+ import { getImageProcessingLibrary } from '@eduh_dev021/baileys'
1487
+ import { readFile } from 'node:fs/promises'
1488
+
1489
+ const lib = await getImageProcessingLibrary()
1490
+ const source = './photo.jpg'
1491
+ const width = 512
1492
+ let output
1493
+
1494
+ if (lib.sharp?.default) {
1495
+ output = await lib.sharp.default(source).resize(width).jpeg({ quality: 80 }).toBuffer()
1496
+ }
1497
+ else if (lib.image?.Transformer) {
1498
+ const input = Buffer.isBuffer(source) ? source : await readFile(source)
1499
+ output = await new lib.image.Transformer(input).resize(width, undefined, 0).jpeg(80)
1500
+ }
1501
+ else if (lib.jimp?.Jimp) {
1502
+ const img = await lib.jimp.Jimp.read(source)
1503
+ output = await img
1504
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
1505
+ .getBuffer('image/jpeg', { quality: 80 })
1506
+ }
1507
+ else {
1508
+ throw new Error('No image processing library available')
1509
+ }
1510
+ ```
1511
+
1512
+ This is exactly what the library itself uses for thumbnails and sticker conversion — install `sharp` for the best performance. Audio/video features (`getAudioData`, animated stickers, video thumbnails) rely on `ffmpeg`/`ffprobe` on the PATH.
1513
+
1514
+ ## Add-on utilities
1515
+
1516
+ The package ships a small, dependency-free utility layer (used by the library internals, also importable by your app):
1517
+
1518
+ ```javascript
1519
+ import {
1520
+ createCache, createMutex, createQueue, createZip,
1521
+ detectFileType, detectMediaInfo, encodeQR,
1522
+ getAudioWaveform, getFile
1523
+ } from '@eduh_dev021/baileys'
1524
+ ```
1525
+
1526
+ ### `createCache(options?)` — TTL + LRU cache
1527
+
1528
+ ```javascript
1529
+ const cache = createCache({ ttl: 300, max: 1024 }) // ttl in SECONDS, max entries (LRU eviction)
1530
+
1531
+ cache.set('key', value) // optional per-entry ttl: cache.set('k', v, 30)
1532
+ cache.get('key') // undefined when missing or expired (counts hits/misses)
1533
+ cache.has('key') // boolean, no statistics
1534
+ cache.del('key') // delete one/many: cache.del('a', 'b') or an array
1535
+ cache.mset([{ key: 'a', val: 1 }, { key: 'b', val: 2 }])
1536
+ cache.mget('a', 'b') // { a: 1, b: 2 } — missing keys omitted
1537
+ cache.keys() // live keys
1538
+ cache.getStats() // { hits, misses, keys }
1539
+ cache.size // live entry count
1540
+ cache.flushAll() // drop everything
1541
+ cache.close() // stop the internal sweep timer
1542
+ ```
1543
+
1544
+ This is the same cache type the socket uses internally for retry counters and debounce maps — plug your own Map-like objects into the socket options if you want custom behavior.
1545
+
1546
+ ### `createMutex()` — async lock
1547
+
1548
+ ```javascript
1549
+ const mutex = createMutex()
1550
+
1551
+ await mutex.runExclusive(async () => {
1552
+ // only one caller runs this block at a time
1553
+ })
1554
+
1555
+ const release = await mutex.acquire() // manual acquire/release (FIFO queue)
1556
+ release()
1557
+ const release2 = mutex.tryAcquire() // undefined when already locked
1558
+ mutex.isLocked()
1559
+ ```
1560
+
1561
+ ### `createQueue(concurrency?)` — bounded task queue
1562
+
1563
+ ```javascript
1564
+ const queue = createQueue(1) // serialize; any positive number = max parallel tasks
1565
+
1566
+ const result = await queue.add(async () => fetchStuff())
1567
+ await queue.push(taskFn) // push is an alias of add
1568
+ ```
1569
+
1570
+ Tasks run in FIFO order; a failing task rejects only its own promise and never stops the queue.
1571
+
1572
+ ### `createZip(entries)` — in-memory ZIP builder
1573
+
1574
+ ```javascript
1575
+ const zipBuffer = await createZip([
1576
+ { name: 'folder/file.txt', data: Buffer.from('hello') },
1577
+ { name: 'image.webp', data: webpBuffer }
1578
+ ]) // -> Buffer (DEFLATE-compressed, valid ZIP readable by any tool)
1579
+ ```
1580
+
1581
+ This is what powers sticker packs (`stickers` + `cover` are zipped into one upload). Entries accept `Buffer`, `Uint8Array`, strings and Node streams.
1582
+
1583
+ ### `detectFileType(input)` — magic-byte detection
1584
+
1585
+ ```javascript
1586
+ await detectFileType('./voice.ogg') // { mime: 'application/ogg', ext: 'ogx' }
1587
+ await detectFileType(pngBuffer) // { mime: 'image/png', ext: 'png' }
1588
+ await detectFileType(someText) // {} — unknown
1589
+ ```
1590
+
1591
+ Accepts a Buffer/Uint8Array, a file path or a stream. Detection is fully built-in (signature table covering images, audio, video, documents and archives); if the optional `magic-bytes.js` or `file-type` packages are installed they take priority.
1592
+
1593
+ ### `detectMediaInfo(input)` — dimensions and duration
1594
+
1595
+ ```javascript
1596
+ await detectMediaInfo('./video.mp4') // { durationSeconds: 9, width: 1280, height: 720 }
1597
+ await detectMediaInfo('./photo.jpg') // { width: 640, height: 480 }
1598
+ await detectMediaInfo(audioBuffer) // { durationSeconds: 12 }
1599
+ ```
1600
+
1601
+ Uses the system `ffprobe`. Buffers are probed through stdin; unparseable inputs throw an error with the ffprobe message.
1602
+
1603
+ ### `encodeQR(text)` — QR codes for the terminal and PNGs
1604
+
1605
+ ```javascript
1606
+ const { ascii, getPngBuffer, getRaw, version } = await encodeQR('pairing-data-here')
1607
+
1608
+ console.log(ascii) // half-block glyphs, ready to print
1609
+ const png = await getPngBuffer() // grayscale PNG (8 px per module)
1610
+ const matrix = await getRaw() // boolean[][] of dark modules
1611
+ ```
1612
+
1613
+ A complete QR encoder (ISO/IEC 18004, versions 1-40, automatic error-correction and mask selection) — this is what draws the pairing QR for `printQRInTerminal`.
1614
+
1615
+ ### `getAudioWaveform(input)` — voice-note waveform
1616
+
1617
+ ```javascript
1618
+ const { durationSeconds, waveform } = await getAudioWaveform('./voice.ogg')
1619
+ // durationSeconds: 12
1620
+ // waveform: [0, 12, 45, 88, 100, ...] — exactly 64 bars, 0-100, relative loudness
1621
+ ```
1622
+
1623
+ Accepts a path, Buffer or stream and decodes with the system `ffmpeg`. The `waveform` array is what WhatsApp renders inside audio bubbles — `sendMessage` computes it automatically for `ptt: true` voice notes.
1624
+
1625
+ ### `getFile(source)` — normalize any media source to a path
1626
+
1627
+ ```javascript
1628
+ const path = await getFile(buffer) // Buffer -> temp file
1629
+ const path2 = await getFile('https://cdn.site/a.jpg') // URL -> downloaded temp file
1630
+ const path3 = await getFile('./local.jpg') // existing path -> returned as-is
1631
+ const path4 = await getFile(readableStream) // stream -> piped to temp file
1632
+ // non-2xx downloads throw: HTTP 404 Not Found
1633
+ ```
1634
+
1635
+ ---
1636
+
1637
+ # Complete export reference
1638
+
1639
+ The package exports **301 names**: `makeWASocket` (also the default export), plus 213 functions, 54 objects/enums and 34 constants. Everything below is importable from `@eduh_dev021/baileys`.
1640
+
1641
+ ### Session and connection
1642
+
1643
+ | Export | Description |
1644
+ | --- | --- |
1645
+ | `makeWASocket` | Create the socket and connect (default export) |
1646
+ | `useMultiFileAuthState` | Auth state in a folder of JSON files |
1647
+ | `useSingleFileAuthState` | Auth state in one JSON file |
1648
+ | `useSqliteAuthState` | Auth state in SQLite (Bun / node:sqlite / better-sqlite3) |
1649
+ | `initAuthCreds` | Create fresh empty credentials |
1650
+ | `makeCacheableSignalKeyStore` | In-memory cache over any keys store |
1651
+ | `fetchLatestBaileysVersion` | Current WhatsApp Web version |
1652
+ | `fetchLatestWaWebVersion` | Version from the WA Web source |
1653
+ | `generateRegistrationNode` | Build the registration payload |
1654
+ | `generateRegistrationId` | Random registration id |
1655
+ | `generateLoginNode` | Build the login payload |
1656
+ | `generateOrGetPreKeys` / `getNextPreKeys` / `getNextPreKeysNode` | Pre-key management |
1657
+ | `xmppPreKey` / `xmppSignedPreKey` | Build pre-key nodes |
1658
+ | `signedKeyPair` | Create a signed pre-key pair |
1659
+ | `createSignalIdentity` | Create a Signal identity object |
1660
+ | `configureSuccessfulPairing` | Finish pairing (internal) |
1661
+ | `derivePairingCodeKey` | Derive pairing-code keys |
1662
+ | `buildPairingQRData` | Build pairing QR data |
1663
+ | `getCodeFromWSError` / `getErrorCodeFromStreamError` | Map server errors to codes |
1664
+ | `getCompanionPlatformId` / `getPlatformId` / `getCompanionWebClientType` | Platform ids for `browser` |
1665
+ | `bindWaitForConnectionUpdate` / `bindWaitForEvent` | Wait helpers on the event emitter |
1666
+ | `makeEventBuffer` | Buffered event emitter (used by the socket) |
1667
+ | `addTransactionCapability` | Wrap an emitter with transactional emit |
1668
+ | `makeNoiseHandler` | Noise protocol wrapper (internal) |
1669
+ | `handleIdentityChange` | Process identity changes |
1670
+ | `parseAndInjectE2ESessions` | Inject sessions from a bundle |
1671
+ | `extractE2ESessionFromRetryReceipt` / `isMissingKeyError` / `isAppStateSyncIrrecoverable` | Retry/error helpers |
1672
+ | `DisconnectReason` | All disconnect codes (`loggedOut`, `connectionClosed`, ...) |
1673
+ | `Browsers` | `Browsers.macOS('Chrome')`, `ubuntu`, `windows`, `baileys`, `appropriate` |
1674
+ | `DEFAULT_CONNECTION_CONFIG` | All socket defaults |
1675
+
1676
+ ### Messages
1677
+
1678
+ | Export | Description |
1679
+ | --- | --- |
1680
+ | `generateWAMessageContent` | Build message content from a sendable object |
1681
+ | `generateWAMessage` | Content + key + timestamp |
1682
+ | `generateWAMessageFromContent` | Wrap a prepared proto content |
1683
+ | `generateForwardMessageContent` | Build forwardable content |
1684
+ | `generateMessageID` / `generateMessageIDV2` | Message id helpers |
1685
+ | `generateLinkPreviewIfRequired` / `getUrlInfo` | Link previews |
1686
+ | `prepareWAMessageMedia` | Upload media and attach keys |
1687
+ | `prepareRichResponseMessage` | Build rich messages (code, tables, LaTeX) |
1688
+ | `prepareDisappearingMessageSettingContent` | Disappearing config message |
1689
+ | `normalizeMessageContent` | Unwrap view-once/ephemeral/replies/forwards |
1690
+ | `extractMessageContent` | Extract real content from stubs |
1691
+ | `getContentType` | `'conversation'`, `'imageMessage'`, ... |
1692
+ | `assertMediaContent` | Assert a message has media |
1693
+ | `getAggregateVotesInPollMessage` | Aggregate poll votes |
1694
+ | `updateMessageWithPollUpdate` / `updateMessageWithReaction` / `updateMessageWithReceipt` / `updateMessageWithEventResponse` | Merge updates into stored messages |
1695
+ | `aggregateMessageKeysNotFromMe` | Keys of non-self messages |
1696
+ | `isRealMessage` / `shouldIncrementChatUnread` / `cleanMessage` | Message filtering |
1697
+ | `getDevice` / `getKeyAuthor` / `getStatusFromReceiptType` | Receipt helpers |
1698
+ | `generateParticipantHashV2` | Group participant hash |
1699
+ | `getDecryptionJid` / `decryptMessageNode` / `decryptMessageEdit` / `decryptPollVote` / `decryptEventResponse` | Decryption helpers |
1700
+ | `decodeMessageNode` | Decode a received message node |
1701
+ | `encodeWAMessage` / `encodeNewsletterMessage` | Encode message protos |
1702
+ | `wrapToBotForwardedMessage` / `markViewOnce` / `isViewOnceMessage` | Message flags |
1703
+ | `hasValidAlbumMedia` / `hasValidCarouselHeader` / `hasValidInteractiveHeader` | Rich message checks |
1704
+ | `tokenizeCode` | Code tokenization for rich code blocks |
1705
+ | `MessageRetryManager` | Class managing message retries |
1706
+ | `DECRYPTION_RETRY_CONFIG` / `RetryReason` | Retry tuning |
1707
+
1708
+ ### Media download and processing
1709
+
1710
+ | Export | Description |
1711
+ | --- | --- |
1712
+ | `downloadContentFromMessage` | Decrypt a media message into a stream |
1713
+ | `downloadMediaMessage` | Download a whole message to buffer/stream |
1714
+ | `downloadEncryptedContent` / `encryptedStream` | Raw encrypted media streams |
1715
+ | `decryptMediaRetryData` / `encryptMediaRetryRequest` / `getStatusCodeForMediaRetry` / `decodeMediaRetryNode` | Media retry protocol |
1716
+ | `getHttpStream` / `getStream` | HTTP streams |
1717
+ | `downloadExternalBlob` / `downloadExternalPatch` | External media fetch |
1718
+ | `getRawMediaUploadData` / `encodeBase64EncodedStringForUpload` / `getWAUploadToServer` / `uploadWithNodeHttp` | Upload pipeline |
1719
+ | `getMediaKeys` / `MEDIA_KEYS` / `MEDIA_HKDF_KEY_MAPPING` | Media key derivation |
1720
+ | `mediaMessageSHA256B64` / `extensionForMediaMessage` / `MEDIA_PATH_MAP` | Media metadata |
1721
+ | `generateThumbnail` / `extractImageThumb` / `extractVideoThumb` / `generateProfilePicture` / `getAudioData` | Thumbnails, waveforms |
1722
+ | `getImageProcessingLibrary` | Pick sharp/jimp/@napi-rs/image |
1723
+ | `decompressingIfRequired` | Decompress media payloads |
1724
+
1725
+ ### JIDs
1726
+
1727
+ | Export | Description |
1728
+ | --- | --- |
1729
+ | `jidNormalizedUser` | Canonical personal/group jid |
1730
+ | `jidDecode` / `jidEncode` | Parse/build jids |
1731
+ | `areJidsSameUser` | Compare two jids across PN/LID |
1732
+ | `isLidUser` / `isPnUser` / `isHostedLidUser` / `isHostedPnUser` / `assertMeId` | Jid kinds |
1733
+ | `isJidGroup` / `isJidNewsletter` / `isJidBot` / `isJidMetaAI` / `isJidBroadcast` / `isJidStatusBroadcast` | Jid domains |
1734
+ | `getChatId` / `getServerFromDomainType` / `extractAddressingContext` / `extractDeviceJids` / `transferDevice` | Jid utilities |
1735
+ | `S_WHATSAPP_NET` / `WAJIDDomains` | Constants |
1736
+
1737
+ ### Binary nodes and proto
1738
+
1739
+ | Export | Description |
1740
+ | --- | --- |
1741
+ | `encodeBinaryNode` / `decodeBinaryNode` / `binaryNodeToString` | Node ↔ bytes |
1742
+ | `getBinaryNodeChild` / `getBinaryNodeChildren` / `getAllBinaryNodeChildren` | Find child nodes |
1743
+ | `getBinaryNodeChildBuffer` / `getBinaryNodeChildString` / `getBinaryNodeChildUInt` | Typed child access |
1744
+ | `getBinaryNodeMessages` / `reduceBinaryNodeToDictionary` / `assertNodeErrorFree` / `buildAckStanza` | Node helpers |
1745
+ | `proto` / `WAProto` | Full protobuf namespace |
1746
+
1747
+ ### History sync and app state
1748
+
1749
+ | Export | Description |
1750
+ | --- | --- |
1751
+ | `decodeSyncdSnapshot` / `decodeSyncdPatch` / `decodeSyncdMutations` / `decodePatches` | Decode app-state data |
1752
+ | `encodeSyncdPatch` / `extractSyncdPatches` | Build/extract patches |
1753
+ | `processSyncAction` / `processHistoryMessage` / `downloadAndProcessHistorySyncNotification` / `getHistoryMsg` / `downloadHistory` | History processing |
1754
+ | `ensureLTHashStateVersion` / `makeLtHashGenerator` / `newLTHashState` / `LT_HASH_ANTI_TAMPERING` | LT-Hash state |
1755
+ | `ALL_WA_PATCH_NAMES` / `SyncState` / `PROCESSABLE_HISTORY_TYPES` | Patch names and state |
1756
+
1757
+ ### USync (user queries)
1758
+
1759
+ | Export | Description |
1760
+ | --- | --- |
1761
+ | `USyncQuery` | Build queries (device list, status, contact, LID...) |
1762
+ | `USyncUser` | User entry for queries |
1763
+ | `USyncContactProtocol` / `USyncDeviceProtocol` / `USyncDisappearingModeProtocol` / `USyncStatusProtocol` / `USyncUsernameProtocol` | Result protocols |
1764
+
1765
+ ### Crypto primitives
1766
+
1767
+ | Export | Description |
1768
+ | --- | --- |
1769
+ | `Curve` | `generateKeyPair`, `sharedKey`, `sign`, `verify`, `generateSignature`, `generateSignedKeyPair`, `createPublicKeyFromPrivateKey` |
1770
+ | `hkdf` / `hkdfInfoKey` / `hmacSign` | Key derivation |
1771
+ | `md5` / `sha256` | Hashes |
1772
+ | `aesEncrypt` / `aesDecrypt` / `aesEncryptCTR` / `aesDecryptCTR` / `aesEncryptGCM` / `aesDecryptGCM` / `aesEncrypWithIV` / `aesDecryptWithIV` | AES helpers |
1773
+ | `writeRandomPadMax16` / `unpadRandomMax16` / `encodeBigEndian` / `bytesToCrockford` | Byte utilities |
1774
+
1775
+ ### Store
1776
+
1777
+ | Export | Description |
1778
+ | --- | --- |
1779
+ | `makeInMemoryStore` | The store described above |
1780
+ | `waChatKey` / `waMessageID` / `waLabelAssociationKey` | Store ordering keys |
1781
+ | `makeOrderedDictionary` / `ObjectRepository` | Store building blocks |
1782
+
1783
+ ### WAM (analytics)
1784
+
1785
+ | Export | Description |
1786
+ | --- | --- |
1787
+ | `BinaryInfo` / `encodeWAM` | Build analytics event payloads |
1788
+
1789
+ ### Timers and small utilities
1790
+
1791
+ | Export | Description |
1792
+ | --- | --- |
1793
+ | `delay` / `delayCancellable` / `promiseTimeout` / `debouncedTimeout` | Async timing |
1794
+ | `unixTimestampSeconds` | Seconds since epoch |
1795
+ | `toNumber` / `toBuffer` / `toReadable` / `toUnified` | Conversions |
1796
+ | `trimUndefined` / `hasNonNullishProperty` / `hasOptionalProperty` / `isStringNullOrEmpty` | Object helpers |
1797
+ | `BufferJSON` | JSON replacer/reviver that survives Buffers |
1798
+
1799
+ ### Addon utilities
1800
+
1801
+ | Export | Description |
1802
+ | --- | --- |
1803
+ | `createCache` | TTL + LRU in-memory cache (see [Add-on utilities](#add-on-utilities)) |
1804
+ | `createMutex` | Async mutual-exclusion lock (FIFO, used by the auth states) |
1805
+ | `createQueue` | Bounded-concurrency task queue |
1806
+ | `createZip` | In-memory ZIP builder (DEFLATE, powers sticker packs) |
1807
+ | `detectFileType` | Magic-byte file type detection — `{ mime, ext }` |
1808
+ | `detectMediaInfo` | Media dimensions/duration via ffprobe |
1809
+ | `encodeQR` | Full QR encoder — terminal ASCII + PNG (used for pairing) |
1810
+ | `getAudioWaveform` | 64-bar audio waveform via ffmpeg |
1811
+ | `getFile` | Normalize Buffer/URL/stream/path into a local file path |
1812
+ | `HttpError` | Error class with `statusCode` used across the API |
1813
+ | `KeyedDB` | Ordered keyed database (powers the store's chat list) |
1814
+ | `getLinkPreview` | Fetch Open Graph data for a URL |
1815
+
1816
+ ### Other notable constants and objects
1817
+
1818
+ `WAMessageStatus` (status codes), `WAMessageStubType` (stub types), `NACK_REASONS`, `NOISE_WA_HEADER`, `WEBSOCKET_STATES`, `URL_REGEX`, `DEFAULT_CACHE_TTLS`, `DEFAULT_ORIGIN`, `DEF_MEDIA_HOST`, `SERVER_JID`, `STORIES_JID`, `META_AI_JID`, `OFFICIAL_BIZ_JID`, `PSA_WID`, `WA_DEFAULT_EPHEMERAL`, `QueryIds`, `XWAPaths`, `CompanionWebClientType`, `ButtonHeaderType`, `ButtonType`, `CarouselCardType`, `ListType`, `AssociationType`, `ProtocolType`, `NewChatMessageCappingStatusType` (and the OTE/MV variants), `ReachoutTimelockEnforcementType`, `WAMessageAddressingMode`, `WEB_EVENTS`, `WEB_GLOBALS`, `WA_CERT_DETAILS`, `KEY_BUNDLE_TYPE`, `SERVER_ERROR_CODES`, `UNAUTHORIZED_CODES`, `TimeMs`, `INITIAL_PREKEY_COUNT`, `MIN_PREKEY_COUNT`, `MAX_SYNC_ATTEMPTS`, `HISTORY_SYNC_PAUSED_TIMEOUT_MS`, `PLACEHOLDER_MAX_AGE_SECONDS`, `STATUS_EXPIRY_SECONDS`, `DICT_VERSION`, `getCallStatusFromNode`, `getBizBinaryNode`, `shouldIncludeBizBinaryNode` and more.
1819
+
1820
+ ---
1821
+
1822
+ # Common problems
1823
+
1824
+ **"Connection closed" right after connecting** — usually the session expired or WhatsApp logged you out. Delete the session storage and pair again.
1825
+
1826
+ **Send fails with a thumbnail error** — install one of the image libraries (`sharp` is the most common) and make sure `ffmpeg`/`ffprobe` are on your system PATH for videos and audio.
1827
+
1828
+ **Node version error on install** — this package needs Node.js 20 or newer. Check with `node -v`.
1829
+
1830
+ **"No SQLite driver found"** — `useSqliteAuthState` needs Bun, Node.js ≥ 22.13 (`node:sqlite`), or the `better-sqlite3` package. Install `better-sqlite3` if you are on an older Node.
1831
+
1832
+ **Messages not decrypting after a restart** — provide `getMessage` in the socket config (read the original message from your store/database) and keep `enableRecentMessageCache` on.
1833
+
1834
+ **Stickers not converting** — sticker conversion needs `ffmpeg` for animated stickers.
1835
+
1836
+ **Album rejects my message** — the `album` field must be an **array** with at least two image/video items.
1837
+
1838
+ **Buttons/lists not showing on Android** — hydrated templates currently render on WhatsApp Web/Desktop and iOS; on Android they appear only inside newsletters. Use plain buttons (`buttons`) or lists (`sections`) for cross-platform messages.
1839
+
1840
+ **Cannot require the package on Node.js 18** — the CommonJS build requires Node.js 20+ (the package states `engines: >=20`). Upgrade Node.js.
1841
+
1842
+ # License
1843
+
1844
+ Released under the [MIT License](LICENSE). Third-party attributions live in the LICENSE file and in the source file headers (see `lib/WACrypto/`).