@blckrose/baileys 1.0.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 (385) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1312 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +81 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97687 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +128 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +403 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +19 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +271 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +202 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +111 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1037 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +258 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +150 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +327 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +245 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +12 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +187 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1476 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +183 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1043 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +3 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +42 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +160 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +181 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/socket.d.ts +55 -0
  118. package/lib/Socket/socket.d.ts.map +1 -0
  119. package/lib/Socket/socket.js +942 -0
  120. package/lib/Socket/socket.js.map +1 -0
  121. package/lib/Types/Auth.d.ts +116 -0
  122. package/lib/Types/Auth.d.ts.map +1 -0
  123. package/lib/Types/Auth.js +2 -0
  124. package/lib/Types/Auth.js.map +1 -0
  125. package/lib/Types/Bussines.d.ts +25 -0
  126. package/lib/Types/Bussines.d.ts.map +1 -0
  127. package/lib/Types/Bussines.js +2 -0
  128. package/lib/Types/Bussines.js.map +1 -0
  129. package/lib/Types/Call.d.ts +15 -0
  130. package/lib/Types/Call.d.ts.map +1 -0
  131. package/lib/Types/Call.js +2 -0
  132. package/lib/Types/Call.js.map +1 -0
  133. package/lib/Types/Chat.d.ts +123 -0
  134. package/lib/Types/Chat.d.ts.map +1 -0
  135. package/lib/Types/Chat.js +8 -0
  136. package/lib/Types/Chat.js.map +1 -0
  137. package/lib/Types/Contact.d.ts +24 -0
  138. package/lib/Types/Contact.d.ts.map +1 -0
  139. package/lib/Types/Contact.js +2 -0
  140. package/lib/Types/Contact.js.map +1 -0
  141. package/lib/Types/Events.d.ts +237 -0
  142. package/lib/Types/Events.d.ts.map +1 -0
  143. package/lib/Types/Events.js +2 -0
  144. package/lib/Types/Events.js.map +1 -0
  145. package/lib/Types/GroupMetadata.d.ts +67 -0
  146. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  147. package/lib/Types/GroupMetadata.js +2 -0
  148. package/lib/Types/GroupMetadata.js.map +1 -0
  149. package/lib/Types/Label.d.ts +47 -0
  150. package/lib/Types/Label.d.ts.map +1 -0
  151. package/lib/Types/Label.js +25 -0
  152. package/lib/Types/Label.js.map +1 -0
  153. package/lib/Types/LabelAssociation.d.ts +30 -0
  154. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  155. package/lib/Types/LabelAssociation.js +7 -0
  156. package/lib/Types/LabelAssociation.js.map +1 -0
  157. package/lib/Types/Message.d.ts +305 -0
  158. package/lib/Types/Message.d.ts.map +1 -0
  159. package/lib/Types/Message.js +11 -0
  160. package/lib/Types/Message.js.map +1 -0
  161. package/lib/Types/Newsletter.d.ts +135 -0
  162. package/lib/Types/Newsletter.d.ts.map +1 -0
  163. package/lib/Types/Newsletter.js +31 -0
  164. package/lib/Types/Newsletter.js.map +1 -0
  165. package/lib/Types/Product.d.ts +79 -0
  166. package/lib/Types/Product.d.ts.map +1 -0
  167. package/lib/Types/Product.js +2 -0
  168. package/lib/Types/Product.js.map +1 -0
  169. package/lib/Types/Signal.d.ts +76 -0
  170. package/lib/Types/Signal.d.ts.map +1 -0
  171. package/lib/Types/Signal.js +2 -0
  172. package/lib/Types/Signal.js.map +1 -0
  173. package/lib/Types/Socket.d.ts +133 -0
  174. package/lib/Types/Socket.d.ts.map +1 -0
  175. package/lib/Types/Socket.js +3 -0
  176. package/lib/Types/Socket.js.map +1 -0
  177. package/lib/Types/State.d.ts +39 -0
  178. package/lib/Types/State.d.ts.map +1 -0
  179. package/lib/Types/State.js +13 -0
  180. package/lib/Types/State.js.map +1 -0
  181. package/lib/Types/USync.d.ts +26 -0
  182. package/lib/Types/USync.d.ts.map +1 -0
  183. package/lib/Types/USync.js +2 -0
  184. package/lib/Types/USync.js.map +1 -0
  185. package/lib/Types/index.d.ts +65 -0
  186. package/lib/Types/index.d.ts.map +1 -0
  187. package/lib/Types/index.js +26 -0
  188. package/lib/Types/index.js.map +1 -0
  189. package/lib/Utils/auth-utils.d.ts +19 -0
  190. package/lib/Utils/auth-utils.d.ts.map +1 -0
  191. package/lib/Utils/auth-utils.js +290 -0
  192. package/lib/Utils/auth-utils.js.map +1 -0
  193. package/lib/Utils/browser-utils.d.ts +4 -0
  194. package/lib/Utils/browser-utils.d.ts.map +1 -0
  195. package/lib/Utils/browser-utils.js +28 -0
  196. package/lib/Utils/browser-utils.js.map +1 -0
  197. package/lib/Utils/business.d.ts +23 -0
  198. package/lib/Utils/business.d.ts.map +1 -0
  199. package/lib/Utils/business.js +231 -0
  200. package/lib/Utils/business.js.map +1 -0
  201. package/lib/Utils/chat-utils.d.ts +70 -0
  202. package/lib/Utils/chat-utils.d.ts.map +1 -0
  203. package/lib/Utils/chat-utils.js +812 -0
  204. package/lib/Utils/chat-utils.js.map +1 -0
  205. package/lib/Utils/crypto.d.ts +37 -0
  206. package/lib/Utils/crypto.d.ts.map +1 -0
  207. package/lib/Utils/crypto.js +118 -0
  208. package/lib/Utils/crypto.js.map +1 -0
  209. package/lib/Utils/decode-wa-message.d.ts +48 -0
  210. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  211. package/lib/Utils/decode-wa-message.js +283 -0
  212. package/lib/Utils/decode-wa-message.js.map +1 -0
  213. package/lib/Utils/event-buffer.d.ts +34 -0
  214. package/lib/Utils/event-buffer.d.ts.map +1 -0
  215. package/lib/Utils/event-buffer.js +574 -0
  216. package/lib/Utils/event-buffer.js.map +1 -0
  217. package/lib/Utils/generics.d.ts +91 -0
  218. package/lib/Utils/generics.d.ts.map +1 -0
  219. package/lib/Utils/generics.js +384 -0
  220. package/lib/Utils/generics.js.map +1 -0
  221. package/lib/Utils/history.d.ts +22 -0
  222. package/lib/Utils/history.d.ts.map +1 -0
  223. package/lib/Utils/history.js +131 -0
  224. package/lib/Utils/history.js.map +1 -0
  225. package/lib/Utils/identity-change-handler.d.ts +37 -0
  226. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  227. package/lib/Utils/identity-change-handler.js +49 -0
  228. package/lib/Utils/identity-change-handler.js.map +1 -0
  229. package/lib/Utils/index.d.ts +20 -0
  230. package/lib/Utils/index.d.ts.map +1 -0
  231. package/lib/Utils/index.js +20 -0
  232. package/lib/Utils/index.js.map +1 -0
  233. package/lib/Utils/link-preview.d.ts +21 -0
  234. package/lib/Utils/link-preview.d.ts.map +1 -0
  235. package/lib/Utils/link-preview.js +85 -0
  236. package/lib/Utils/link-preview.js.map +1 -0
  237. package/lib/Utils/logger.d.ts +13 -0
  238. package/lib/Utils/logger.d.ts.map +1 -0
  239. package/lib/Utils/logger.js +3 -0
  240. package/lib/Utils/logger.js.map +1 -0
  241. package/lib/Utils/lt-hash.d.ts +8 -0
  242. package/lib/Utils/lt-hash.d.ts.map +1 -0
  243. package/lib/Utils/lt-hash.js +8 -0
  244. package/lib/Utils/lt-hash.js.map +1 -0
  245. package/lib/Utils/make-mutex.d.ts +9 -0
  246. package/lib/Utils/make-mutex.d.ts.map +1 -0
  247. package/lib/Utils/make-mutex.js +33 -0
  248. package/lib/Utils/make-mutex.js.map +1 -0
  249. package/lib/Utils/message-retry-manager.d.ts +110 -0
  250. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  251. package/lib/Utils/message-retry-manager.js +225 -0
  252. package/lib/Utils/message-retry-manager.js.map +1 -0
  253. package/lib/Utils/messages-media.d.ts +130 -0
  254. package/lib/Utils/messages-media.d.ts.map +1 -0
  255. package/lib/Utils/messages-media.js +774 -0
  256. package/lib/Utils/messages-media.js.map +1 -0
  257. package/lib/Utils/messages.d.ts +91 -0
  258. package/lib/Utils/messages.d.ts.map +1 -0
  259. package/lib/Utils/messages.js +870 -0
  260. package/lib/Utils/messages.js.map +1 -0
  261. package/lib/Utils/noise-handler.d.ts +20 -0
  262. package/lib/Utils/noise-handler.d.ts.map +1 -0
  263. package/lib/Utils/noise-handler.js +201 -0
  264. package/lib/Utils/noise-handler.js.map +1 -0
  265. package/lib/Utils/pre-key-manager.d.ts +28 -0
  266. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  267. package/lib/Utils/pre-key-manager.js +106 -0
  268. package/lib/Utils/pre-key-manager.js.map +1 -0
  269. package/lib/Utils/process-message.d.ts +60 -0
  270. package/lib/Utils/process-message.d.ts.map +1 -0
  271. package/lib/Utils/process-message.js +528 -0
  272. package/lib/Utils/process-message.js.map +1 -0
  273. package/lib/Utils/reporting-utils.d.ts +11 -0
  274. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  275. package/lib/Utils/reporting-utils.js +258 -0
  276. package/lib/Utils/reporting-utils.js.map +1 -0
  277. package/lib/Utils/signal.d.ts +34 -0
  278. package/lib/Utils/signal.d.ts.map +1 -0
  279. package/lib/Utils/signal.js +159 -0
  280. package/lib/Utils/signal.js.map +1 -0
  281. package/lib/Utils/sync-action-utils.d.ts +19 -0
  282. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  283. package/lib/Utils/sync-action-utils.js +48 -0
  284. package/lib/Utils/sync-action-utils.js.map +1 -0
  285. package/lib/Utils/tc-token-utils.d.ts +12 -0
  286. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  287. package/lib/Utils/tc-token-utils.js +18 -0
  288. package/lib/Utils/tc-token-utils.js.map +1 -0
  289. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  290. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  291. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  292. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  293. package/lib/Utils/validate-connection.d.ts +11 -0
  294. package/lib/Utils/validate-connection.d.ts.map +1 -0
  295. package/lib/Utils/validate-connection.js +200 -0
  296. package/lib/Utils/validate-connection.js.map +1 -0
  297. package/lib/WABinary/constants.d.ts +28 -0
  298. package/lib/WABinary/constants.d.ts.map +1 -0
  299. package/lib/WABinary/constants.js +1301 -0
  300. package/lib/WABinary/constants.js.map +1 -0
  301. package/lib/WABinary/decode.d.ts +7 -0
  302. package/lib/WABinary/decode.d.ts.map +1 -0
  303. package/lib/WABinary/decode.js +262 -0
  304. package/lib/WABinary/decode.js.map +1 -0
  305. package/lib/WABinary/encode.d.ts +3 -0
  306. package/lib/WABinary/encode.d.ts.map +1 -0
  307. package/lib/WABinary/encode.js +220 -0
  308. package/lib/WABinary/encode.js.map +1 -0
  309. package/lib/WABinary/generic-utils.d.ts +15 -0
  310. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  311. package/lib/WABinary/generic-utils.js +113 -0
  312. package/lib/WABinary/generic-utils.js.map +1 -0
  313. package/lib/WABinary/index.d.ts +6 -0
  314. package/lib/WABinary/index.d.ts.map +1 -0
  315. package/lib/WABinary/index.js +6 -0
  316. package/lib/WABinary/index.js.map +1 -0
  317. package/lib/WABinary/jid-utils.d.ts +48 -0
  318. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  319. package/lib/WABinary/jid-utils.js +96 -0
  320. package/lib/WABinary/jid-utils.js.map +1 -0
  321. package/lib/WABinary/types.d.ts +19 -0
  322. package/lib/WABinary/types.d.ts.map +1 -0
  323. package/lib/WABinary/types.js +2 -0
  324. package/lib/WABinary/types.js.map +1 -0
  325. package/lib/WAM/BinaryInfo.d.ts +9 -0
  326. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  327. package/lib/WAM/BinaryInfo.js +10 -0
  328. package/lib/WAM/BinaryInfo.js.map +1 -0
  329. package/lib/WAM/constants.d.ts +40 -0
  330. package/lib/WAM/constants.d.ts.map +1 -0
  331. package/lib/WAM/constants.js +22853 -0
  332. package/lib/WAM/constants.js.map +1 -0
  333. package/lib/WAM/encode.d.ts +3 -0
  334. package/lib/WAM/encode.d.ts.map +1 -0
  335. package/lib/WAM/encode.js +150 -0
  336. package/lib/WAM/encode.js.map +1 -0
  337. package/lib/WAM/index.d.ts +4 -0
  338. package/lib/WAM/index.d.ts.map +1 -0
  339. package/lib/WAM/index.js +4 -0
  340. package/lib/WAM/index.js.map +1 -0
  341. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  342. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  343. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  344. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  345. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  346. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  347. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  348. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  349. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  350. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  351. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  352. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  353. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  354. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  355. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  356. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  357. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  358. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  360. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  362. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  364. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  366. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/index.js +5 -0
  368. package/lib/WAUSync/Protocols/index.js.map +1 -0
  369. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  370. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  371. package/lib/WAUSync/USyncQuery.js +94 -0
  372. package/lib/WAUSync/USyncQuery.js.map +1 -0
  373. package/lib/WAUSync/USyncUser.d.ts +13 -0
  374. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  375. package/lib/WAUSync/USyncUser.js +23 -0
  376. package/lib/WAUSync/USyncUser.js.map +1 -0
  377. package/lib/WAUSync/index.d.ts +4 -0
  378. package/lib/WAUSync/index.d.ts.map +1 -0
  379. package/lib/WAUSync/index.js +4 -0
  380. package/lib/WAUSync/index.js.map +1 -0
  381. package/lib/index.d.ts +12 -0
  382. package/lib/index.d.ts.map +1 -0
  383. package/lib/index.js +11 -0
  384. package/lib/index.js.map +1 -0
  385. package/package.json +58 -0
@@ -0,0 +1,1037 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
+ import { SyncState } from '../Types/State.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
8
+ import { makeMutex } from '../Utils/make-mutex.js';
9
+ import processMessage from '../Utils/process-message.js';
10
+ import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeSocket } from './socket.js';
14
+ const MAX_SYNC_ATTEMPTS = 2;
15
+ export const makeChatsSocket = (config) => {
16
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
17
+ const sock = makeSocket(config);
18
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
19
+ let privacySettings;
20
+ let syncState = SyncState.Connecting;
21
+ /** this mutex ensures that messages are processed in order */
22
+ const messageMutex = makeMutex();
23
+ /** this mutex ensures that receipts are processed in order */
24
+ const receiptMutex = makeMutex();
25
+ /** this mutex ensures that app state patches are processed in order */
26
+ const appStatePatchMutex = makeMutex();
27
+ /** this mutex ensures that notifications are processed in order */
28
+ const notificationMutex = makeMutex();
29
+ // Timeout for AwaitingInitialSync state
30
+ let awaitingSyncTimeout;
31
+ const placeholderResendCache = config.placeholderResendCache ||
32
+ new NodeCache({
33
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
36
+ if (!config.placeholderResendCache) {
37
+ config.placeholderResendCache = placeholderResendCache;
38
+ }
39
+ /** helper function to fetch the given app state sync key */
40
+ const getAppStateSyncKey = async (keyId) => {
41
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
42
+ return key;
43
+ };
44
+ const fetchPrivacySettings = async (force = false) => {
45
+ if (!privacySettings || force) {
46
+ const { content } = await query({
47
+ tag: 'iq',
48
+ attrs: {
49
+ xmlns: 'privacy',
50
+ to: S_WHATSAPP_NET,
51
+ type: 'get'
52
+ },
53
+ content: [{ tag: 'privacy', attrs: {} }]
54
+ });
55
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
56
+ }
57
+ return privacySettings;
58
+ };
59
+ /** helper function to run a privacy IQ query */
60
+ const privacyQuery = async (name, value) => {
61
+ await query({
62
+ tag: 'iq',
63
+ attrs: {
64
+ xmlns: 'privacy',
65
+ to: S_WHATSAPP_NET,
66
+ type: 'set'
67
+ },
68
+ content: [
69
+ {
70
+ tag: 'privacy',
71
+ attrs: {},
72
+ content: [
73
+ {
74
+ tag: 'category',
75
+ attrs: { name, value }
76
+ }
77
+ ]
78
+ }
79
+ ]
80
+ });
81
+ };
82
+ const updateMessagesPrivacy = async (value) => {
83
+ await privacyQuery('messages', value);
84
+ };
85
+ const updateCallPrivacy = async (value) => {
86
+ await privacyQuery('calladd', value);
87
+ };
88
+ const updateLastSeenPrivacy = async (value) => {
89
+ await privacyQuery('last', value);
90
+ };
91
+ const updateOnlinePrivacy = async (value) => {
92
+ await privacyQuery('online', value);
93
+ };
94
+ const updateProfilePicturePrivacy = async (value) => {
95
+ await privacyQuery('profile', value);
96
+ };
97
+ const updateStatusPrivacy = async (value) => {
98
+ await privacyQuery('status', value);
99
+ };
100
+ const updateReadReceiptsPrivacy = async (value) => {
101
+ await privacyQuery('readreceipts', value);
102
+ };
103
+ const updateGroupsAddPrivacy = async (value) => {
104
+ await privacyQuery('groupadd', value);
105
+ };
106
+ const updateDefaultDisappearingMode = async (duration) => {
107
+ await query({
108
+ tag: 'iq',
109
+ attrs: {
110
+ xmlns: 'disappearing_mode',
111
+ to: S_WHATSAPP_NET,
112
+ type: 'set'
113
+ },
114
+ content: [
115
+ {
116
+ tag: 'disappearing_mode',
117
+ attrs: {
118
+ duration: duration.toString()
119
+ }
120
+ }
121
+ ]
122
+ });
123
+ };
124
+ const getBotListV2 = async () => {
125
+ const resp = await query({
126
+ tag: 'iq',
127
+ attrs: {
128
+ xmlns: 'bot',
129
+ to: S_WHATSAPP_NET,
130
+ type: 'get'
131
+ },
132
+ content: [
133
+ {
134
+ tag: 'bot',
135
+ attrs: {
136
+ v: '2'
137
+ }
138
+ }
139
+ ]
140
+ });
141
+ const botNode = getBinaryNodeChild(resp, 'bot');
142
+ const botList = [];
143
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
144
+ if (section.attrs.type === 'all') {
145
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
146
+ botList.push({
147
+ jid: bot.attrs.jid,
148
+ personaId: bot.attrs['persona_id']
149
+ });
150
+ }
151
+ }
152
+ }
153
+ return botList;
154
+ };
155
+ const fetchStatus = async (...jids) => {
156
+ const usyncQuery = new USyncQuery().withStatusProtocol();
157
+ for (const jid of jids) {
158
+ usyncQuery.withUser(new USyncUser().withId(jid));
159
+ }
160
+ const result = await sock.executeUSyncQuery(usyncQuery);
161
+ if (result) {
162
+ return result.list;
163
+ }
164
+ };
165
+ const fetchDisappearingDuration = async (...jids) => {
166
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
167
+ for (const jid of jids) {
168
+ usyncQuery.withUser(new USyncUser().withId(jid));
169
+ }
170
+ const result = await sock.executeUSyncQuery(usyncQuery);
171
+ if (result) {
172
+ return result.list;
173
+ }
174
+ };
175
+ /** update the profile picture for yourself or a group */
176
+ const updateProfilePicture = async (jid, content, dimensions) => {
177
+ let targetJid;
178
+ if (!jid) {
179
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
180
+ }
181
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
182
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
183
+ }
184
+ else {
185
+ targetJid = undefined;
186
+ }
187
+ const { img } = await generateProfilePicture(content, dimensions);
188
+ await query({
189
+ tag: 'iq',
190
+ attrs: {
191
+ to: S_WHATSAPP_NET,
192
+ type: 'set',
193
+ xmlns: 'w:profile:picture',
194
+ ...(targetJid ? { target: targetJid } : {})
195
+ },
196
+ content: [
197
+ {
198
+ tag: 'picture',
199
+ attrs: { type: 'image' },
200
+ content: img
201
+ }
202
+ ]
203
+ });
204
+ };
205
+ /** remove the profile picture for yourself or a group */
206
+ const removeProfilePicture = async (jid) => {
207
+ let targetJid;
208
+ if (!jid) {
209
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
210
+ }
211
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
212
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
213
+ }
214
+ else {
215
+ targetJid = undefined;
216
+ }
217
+ await query({
218
+ tag: 'iq',
219
+ attrs: {
220
+ to: S_WHATSAPP_NET,
221
+ type: 'set',
222
+ xmlns: 'w:profile:picture',
223
+ ...(targetJid ? { target: targetJid } : {})
224
+ }
225
+ });
226
+ };
227
+ /** update the profile status for yourself */
228
+ const updateProfileStatus = async (status) => {
229
+ await query({
230
+ tag: 'iq',
231
+ attrs: {
232
+ to: S_WHATSAPP_NET,
233
+ type: 'set',
234
+ xmlns: 'status'
235
+ },
236
+ content: [
237
+ {
238
+ tag: 'status',
239
+ attrs: {},
240
+ content: Buffer.from(status, 'utf-8')
241
+ }
242
+ ]
243
+ });
244
+ };
245
+ const updateProfileName = async (name) => {
246
+ await chatModify({ pushNameSetting: name }, '');
247
+ };
248
+ const fetchBlocklist = async () => {
249
+ const result = await query({
250
+ tag: 'iq',
251
+ attrs: {
252
+ xmlns: 'blocklist',
253
+ to: S_WHATSAPP_NET,
254
+ type: 'get'
255
+ }
256
+ });
257
+ const listNode = getBinaryNodeChild(result, 'list');
258
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
259
+ };
260
+ const updateBlockStatus = async (jid, action) => {
261
+ await query({
262
+ tag: 'iq',
263
+ attrs: {
264
+ xmlns: 'blocklist',
265
+ to: S_WHATSAPP_NET,
266
+ type: 'set'
267
+ },
268
+ content: [
269
+ {
270
+ tag: 'item',
271
+ attrs: {
272
+ action,
273
+ jid
274
+ }
275
+ }
276
+ ]
277
+ });
278
+ };
279
+ const getBusinessProfile = async (jid) => {
280
+ const results = await query({
281
+ tag: 'iq',
282
+ attrs: {
283
+ to: 's.whatsapp.net',
284
+ xmlns: 'w:biz',
285
+ type: 'get'
286
+ },
287
+ content: [
288
+ {
289
+ tag: 'business_profile',
290
+ attrs: { v: '244' },
291
+ content: [
292
+ {
293
+ tag: 'profile',
294
+ attrs: { jid }
295
+ }
296
+ ]
297
+ }
298
+ ]
299
+ });
300
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
301
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
302
+ if (profiles) {
303
+ const address = getBinaryNodeChild(profiles, 'address');
304
+ const description = getBinaryNodeChild(profiles, 'description');
305
+ const website = getBinaryNodeChild(profiles, 'website');
306
+ const email = getBinaryNodeChild(profiles, 'email');
307
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
308
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
309
+ const businessHoursConfig = businessHours
310
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
311
+ : undefined;
312
+ const websiteStr = website?.content?.toString();
313
+ return {
314
+ wid: profiles.attrs?.jid,
315
+ address: address?.content?.toString(),
316
+ description: description?.content?.toString() || '',
317
+ website: websiteStr ? [websiteStr] : [],
318
+ email: email?.content?.toString(),
319
+ category: category?.content?.toString(),
320
+ business_hours: {
321
+ timezone: businessHours?.attrs?.timezone,
322
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
323
+ }
324
+ };
325
+ }
326
+ };
327
+ const cleanDirtyBits = async (type, fromTimestamp) => {
328
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
329
+ await sendNode({
330
+ tag: 'iq',
331
+ attrs: {
332
+ to: S_WHATSAPP_NET,
333
+ type: 'set',
334
+ xmlns: 'urn:xmpp:whatsapp:dirty',
335
+ id: generateMessageTag()
336
+ },
337
+ content: [
338
+ {
339
+ tag: 'clean',
340
+ attrs: {
341
+ type,
342
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
343
+ }
344
+ }
345
+ ]
346
+ });
347
+ };
348
+ const newAppStateChunkHandler = (isInitialSync) => {
349
+ return {
350
+ onMutation(mutation) {
351
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
352
+ }
353
+ };
354
+ };
355
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
356
+ const appStateSyncKeyCache = new Map();
357
+ const getCachedAppStateSyncKey = async (keyId) => {
358
+ if (appStateSyncKeyCache.has(keyId)) {
359
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
360
+ }
361
+ const key = await getAppStateSyncKey(keyId);
362
+ appStateSyncKeyCache.set(keyId, key ?? null);
363
+ return key;
364
+ };
365
+ // we use this to determine which events to fire
366
+ // otherwise when we resync from scratch -- all notifications will fire
367
+ const initialVersionMap = {};
368
+ const globalMutationMap = {};
369
+ await authState.keys.transaction(async () => {
370
+ const collectionsToHandle = new Set(collections);
371
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
372
+ const attemptsMap = {};
373
+ // keep executing till all collections are done
374
+ // sometimes a single patch request will not return all the patches (God knows why)
375
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
376
+ while (collectionsToHandle.size) {
377
+ const states = {};
378
+ const nodes = [];
379
+ for (const name of collectionsToHandle) {
380
+ const result = await authState.keys.get('app-state-sync-version', [name]);
381
+ let state = result[name];
382
+ if (state) {
383
+ if (typeof initialVersionMap[name] === 'undefined') {
384
+ initialVersionMap[name] = state.version;
385
+ }
386
+ }
387
+ else {
388
+ state = newLTHashState();
389
+ }
390
+ states[name] = state;
391
+ logger.info(`resyncing ${name} from v${state.version}`);
392
+ nodes.push({
393
+ tag: 'collection',
394
+ attrs: {
395
+ name,
396
+ version: state.version.toString(),
397
+ // return snapshot if being synced from scratch
398
+ return_snapshot: (!state.version).toString()
399
+ }
400
+ });
401
+ }
402
+ const result = await query({
403
+ tag: 'iq',
404
+ attrs: {
405
+ to: S_WHATSAPP_NET,
406
+ xmlns: 'w:sync:app:state',
407
+ type: 'set'
408
+ },
409
+ content: [
410
+ {
411
+ tag: 'sync',
412
+ attrs: {},
413
+ content: nodes
414
+ }
415
+ ]
416
+ });
417
+ // extract from binary node
418
+ const decoded = await extractSyncdPatches(result, config?.options);
419
+ for (const key in decoded) {
420
+ const name = key;
421
+ const { patches, hasMorePatches, snapshot } = decoded[name];
422
+ try {
423
+ if (snapshot) {
424
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
425
+ states[name] = newState;
426
+ Object.assign(globalMutationMap, mutationMap);
427
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
428
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
429
+ }
430
+ // only process if there are syncd patches
431
+ if (patches.length) {
432
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
433
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
434
+ logger.info(`synced ${name} to v${newState.version}`);
435
+ initialVersionMap[name] = newState.version;
436
+ Object.assign(globalMutationMap, mutationMap);
437
+ }
438
+ if (hasMorePatches) {
439
+ logger.info(`${name} has more patches...`);
440
+ }
441
+ else {
442
+ // collection is done with sync
443
+ collectionsToHandle.delete(name);
444
+ }
445
+ }
446
+ catch (error) {
447
+ // if retry attempts overshoot
448
+ // or key not found
449
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
450
+ error.output?.statusCode === 404 ||
451
+ error.name === 'TypeError';
452
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
453
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
454
+ // increment number of retries
455
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
456
+ if (isIrrecoverableError) {
457
+ // stop retrying
458
+ collectionsToHandle.delete(name);
459
+ }
460
+ }
461
+ }
462
+ }
463
+ }, authState?.creds?.me?.id || 'resync-app-state');
464
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
465
+ for (const key in globalMutationMap) {
466
+ onMutation(globalMutationMap[key]);
467
+ }
468
+ });
469
+ /**
470
+ * fetch the profile picture of a user/group
471
+ * type = "preview" for a low res picture
472
+ * type = "image for the high res picture"
473
+ */
474
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
475
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
476
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent });
477
+ jid = jidNormalizedUser(jid);
478
+ const result = await query({
479
+ tag: 'iq',
480
+ attrs: {
481
+ target: jid,
482
+ to: S_WHATSAPP_NET,
483
+ type: 'get',
484
+ xmlns: 'w:profile:picture'
485
+ },
486
+ content: tcTokenContent
487
+ }, timeoutMs);
488
+ const child = getBinaryNodeChild(result, 'picture');
489
+ return child?.attrs?.url;
490
+ };
491
+ const createCallLink = async (type, event, timeoutMs) => {
492
+ const result = await query({
493
+ tag: 'call',
494
+ attrs: {
495
+ id: generateMessageTag(),
496
+ to: '@call'
497
+ },
498
+ content: [
499
+ {
500
+ tag: 'link_create',
501
+ attrs: { media: type },
502
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
503
+ }
504
+ ]
505
+ }, timeoutMs);
506
+ const child = getBinaryNodeChild(result, 'link_create');
507
+ return child?.attrs?.token;
508
+ };
509
+ const sendPresenceUpdate = async (type, toJid) => {
510
+ const me = authState.creds.me;
511
+ const isAvailableType = type === 'available';
512
+ if (isAvailableType || type === 'unavailable') {
513
+ if (!me.name) {
514
+ logger.warn('no name present, ignoring presence update request...');
515
+ return;
516
+ }
517
+ ev.emit('connection.update', { isOnline: isAvailableType });
518
+ if (isAvailableType) {
519
+ void sendUnifiedSession();
520
+ }
521
+ await sendNode({
522
+ tag: 'presence',
523
+ attrs: {
524
+ name: me.name.replace(/@/g, ''),
525
+ type
526
+ }
527
+ });
528
+ }
529
+ else {
530
+ const { server } = jidDecode(toJid);
531
+ const isLid = server === 'lid';
532
+ await sendNode({
533
+ tag: 'chatstate',
534
+ attrs: {
535
+ from: isLid ? me.lid : me.id,
536
+ to: toJid
537
+ },
538
+ content: [
539
+ {
540
+ tag: type === 'recording' ? 'composing' : type,
541
+ attrs: type === 'recording' ? { media: 'audio' } : {}
542
+ }
543
+ ]
544
+ });
545
+ }
546
+ };
547
+ /**
548
+ * @param toJid the jid to subscribe to
549
+ * @param tcToken token for subscription, use if present
550
+ */
551
+ const presenceSubscribe = async (toJid) => {
552
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid });
553
+ return sendNode({
554
+ tag: 'presence',
555
+ attrs: {
556
+ to: toJid,
557
+ id: generateMessageTag(),
558
+ type: 'subscribe'
559
+ },
560
+ content: tcTokenContent
561
+ });
562
+ };
563
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
564
+ let presence;
565
+ const jid = attrs.from;
566
+ const participant = attrs.participant || attrs.from;
567
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
568
+ return;
569
+ }
570
+ if (tag === 'presence') {
571
+ presence = {
572
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
573
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
574
+ };
575
+ }
576
+ else if (Array.isArray(content)) {
577
+ const [firstChild] = content;
578
+ let type = firstChild.tag;
579
+ if (type === 'paused') {
580
+ type = 'available';
581
+ }
582
+ if (firstChild.attrs?.media === 'audio') {
583
+ type = 'recording';
584
+ }
585
+ presence = { lastKnownPresence: type };
586
+ }
587
+ else {
588
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
589
+ }
590
+ if (presence) {
591
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
592
+ }
593
+ };
594
+ const appPatch = async (patchCreate) => {
595
+ const name = patchCreate.type;
596
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
597
+ if (!myAppStateKeyId) {
598
+ throw new Boom('App state key not present!', { statusCode: 400 });
599
+ }
600
+ let initial;
601
+ let encodeResult;
602
+ await appStatePatchMutex.mutex(async () => {
603
+ await authState.keys.transaction(async () => {
604
+ logger.debug({ patch: patchCreate }, 'applying app patch');
605
+ await resyncAppState([name], false);
606
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
607
+ initial = currentSyncVersion || newLTHashState();
608
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
609
+ const { patch, state } = encodeResult;
610
+ const node = {
611
+ tag: 'iq',
612
+ attrs: {
613
+ to: S_WHATSAPP_NET,
614
+ type: 'set',
615
+ xmlns: 'w:sync:app:state'
616
+ },
617
+ content: [
618
+ {
619
+ tag: 'sync',
620
+ attrs: {},
621
+ content: [
622
+ {
623
+ tag: 'collection',
624
+ attrs: {
625
+ name,
626
+ version: (state.version - 1).toString(),
627
+ return_snapshot: 'false'
628
+ },
629
+ content: [
630
+ {
631
+ tag: 'patch',
632
+ attrs: {},
633
+ content: proto.SyncdPatch.encode(patch).finish()
634
+ }
635
+ ]
636
+ }
637
+ ]
638
+ }
639
+ ]
640
+ };
641
+ await query(node);
642
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
643
+ }, authState?.creds?.me?.id || 'app-patch');
644
+ });
645
+ if (config.emitOwnEvents) {
646
+ const { onMutation } = newAppStateChunkHandler(false);
647
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
648
+ for (const key in mutationMap) {
649
+ onMutation(mutationMap[key]);
650
+ }
651
+ }
652
+ };
653
+ /** sending non-abt props may fix QR scan fail if server expects */
654
+ const fetchProps = async () => {
655
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
656
+ const resultNode = await query({
657
+ tag: 'iq',
658
+ attrs: {
659
+ to: S_WHATSAPP_NET,
660
+ xmlns: 'w',
661
+ type: 'get'
662
+ },
663
+ content: [
664
+ {
665
+ tag: 'props',
666
+ attrs: {
667
+ protocol: '2',
668
+ hash: authState?.creds?.lastPropHash || ''
669
+ }
670
+ }
671
+ ]
672
+ });
673
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
674
+ let props = {};
675
+ if (propsNode) {
676
+ if (propsNode.attrs?.hash) {
677
+ // on some clients, the hash is returning as undefined
678
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
679
+ ev.emit('creds.update', authState.creds);
680
+ }
681
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
682
+ }
683
+ logger.debug('fetched props');
684
+ return props;
685
+ };
686
+ /**
687
+ * modify a chat -- mark unread, read etc.
688
+ * lastMessages must be sorted in reverse chronologically
689
+ * requires the last messages till the last message received; required for archive & unread
690
+ */
691
+ const chatModify = (mod, jid) => {
692
+ const patch = chatModificationToAppPatch(mod, jid);
693
+ return appPatch(patch);
694
+ };
695
+ /**
696
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
697
+ */
698
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
699
+ return chatModify({
700
+ disableLinkPreviews: { isPreviewsDisabled }
701
+ }, '');
702
+ };
703
+ /**
704
+ * Star or Unstar a message
705
+ */
706
+ const star = (jid, messages, star) => {
707
+ return chatModify({
708
+ star: {
709
+ messages,
710
+ star
711
+ }
712
+ }, jid);
713
+ };
714
+ /**
715
+ * Add or Edit Contact
716
+ */
717
+ const addOrEditContact = (jid, contact) => {
718
+ return chatModify({
719
+ contact
720
+ }, jid);
721
+ };
722
+ /**
723
+ * Remove Contact
724
+ */
725
+ const removeContact = (jid) => {
726
+ return chatModify({
727
+ contact: null
728
+ }, jid);
729
+ };
730
+ /**
731
+ * Adds label
732
+ */
733
+ const addLabel = (jid, labels) => {
734
+ return chatModify({
735
+ addLabel: {
736
+ ...labels
737
+ }
738
+ }, jid);
739
+ };
740
+ /**
741
+ * Adds label for the chats
742
+ */
743
+ const addChatLabel = (jid, labelId) => {
744
+ return chatModify({
745
+ addChatLabel: {
746
+ labelId
747
+ }
748
+ }, jid);
749
+ };
750
+ /**
751
+ * Removes label for the chat
752
+ */
753
+ const removeChatLabel = (jid, labelId) => {
754
+ return chatModify({
755
+ removeChatLabel: {
756
+ labelId
757
+ }
758
+ }, jid);
759
+ };
760
+ /**
761
+ * Adds label for the message
762
+ */
763
+ const addMessageLabel = (jid, messageId, labelId) => {
764
+ return chatModify({
765
+ addMessageLabel: {
766
+ messageId,
767
+ labelId
768
+ }
769
+ }, jid);
770
+ };
771
+ /**
772
+ * Removes label for the message
773
+ */
774
+ const removeMessageLabel = (jid, messageId, labelId) => {
775
+ return chatModify({
776
+ removeMessageLabel: {
777
+ messageId,
778
+ labelId
779
+ }
780
+ }, jid);
781
+ };
782
+ /**
783
+ * Add or Edit Quick Reply
784
+ */
785
+ const addOrEditQuickReply = (quickReply) => {
786
+ return chatModify({
787
+ quickReply
788
+ }, '');
789
+ };
790
+ /**
791
+ * Remove Quick Reply
792
+ */
793
+ const removeQuickReply = (timestamp) => {
794
+ return chatModify({
795
+ quickReply: { timestamp, deleted: true }
796
+ }, '');
797
+ };
798
+ /**
799
+ * queries need to be fired on connection open
800
+ * help ensure parity with WA Web
801
+ * */
802
+ const executeInitQueries = async () => {
803
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
804
+ };
805
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
806
+ ev.emit('messages.upsert', { messages: [msg], type });
807
+ if (!!msg.pushName) {
808
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
809
+ jid = jidNormalizedUser(jid);
810
+ if (!msg.key.fromMe) {
811
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
812
+ }
813
+ // update our pushname too
814
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
815
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
816
+ }
817
+ }
818
+ const historyMsg = getHistoryMsg(msg.message);
819
+ const shouldProcessHistoryMsg = historyMsg
820
+ ? shouldSyncHistoryMessage(historyMsg) &&
821
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
822
+ : false;
823
+ // State machine: decide on sync and flush
824
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
825
+ if (awaitingSyncTimeout) {
826
+ clearTimeout(awaitingSyncTimeout);
827
+ awaitingSyncTimeout = undefined;
828
+ }
829
+ if (shouldProcessHistoryMsg) {
830
+ syncState = SyncState.Syncing;
831
+ logger.info('Transitioned to Syncing state');
832
+ // Let doAppStateSync handle the final flush after it's done
833
+ }
834
+ else {
835
+ syncState = SyncState.Online;
836
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
837
+ ev.flush();
838
+ }
839
+ }
840
+ const doAppStateSync = async () => {
841
+ if (syncState === SyncState.Syncing) {
842
+ logger.info('Doing app state sync');
843
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
844
+ // Sync is complete, go online and flush everything
845
+ syncState = SyncState.Online;
846
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
847
+ ev.flush();
848
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
849
+ ev.emit('creds.update', { accountSyncCounter });
850
+ }
851
+ };
852
+ await Promise.all([
853
+ (async () => {
854
+ if (shouldProcessHistoryMsg) {
855
+ await doAppStateSync();
856
+ }
857
+ })(),
858
+ processMessage(msg, {
859
+ signalRepository,
860
+ shouldProcessHistoryMsg,
861
+ placeholderResendCache,
862
+ ev,
863
+ creds: authState.creds,
864
+ keyStore: authState.keys,
865
+ logger,
866
+ options: config.options,
867
+ getMessage
868
+ })
869
+ ]);
870
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
871
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
872
+ logger.info('App state sync key arrived, triggering app state sync');
873
+ await doAppStateSync();
874
+ }
875
+ });
876
+ ws.on('CB:presence', handlePresenceUpdate);
877
+ ws.on('CB:chatstate', handlePresenceUpdate);
878
+ ws.on('CB:ib,,dirty', async (node) => {
879
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
880
+ const type = attrs.type;
881
+ switch (type) {
882
+ case 'account_sync':
883
+ if (attrs.timestamp) {
884
+ let { lastAccountSyncTimestamp } = authState.creds;
885
+ if (lastAccountSyncTimestamp) {
886
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
887
+ }
888
+ lastAccountSyncTimestamp = +attrs.timestamp;
889
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
890
+ }
891
+ break;
892
+ case 'groups':
893
+ // handled in groups.ts
894
+ break;
895
+ default:
896
+ logger.info({ node }, 'received unknown sync');
897
+ break;
898
+ }
899
+ });
900
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
901
+ if (connection === 'open') {
902
+ if (fireInitQueries) {
903
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
904
+ }
905
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
906
+ }
907
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
908
+ return;
909
+ }
910
+ syncState = SyncState.AwaitingInitialSync;
911
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
912
+ ev.buffer();
913
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
914
+ syncType: proto.HistorySync.HistorySyncType.RECENT
915
+ }));
916
+ if (!willSyncHistory) {
917
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
918
+ syncState = SyncState.Online;
919
+ setTimeout(() => ev.flush(), 0);
920
+ return;
921
+ }
922
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
923
+ if (awaitingSyncTimeout) {
924
+ clearTimeout(awaitingSyncTimeout);
925
+ }
926
+ awaitingSyncTimeout = setTimeout(() => {
927
+ if (syncState === SyncState.AwaitingInitialSync) {
928
+ // TODO: investigate
929
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
930
+ syncState = SyncState.Online;
931
+ ev.flush();
932
+ }
933
+ }, 20000);
934
+ });
935
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
936
+ try {
937
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
938
+ }
939
+ catch (error) {
940
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
941
+ }
942
+ });
943
+ ev.on('groups.upsert', async (groups) => {
944
+ try {
945
+ const mappings = [];
946
+ for (const group of groups) {
947
+ for (const p of group.participants || []) {
948
+ const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
949
+ const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
950
+ ? p.phoneNumber
951
+ : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
952
+ if (lidJid && pnJid) {
953
+ mappings.push({ lid: lidJid, pn: pnJid });
954
+ }
955
+ }
956
+ }
957
+ if (mappings.length > 0) {
958
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
959
+ logger.debug({ count: mappings.length }, 'groups.upsert: stored LID-PN mappings from participants');
960
+ }
961
+ }
962
+ catch (error) {
963
+ logger.warn({ error }, 'groups.upsert: failed to store LID-PN mappings');
964
+ }
965
+ });
966
+ ev.on('groups.update', async (updates) => {
967
+ try {
968
+ const mappings = [];
969
+ for (const update of updates) {
970
+ for (const p of update.participants || []) {
971
+ const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
972
+ const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
973
+ ? p.phoneNumber
974
+ : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
975
+ if (lidJid && pnJid) {
976
+ mappings.push({ lid: lidJid, pn: pnJid });
977
+ }
978
+ }
979
+ }
980
+ if (mappings.length > 0) {
981
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
982
+ logger.debug({ count: mappings.length }, 'groups.update: stored LID-PN mappings from participants');
983
+ }
984
+ }
985
+ catch (error) {
986
+ logger.warn({ error }, 'groups.update: failed to store LID-PN mappings');
987
+ }
988
+ });
989
+ return {
990
+ ...sock,
991
+ createCallLink,
992
+ getBotListV2,
993
+ messageMutex,
994
+ receiptMutex,
995
+ appStatePatchMutex,
996
+ notificationMutex,
997
+ fetchPrivacySettings,
998
+ upsertMessage,
999
+ appPatch,
1000
+ sendPresenceUpdate,
1001
+ presenceSubscribe,
1002
+ profilePictureUrl,
1003
+ fetchBlocklist,
1004
+ fetchStatus,
1005
+ fetchDisappearingDuration,
1006
+ updateProfilePicture,
1007
+ removeProfilePicture,
1008
+ updateProfileStatus,
1009
+ updateProfileName,
1010
+ updateBlockStatus,
1011
+ updateDisableLinkPreviewsPrivacy,
1012
+ updateCallPrivacy,
1013
+ updateMessagesPrivacy,
1014
+ updateLastSeenPrivacy,
1015
+ updateOnlinePrivacy,
1016
+ updateProfilePicturePrivacy,
1017
+ updateStatusPrivacy,
1018
+ updateReadReceiptsPrivacy,
1019
+ updateGroupsAddPrivacy,
1020
+ updateDefaultDisappearingMode,
1021
+ getBusinessProfile,
1022
+ resyncAppState,
1023
+ chatModify,
1024
+ cleanDirtyBits,
1025
+ addOrEditContact,
1026
+ removeContact,
1027
+ addLabel,
1028
+ addChatLabel,
1029
+ removeChatLabel,
1030
+ addMessageLabel,
1031
+ removeMessageLabel,
1032
+ star,
1033
+ addOrEditQuickReply,
1034
+ removeQuickReply
1035
+ };
1036
+ };
1037
+ //# sourceMappingURL=chats.js.map