@fer2809fl/baileys 1.4.9 → 7.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 (481) hide show
  1. package/LICENSE +21 -674
  2. package/README.md +556 -523
  3. package/WAProto/GenerateStatics.sh +3 -4
  4. package/WAProto/WAProto.proto +1215 -511
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +4347 -45387
  7. package/WAProto/index.js +65475 -137445
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +34 -18
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +95 -67
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +1 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +2 -5
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +4 -3
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +7 -41
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +37 -60
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -11
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -57
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +2 -1
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +7 -44
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +3 -2
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +7 -15
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +2 -1
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +2 -1
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +9 -12
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +1 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +2 -5
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +3 -2
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +12 -37
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +7 -6
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +27 -42
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +1 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +4 -7
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -3
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +347 -90
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +277 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -2
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -18
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +4 -4
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +4 -6
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +3 -3
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +21 -78
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +205 -93
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +162 -43
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +77 -28
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +639 -248
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +340 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +434 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +93 -46
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +260 -102
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +253 -98
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +11 -9
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +192 -83
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1314 -559
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +190 -75
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +937 -581
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +4 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +62 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +129 -73
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +373 -222
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/smgss.d.ts +119 -0
  118. package/lib/Socket/smgss.d.ts.map +1 -0
  119. package/lib/Socket/smgss.js +453 -0
  120. package/lib/Socket/smgss.js.map +1 -0
  121. package/lib/Socket/socket.d.ts +59 -270
  122. package/lib/Socket/socket.d.ts.map +1 -0
  123. package/lib/Socket/socket.js +738 -326
  124. package/lib/Socket/socket.js.map +1 -0
  125. package/lib/Store/index.d.ts +4 -2
  126. package/lib/Store/index.d.ts.map +1 -0
  127. package/lib/Store/index.js +4 -8
  128. package/lib/Store/index.js.map +1 -0
  129. package/lib/Store/make-in-memory-store.d.ts +74 -60
  130. package/lib/Store/make-in-memory-store.d.ts.map +1 -0
  131. package/lib/Store/make-in-memory-store.js +130 -119
  132. package/lib/Store/make-in-memory-store.js.map +1 -0
  133. package/lib/Store/make-ordered-dictionary.d.ts +4 -3
  134. package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
  135. package/lib/Store/make-ordered-dictionary.js +5 -6
  136. package/lib/Store/make-ordered-dictionary.js.map +1 -0
  137. package/lib/Store/object-repository.d.ts +6 -3
  138. package/lib/Store/object-repository.d.ts.map +1 -0
  139. package/lib/Store/object-repository.js +2 -5
  140. package/lib/Store/object-repository.js.map +1 -0
  141. package/lib/Types/Auth.d.ts +19 -5
  142. package/lib/Types/Auth.d.ts.map +1 -0
  143. package/lib/Types/Auth.js +2 -2
  144. package/lib/Types/Auth.js.map +1 -0
  145. package/lib/Types/Bussines.d.ts +25 -0
  146. package/lib/Types/Bussines.d.ts.map +1 -0
  147. package/lib/Types/Bussines.js +2 -0
  148. package/lib/Types/Bussines.js.map +1 -0
  149. package/lib/Types/Call.d.ts +3 -1
  150. package/lib/Types/Call.d.ts.map +1 -0
  151. package/lib/Types/Call.js +2 -2
  152. package/lib/Types/Call.js.map +1 -0
  153. package/lib/Types/Chat.d.ts +24 -9
  154. package/lib/Types/Chat.d.ts.map +1 -0
  155. package/lib/Types/Chat.js +8 -4
  156. package/lib/Types/Chat.js.map +1 -0
  157. package/lib/Types/Contact.d.ts +7 -4
  158. package/lib/Types/Contact.d.ts.map +1 -0
  159. package/lib/Types/Contact.js +2 -2
  160. package/lib/Types/Contact.js.map +1 -0
  161. package/lib/Types/Events.d.ts +90 -33
  162. package/lib/Types/Events.d.ts.map +1 -0
  163. package/lib/Types/Events.js +2 -2
  164. package/lib/Types/Events.js.map +1 -0
  165. package/lib/Types/GroupMetadata.d.ts +16 -9
  166. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  167. package/lib/Types/GroupMetadata.js +2 -2
  168. package/lib/Types/GroupMetadata.js.map +1 -0
  169. package/lib/Types/Label.d.ts +12 -0
  170. package/lib/Types/Label.d.ts.map +1 -0
  171. package/lib/Types/Label.js +3 -5
  172. package/lib/Types/Label.js.map +1 -0
  173. package/lib/Types/LabelAssociation.d.ts +1 -0
  174. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  175. package/lib/Types/LabelAssociation.js +3 -5
  176. package/lib/Types/LabelAssociation.js.map +1 -0
  177. package/lib/Types/Message.d.ts +176 -148
  178. package/lib/Types/Message.d.ts.map +1 -0
  179. package/lib/Types/Message.js +15 -7
  180. package/lib/Types/Message.js.map +1 -0
  181. package/lib/Types/Mex.d.ts +154 -0
  182. package/lib/Types/Mex.d.ts.map +1 -0
  183. package/lib/Types/Mex.js +39 -0
  184. package/lib/Types/Mex.js.map +1 -0
  185. package/lib/Types/Product.d.ts +2 -1
  186. package/lib/Types/Product.d.ts.map +1 -0
  187. package/lib/Types/Product.js +2 -2
  188. package/lib/Types/Product.js.map +1 -0
  189. package/lib/Types/Signal.d.ts +32 -2
  190. package/lib/Types/Signal.d.ts.map +1 -0
  191. package/lib/Types/Signal.js +2 -2
  192. package/lib/Types/Signal.js.map +1 -0
  193. package/lib/Types/Socket.d.ts +46 -20
  194. package/lib/Types/Socket.d.ts.map +1 -0
  195. package/lib/Types/Socket.js +3 -2
  196. package/lib/Types/Socket.js.map +1 -0
  197. package/lib/Types/State.d.ts +79 -2
  198. package/lib/Types/State.d.ts.map +1 -0
  199. package/lib/Types/State.js +56 -2
  200. package/lib/Types/State.js.map +1 -0
  201. package/lib/Types/USync.d.ts +3 -2
  202. package/lib/Types/USync.d.ts.map +1 -0
  203. package/lib/Types/USync.js +2 -2
  204. package/lib/Types/USync.js.map +1 -0
  205. package/lib/Types/index.d.ts +16 -14
  206. package/lib/Types/index.d.ts.map +1 -0
  207. package/lib/Types/index.js +15 -31
  208. package/lib/Types/index.js.map +1 -0
  209. package/lib/Utils/auth-utils.d.ts +10 -4
  210. package/lib/Utils/auth-utils.d.ts.map +1 -0
  211. package/lib/Utils/auth-utils.js +242 -151
  212. package/lib/Utils/auth-utils.js.map +1 -0
  213. package/lib/Utils/browser-utils.d.ts +4 -0
  214. package/lib/Utils/browser-utils.d.ts.map +1 -0
  215. package/lib/Utils/browser-utils.js +29 -0
  216. package/lib/Utils/browser-utils.js.map +1 -0
  217. package/lib/Utils/business.d.ts +3 -2
  218. package/lib/Utils/business.d.ts.map +1 -0
  219. package/lib/Utils/business.js +66 -69
  220. package/lib/Utils/business.js.map +1 -0
  221. package/lib/Utils/button-handler.d.ts +28 -0
  222. package/lib/Utils/button-handler.d.ts.map +1 -0
  223. package/lib/Utils/button-handler.js +79 -90
  224. package/lib/Utils/button-handler.js.map +1 -0
  225. package/lib/Utils/chat-utils.d.ts +42 -12
  226. package/lib/Utils/chat-utils.d.ts.map +1 -0
  227. package/lib/Utils/chat-utils.js +380 -238
  228. package/lib/Utils/chat-utils.js.map +1 -0
  229. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  230. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  231. package/lib/Utils/companion-reg-client-utils.js +35 -0
  232. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  233. package/lib/Utils/crypto.d.ts +11 -14
  234. package/lib/Utils/crypto.d.ts.map +1 -0
  235. package/lib/Utils/crypto.js +41 -116
  236. package/lib/Utils/crypto.js.map +1 -0
  237. package/lib/Utils/decode-wa-message.d.ts +36 -5
  238. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  239. package/lib/Utils/decode-wa-message.js +173 -63
  240. package/lib/Utils/decode-wa-message.js.map +1 -0
  241. package/lib/Utils/event-buffer.d.ts +8 -7
  242. package/lib/Utils/event-buffer.d.ts.map +1 -0
  243. package/lib/Utils/event-buffer.js +174 -70
  244. package/lib/Utils/event-buffer.js.map +1 -0
  245. package/lib/Utils/generics.d.ts +20 -17
  246. package/lib/Utils/generics.d.ts.map +1 -0
  247. package/lib/Utils/generics.js +159 -207
  248. package/lib/Utils/generics.js.map +1 -0
  249. package/lib/Utils/history.d.ts +16 -11
  250. package/lib/Utils/history.d.ts.map +1 -0
  251. package/lib/Utils/history.js +93 -53
  252. package/lib/Utils/history.js.map +1 -0
  253. package/lib/Utils/identity-change-handler.d.ts +44 -0
  254. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  255. package/lib/Utils/identity-change-handler.js +50 -0
  256. package/lib/Utils/identity-change-handler.js.map +1 -0
  257. package/lib/Utils/index.d.ts +30 -18
  258. package/lib/Utils/index.d.ts.map +1 -0
  259. package/lib/Utils/index.js +30 -34
  260. package/lib/Utils/index.js.map +1 -0
  261. package/lib/Utils/interactive.d.ts +60 -0
  262. package/lib/Utils/interactive.d.ts.map +1 -0
  263. package/lib/Utils/interactive.js +87 -117
  264. package/lib/Utils/interactive.js.map +1 -0
  265. package/lib/Utils/link-preview.d.ts +4 -4
  266. package/lib/Utils/link-preview.d.ts.map +1 -0
  267. package/lib/Utils/link-preview.js +17 -58
  268. package/lib/Utils/link-preview.js.map +1 -0
  269. package/lib/Utils/logger.d.ts +8 -6
  270. package/lib/Utils/logger.d.ts.map +1 -0
  271. package/lib/Utils/logger.js +3 -10
  272. package/lib/Utils/logger.js.map +1 -0
  273. package/lib/Utils/lt-hash.d.ts +8 -12
  274. package/lib/Utils/lt-hash.d.ts.map +1 -0
  275. package/lib/Utils/lt-hash.js +3 -46
  276. package/lib/Utils/lt-hash.js.map +1 -0
  277. package/lib/Utils/make-mutex.d.ts +2 -0
  278. package/lib/Utils/make-mutex.d.ts.map +1 -0
  279. package/lib/Utils/make-mutex.js +24 -34
  280. package/lib/Utils/make-mutex.js.map +1 -0
  281. package/lib/Utils/message-composer.d.ts +93 -0
  282. package/lib/Utils/message-composer.d.ts.map +1 -0
  283. package/lib/Utils/message-composer.js +311 -0
  284. package/lib/Utils/message-composer.js.map +1 -0
  285. package/lib/Utils/message-retry-manager.d.ts +115 -0
  286. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  287. package/lib/Utils/message-retry-manager.js +265 -0
  288. package/lib/Utils/message-retry-manager.js.map +1 -0
  289. package/lib/Utils/messages-media.d.ts +82 -40
  290. package/lib/Utils/messages-media.d.ts.map +1 -0
  291. package/lib/Utils/messages-media.js +674 -677
  292. package/lib/Utils/messages-media.js.map +1 -0
  293. package/lib/Utils/messages-newsletter.d.ts +74 -0
  294. package/lib/Utils/messages-newsletter.d.ts.map +1 -0
  295. package/lib/Utils/messages-newsletter.js +128 -0
  296. package/lib/Utils/messages-newsletter.js.map +1 -0
  297. package/lib/Utils/messages.d.ts +38 -14
  298. package/lib/Utils/messages.d.ts.map +1 -0
  299. package/lib/Utils/messages.js +835 -602
  300. package/lib/Utils/messages.js.map +1 -0
  301. package/lib/Utils/noise-handler.d.ts +9 -8
  302. package/lib/Utils/noise-handler.d.ts.map +1 -0
  303. package/lib/Utils/noise-handler.js +149 -98
  304. package/lib/Utils/noise-handler.js.map +1 -0
  305. package/lib/Utils/offline-node-processor.d.ts +17 -0
  306. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  307. package/lib/Utils/offline-node-processor.js +40 -0
  308. package/lib/Utils/offline-node-processor.js.map +1 -0
  309. package/lib/Utils/pre-key-manager.d.ts +28 -0
  310. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  311. package/lib/Utils/pre-key-manager.js +106 -0
  312. package/lib/Utils/pre-key-manager.js.map +1 -0
  313. package/lib/Utils/process-message.d.ts +30 -12
  314. package/lib/Utils/process-message.d.ts.map +1 -0
  315. package/lib/Utils/process-message.js +438 -230
  316. package/lib/Utils/process-message.js.map +1 -0
  317. package/lib/Utils/reporting-utils.d.ts +11 -0
  318. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  319. package/lib/Utils/reporting-utils.js +258 -0
  320. package/lib/Utils/reporting-utils.js.map +1 -0
  321. package/lib/Utils/shortcake-crypto.d.ts +36 -0
  322. package/lib/Utils/shortcake-crypto.d.ts.map +1 -0
  323. package/lib/Utils/shortcake-crypto.js +71 -0
  324. package/lib/Utils/shortcake-crypto.js.map +1 -0
  325. package/lib/Utils/shortcake.d.ts +36 -0
  326. package/lib/Utils/shortcake.d.ts.map +1 -0
  327. package/lib/Utils/shortcake.js +162 -0
  328. package/lib/Utils/shortcake.js.map +1 -0
  329. package/lib/Utils/signal.d.ts +20 -6
  330. package/lib/Utils/signal.d.ts.map +1 -0
  331. package/lib/Utils/signal.js +112 -64
  332. package/lib/Utils/signal.js.map +1 -0
  333. package/lib/Utils/stanza-ack.d.ts +11 -0
  334. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  335. package/lib/Utils/stanza-ack.js +38 -0
  336. package/lib/Utils/stanza-ack.js.map +1 -0
  337. package/lib/Utils/sync-action-utils.d.ts +19 -0
  338. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  339. package/lib/Utils/sync-action-utils.js +49 -0
  340. package/lib/Utils/sync-action-utils.js.map +1 -0
  341. package/lib/Utils/tc-token-utils.d.ts +37 -0
  342. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  343. package/lib/Utils/tc-token-utils.js +164 -0
  344. package/lib/Utils/tc-token-utils.js.map +1 -0
  345. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  346. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  347. package/lib/Utils/use-multi-file-auth-state.js +40 -64
  348. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  349. package/lib/Utils/use-single-file-auth-state.d.ts +6 -0
  350. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  351. package/lib/Utils/use-single-file-auth-state.js +111 -0
  352. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  353. package/lib/Utils/use-sqlite-auth-state.d.ts +14 -0
  354. package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
  355. package/lib/Utils/use-sqlite-auth-state.js +107 -0
  356. package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
  357. package/lib/Utils/validate-connection.d.ts +5 -3
  358. package/lib/Utils/validate-connection.d.ts.map +1 -0
  359. package/lib/Utils/validate-connection.js +82 -101
  360. package/lib/Utils/validate-connection.js.map +1 -0
  361. package/lib/WABinary/constants.d.ts +1 -0
  362. package/lib/WABinary/constants.d.ts.map +1 -0
  363. package/lib/WABinary/constants.js +10 -12
  364. package/lib/WABinary/constants.js.map +1 -0
  365. package/lib/WABinary/decode.d.ts +2 -1
  366. package/lib/WABinary/decode.d.ts.map +1 -0
  367. package/lib/WABinary/decode.js +49 -52
  368. package/lib/WABinary/decode.js.map +1 -0
  369. package/lib/WABinary/encode.d.ts +2 -1
  370. package/lib/WABinary/encode.d.ts.map +1 -0
  371. package/lib/WABinary/encode.js +19 -49
  372. package/lib/WABinary/encode.js.map +1 -0
  373. package/lib/WABinary/generic-utils.d.ts +5 -4
  374. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  375. package/lib/WABinary/generic-utils.js +46 -43
  376. package/lib/WABinary/generic-utils.js.map +1 -0
  377. package/lib/WABinary/index.d.ts +6 -5
  378. package/lib/WABinary/index.d.ts.map +1 -0
  379. package/lib/WABinary/index.js +6 -21
  380. package/lib/WABinary/index.js.map +1 -0
  381. package/lib/WABinary/jid-utils.d.ts +32 -10
  382. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  383. package/lib/WABinary/jid-utils.js +103 -59
  384. package/lib/WABinary/jid-utils.js.map +1 -0
  385. package/lib/WABinary/types.d.ts +2 -1
  386. package/lib/WABinary/types.d.ts.map +1 -0
  387. package/lib/WABinary/types.js +2 -2
  388. package/lib/WABinary/types.js.map +1 -0
  389. package/lib/WAM/BinaryInfo.d.ts +2 -1
  390. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  391. package/lib/WAM/BinaryInfo.js +2 -5
  392. package/lib/WAM/BinaryInfo.js.map +1 -0
  393. package/lib/WAM/constants.d.ts +5 -3
  394. package/lib/WAM/constants.d.ts.map +1 -0
  395. package/lib/WAM/constants.js +19071 -11568
  396. package/lib/WAM/constants.js.map +1 -0
  397. package/lib/WAM/encode.d.ts +2 -1
  398. package/lib/WAM/encode.d.ts.map +1 -0
  399. package/lib/WAM/encode.js +17 -22
  400. package/lib/WAM/encode.js.map +1 -0
  401. package/lib/WAM/index.d.ts +4 -3
  402. package/lib/WAM/index.d.ts.map +1 -0
  403. package/lib/WAM/index.js +4 -19
  404. package/lib/WAM/index.js.map +1 -0
  405. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  406. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  407. package/lib/WAUSync/Protocols/USyncContactProtocol.js +33 -13
  408. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  409. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  410. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  411. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  412. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  413. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  414. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  415. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +8 -11
  416. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  417. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  418. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  419. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  420. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  421. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  422. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  423. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  424. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  425. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  426. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  427. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  428. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  429. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +5 -3
  430. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  431. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  432. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  433. package/lib/WAUSync/Protocols/index.d.ts +6 -4
  434. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  435. package/lib/WAUSync/Protocols/index.js +6 -20
  436. package/lib/WAUSync/Protocols/index.js.map +1 -0
  437. package/lib/WAUSync/USyncQuery.d.ts +6 -4
  438. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  439. package/lib/WAUSync/USyncQuery.js +44 -35
  440. package/lib/WAUSync/USyncQuery.js.map +1 -0
  441. package/lib/WAUSync/USyncUser.d.ts +10 -5
  442. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  443. package/lib/WAUSync/USyncUser.js +10 -5
  444. package/lib/WAUSync/USyncUser.js.map +1 -0
  445. package/lib/WAUSync/index.d.ts +4 -3
  446. package/lib/WAUSync/index.d.ts.map +1 -0
  447. package/lib/WAUSync/index.js +4 -19
  448. package/lib/WAUSync/index.js.map +1 -0
  449. package/lib/index.d.ts +12 -15
  450. package/lib/index.d.ts.map +1 -0
  451. package/lib/index.js +15 -48
  452. package/lib/index.js.map +1 -0
  453. package/package.json +44 -64
  454. package/WAProto/index.ts.ts +0 -53473
  455. package/WAProto/n +0 -1
  456. package/lib/Baileys.jpeg +0 -0
  457. package/lib/Defaults/baileys-version.json +0 -3
  458. package/lib/Defaults/n +0 -1
  459. package/lib/Signal/Group/queue-job.d.ts +0 -1
  460. package/lib/Signal/Group/queue-job.js +0 -57
  461. package/lib/Signal/n +0 -1
  462. package/lib/Socket/Client/n +0 -1
  463. package/lib/Socket/n +0 -1
  464. package/lib/Socket/setup.js +0 -480
  465. package/lib/Socket/setup.ts +0 -622
  466. package/lib/Socket/usync.d.ts +0 -36
  467. package/lib/Socket/usync.js +0 -70
  468. package/lib/Store/n +0 -1
  469. package/lib/Types/Newsletter.d.ts +0 -79
  470. package/lib/Types/Newsletter.js +0 -18
  471. package/lib/Types/n +0 -1
  472. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  473. package/lib/Utils/baileys-event-stream.js +0 -63
  474. package/lib/Utils/error-handler.js +0 -37
  475. package/lib/Utils/n +0 -1
  476. package/lib/WABinary/jid-utils.js.bak +0 -83
  477. package/lib/WABinary/n +0 -1
  478. package/lib/WAM/n +0 -1
  479. package/lib/WAUSync/Protocols/n +0 -1
  480. package/lib/WAUSync/n +0 -1
  481. package/lib/n +0 -1
@@ -1,37 +1,64 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
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, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
+ import { ALL_WA_PATCH_NAMES, WAMessageStubType } from '../Types/index.js';
6
+ import { SyncState } from '../Types/State.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, 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, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, 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
+ export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
15
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } };
16
+ if (tcTokenContent?.length) {
17
+ picture.content = tcTokenContent;
18
+ }
19
+ return [picture];
4
20
  };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeChatsSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const WAProto_1 = require("../../WAProto");
10
- const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
12
- const Utils_1 = require("../Utils");
13
- const make_mutex_1 = require("../Utils/make-mutex");
14
- const process_message_1 = __importDefault(require("../Utils/process-message"));
15
- const WABinary_1 = require("../WABinary");
16
- const WAUSync_1 = require("../WAUSync");
17
- const usync_1 = require("./usync");
18
- const MAX_SYNC_ATTEMPTS = 2;
19
- const makeChatsSocket = (config) => {
20
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
- const sock = (0, usync_1.makeUSyncSocket)(config);
22
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
21
+ const USER_ID_CACHE = new Map();
22
+ export const makeChatsSocket = (config) => {
23
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
24
+ const sock = makeSocket(config);
25
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
26
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
23
27
  let privacySettings;
24
- let needToFlushWithAppStateSync = false;
25
- let pendingAppStateSync = false;
26
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
27
- const processingMutex = (0, make_mutex_1.makeMutex)();
28
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
29
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
30
- useClones: false
31
- });
32
- if (!config.placeholderResendCache) {
33
- config.placeholderResendCache = placeholderResendCache;
34
- }
28
+ /** Server-assigned AB props for protocol behavior. */
29
+ const serverProps = {
30
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
31
+ privacyTokenOn1to1: true,
32
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
33
+ profilePicPrivacyToken: true,
34
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
35
+ lidTrustedTokenIssueToLid: false
36
+ };
37
+ let syncState = SyncState.Connecting;
38
+ /** this mutex ensures that messages are processed in order */
39
+ const messageMutex = makeMutex();
40
+ /** this mutex ensures that receipts are processed in order */
41
+ const receiptMutex = makeMutex();
42
+ /** this mutex ensures that app state patches are processed in order */
43
+ const appStatePatchMutex = makeMutex();
44
+ /** this mutex ensures that notifications are processed in order */
45
+ const notificationMutex = makeMutex();
46
+ // Timeout for AwaitingInitialSync state
47
+ let awaitingSyncTimeout;
48
+ // In-memory history sync completion tracking (resets on reconnection)
49
+ const historySyncStatus = {
50
+ initialBootstrapComplete: false,
51
+ recentSyncComplete: false
52
+ };
53
+ let historySyncPausedTimeout;
54
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
55
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
56
+ const blockedCollections = new Set();
57
+ const placeholderResendCache = config.placeholderResendCache ||
58
+ new NodeCache({
59
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
60
+ useClones: false
61
+ });
35
62
  /** helper function to fetch the given app state sync key */
36
63
  const getAppStateSyncKey = async (keyId) => {
37
64
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -43,14 +70,12 @@ const makeChatsSocket = (config) => {
43
70
  tag: 'iq',
44
71
  attrs: {
45
72
  xmlns: 'privacy',
46
- to: WABinary_1.S_WHATSAPP_NET,
73
+ to: S_WHATSAPP_NET,
47
74
  type: 'get'
48
75
  },
49
- content: [
50
- { tag: 'privacy', attrs: {} }
51
- ]
76
+ content: [{ tag: 'privacy', attrs: {} }]
52
77
  });
53
- privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
78
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
54
79
  }
55
80
  return privacySettings;
56
81
  };
@@ -60,10 +85,11 @@ const makeChatsSocket = (config) => {
60
85
  tag: 'iq',
61
86
  attrs: {
62
87
  xmlns: 'privacy',
63
- to: WABinary_1.S_WHATSAPP_NET,
88
+ to: S_WHATSAPP_NET,
64
89
  type: 'set'
65
90
  },
66
- content: [{
91
+ content: [
92
+ {
67
93
  tag: 'privacy',
68
94
  attrs: {},
69
95
  content: [
@@ -72,7 +98,8 @@ const makeChatsSocket = (config) => {
72
98
  attrs: { name, value }
73
99
  }
74
100
  ]
75
- }]
101
+ }
102
+ ]
76
103
  });
77
104
  };
78
105
  const updateMessagesPrivacy = async (value) => {
@@ -104,15 +131,17 @@ const makeChatsSocket = (config) => {
104
131
  tag: 'iq',
105
132
  attrs: {
106
133
  xmlns: 'disappearing_mode',
107
- to: WABinary_1.S_WHATSAPP_NET,
134
+ to: S_WHATSAPP_NET,
108
135
  type: 'set'
109
136
  },
110
- content: [{
137
+ content: [
138
+ {
111
139
  tag: 'disappearing_mode',
112
140
  attrs: {
113
141
  duration: duration.toString()
114
142
  }
115
- }]
143
+ }
144
+ ]
116
145
  });
117
146
  };
118
147
  const getBotListV2 = async () => {
@@ -120,21 +149,23 @@ const makeChatsSocket = (config) => {
120
149
  tag: 'iq',
121
150
  attrs: {
122
151
  xmlns: 'bot',
123
- to: WABinary_1.S_WHATSAPP_NET,
152
+ to: S_WHATSAPP_NET,
124
153
  type: 'get'
125
154
  },
126
- content: [{
155
+ content: [
156
+ {
127
157
  tag: 'bot',
128
158
  attrs: {
129
159
  v: '2'
130
160
  }
131
- }]
161
+ }
162
+ ]
132
163
  });
133
- const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
164
+ const botNode = getBinaryNodeChild(resp, 'bot');
134
165
  const botList = [];
135
- for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
166
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
136
167
  if (section.attrs.type === 'all') {
137
- for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
168
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
138
169
  botList.push({
139
170
  jid: bot.attrs.jid,
140
171
  personaId: bot.attrs['persona_id']
@@ -144,24 +175,10 @@ const makeChatsSocket = (config) => {
144
175
  }
145
176
  return botList;
146
177
  };
147
- const onWhatsApp = async (...jids) => {
148
- const usyncQuery = new WAUSync_1.USyncQuery()
149
- .withContactProtocol()
150
- .withLIDProtocol();
151
- for (const jid of jids) {
152
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
153
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
154
- }
155
- const results = await sock.executeUSyncQuery(usyncQuery);
156
- if (results) {
157
- return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
158
- }
159
- };
160
178
  const fetchStatus = async (...jids) => {
161
- const usyncQuery = new WAUSync_1.USyncQuery()
162
- .withStatusProtocol();
179
+ const usyncQuery = new USyncQuery().withStatusProtocol();
163
180
  for (const jid of jids) {
164
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
181
+ usyncQuery.withUser(new USyncUser().withId(jid));
165
182
  }
166
183
  const result = await sock.executeUSyncQuery(usyncQuery);
167
184
  if (result) {
@@ -169,33 +186,68 @@ const makeChatsSocket = (config) => {
169
186
  }
170
187
  };
171
188
  const fetchDisappearingDuration = async (...jids) => {
172
- const usyncQuery = new WAUSync_1.USyncQuery()
173
- .withDisappearingModeProtocol();
189
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
174
190
  for (const jid of jids) {
175
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
191
+ usyncQuery.withUser(new USyncUser().withId(jid));
176
192
  }
177
193
  const result = await sock.executeUSyncQuery(usyncQuery);
178
194
  if (result) {
179
195
  return result.list;
180
196
  }
181
197
  };
198
+ const findUserId = async (pnOrLid) => {
199
+ const cached = USER_ID_CACHE.get(pnOrLid);
200
+ if (cached) {
201
+ return cached;
202
+ }
203
+ const userId = { phoneNumber: '', lid: '' };
204
+ if (isPnUser(pnOrLid) || isHostedPnUser(pnOrLid)) {
205
+ userId.phoneNumber = pnOrLid;
206
+ const lid = await signalRepository.lidMapping.getLIDForPN(pnOrLid);
207
+ if (!lid) {
208
+ userId.lid = 'id-not-found';
209
+ return userId;
210
+ }
211
+ userId.lid = lid;
212
+ }
213
+ else if (isLidUser(pnOrLid) || isHostedLidUser(pnOrLid)) {
214
+ userId.lid = pnOrLid;
215
+ const pn = await signalRepository.lidMapping.getPNForLID(pnOrLid);
216
+ if (!pn) {
217
+ userId.phoneNumber = 'id-not-found';
218
+ return userId;
219
+ }
220
+ userId.phoneNumber = pn;
221
+ }
222
+ else {
223
+ throw new Boom('Invalid id input to find user ids', { statusCode: 400 });
224
+ }
225
+ userId.phoneNumber = jidNormalizedUser(userId.phoneNumber);
226
+ userId.lid = jidNormalizedUser(userId.lid);
227
+ USER_ID_CACHE.set(userId.phoneNumber, userId);
228
+ USER_ID_CACHE.set(userId.lid, userId);
229
+ return userId;
230
+ };
182
231
  /** update the profile picture for yourself or a group */
183
- const updateProfilePicture = async (jid, content) => {
232
+ const updateProfilePicture = async (jid, content, dimensions, options) => {
184
233
  let targetJid;
185
234
  if (!jid) {
186
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
235
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
187
236
  }
188
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
189
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
237
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
238
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
239
+ }
240
+ else {
241
+ targetJid = undefined;
190
242
  }
191
- const { img } = await (0, Utils_1.generateProfilePicture)(content);
243
+ const { img } = await generateProfilePicture(content, dimensions, options);
192
244
  await query({
193
245
  tag: 'iq',
194
246
  attrs: {
195
- target: targetJid,
196
- to: WABinary_1.S_WHATSAPP_NET,
247
+ to: S_WHATSAPP_NET,
197
248
  type: 'set',
198
- xmlns: 'w:profile:picture'
249
+ xmlns: 'w:profile:picture',
250
+ ...(targetJid ? { target: targetJid } : {})
199
251
  },
200
252
  content: [
201
253
  {
@@ -210,18 +262,21 @@ const makeChatsSocket = (config) => {
210
262
  const removeProfilePicture = async (jid) => {
211
263
  let targetJid;
212
264
  if (!jid) {
213
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
265
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
266
+ }
267
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
268
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
214
269
  }
215
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
216
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
270
+ else {
271
+ targetJid = undefined;
217
272
  }
218
273
  await query({
219
274
  tag: 'iq',
220
275
  attrs: {
221
- target: targetJid,
222
- to: WABinary_1.S_WHATSAPP_NET,
276
+ to: S_WHATSAPP_NET,
223
277
  type: 'set',
224
- xmlns: 'w:profile:picture'
278
+ xmlns: 'w:profile:picture',
279
+ ...(targetJid ? { target: targetJid } : {})
225
280
  }
226
281
  });
227
282
  };
@@ -230,7 +285,7 @@ const makeChatsSocket = (config) => {
230
285
  await query({
231
286
  tag: 'iq',
232
287
  attrs: {
233
- to: WABinary_1.S_WHATSAPP_NET,
288
+ to: S_WHATSAPP_NET,
234
289
  type: 'set',
235
290
  xmlns: 'status'
236
291
  },
@@ -251,35 +306,66 @@ const makeChatsSocket = (config) => {
251
306
  tag: 'iq',
252
307
  attrs: {
253
308
  xmlns: 'blocklist',
254
- to: WABinary_1.S_WHATSAPP_NET,
309
+ to: S_WHATSAPP_NET,
255
310
  type: 'get'
256
311
  }
257
312
  });
258
- const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
259
- return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
260
- .map(n => n.attrs.jid);
313
+ const listNode = getBinaryNodeChild(result, 'list');
314
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
261
315
  };
262
316
  const updateBlockStatus = async (jid, action) => {
317
+ const normalizedJid = jidNormalizedUser(jid);
318
+ let lid;
319
+ let pn_jid;
320
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
321
+ lid = normalizedJid;
322
+ if (action === 'block') {
323
+ const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
324
+ if (!pn) {
325
+ throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
326
+ }
327
+ pn_jid = jidNormalizedUser(pn);
328
+ }
329
+ }
330
+ else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
331
+ const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
332
+ if (!mapped) {
333
+ throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
334
+ }
335
+ lid = mapped;
336
+ if (action === 'block') {
337
+ pn_jid = jidNormalizedUser(normalizedJid);
338
+ }
339
+ }
340
+ else {
341
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
342
+ }
343
+ const itemAttrs = {
344
+ action,
345
+ jid: lid
346
+ };
347
+ if (action === 'block') {
348
+ if (!pn_jid) {
349
+ throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
350
+ }
351
+ itemAttrs.pn_jid = pn_jid;
352
+ }
263
353
  await query({
264
354
  tag: 'iq',
265
355
  attrs: {
266
356
  xmlns: 'blocklist',
267
- to: WABinary_1.S_WHATSAPP_NET,
357
+ to: S_WHATSAPP_NET,
268
358
  type: 'set'
269
359
  },
270
360
  content: [
271
361
  {
272
362
  tag: 'item',
273
- attrs: {
274
- action,
275
- jid
276
- }
363
+ attrs: itemAttrs
277
364
  }
278
365
  ]
279
366
  });
280
367
  };
281
368
  const getBusinessProfile = async (jid) => {
282
- var _a, _b, _c, _d, _e, _f, _g;
283
369
  const results = await query({
284
370
  tag: 'iq',
285
371
  attrs: {
@@ -287,38 +373,42 @@ const makeChatsSocket = (config) => {
287
373
  xmlns: 'w:biz',
288
374
  type: 'get'
289
375
  },
290
- content: [{
376
+ content: [
377
+ {
291
378
  tag: 'business_profile',
292
379
  attrs: { v: '244' },
293
- content: [{
380
+ content: [
381
+ {
294
382
  tag: 'profile',
295
383
  attrs: { jid }
296
- }]
297
- }]
384
+ }
385
+ ]
386
+ }
387
+ ]
298
388
  });
299
- const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
300
- const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
389
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
390
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
301
391
  if (profiles) {
302
- const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
303
- const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
304
- const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
305
- const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
306
- const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
307
- const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
392
+ const address = getBinaryNodeChild(profiles, 'address');
393
+ const description = getBinaryNodeChild(profiles, 'description');
394
+ const website = getBinaryNodeChild(profiles, 'website');
395
+ const email = getBinaryNodeChild(profiles, 'email');
396
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
397
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
308
398
  const businessHoursConfig = businessHours
309
- ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
399
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
310
400
  : undefined;
311
- const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
401
+ const websiteStr = website?.content?.toString();
312
402
  return {
313
- wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
314
- address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
315
- description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
403
+ wid: profiles.attrs?.jid,
404
+ address: address?.content?.toString(),
405
+ description: description?.content?.toString() || '',
316
406
  website: websiteStr ? [websiteStr] : [],
317
- email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
318
- category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
319
- 'business_hours': {
320
- timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
321
- 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
407
+ email: email?.content?.toString(),
408
+ category: category?.content?.toString(),
409
+ business_hours: {
410
+ timezone: businessHours?.attrs?.timezone,
411
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
322
412
  }
323
413
  };
324
414
  }
@@ -328,17 +418,17 @@ const makeChatsSocket = (config) => {
328
418
  await sendNode({
329
419
  tag: 'iq',
330
420
  attrs: {
331
- to: WABinary_1.S_WHATSAPP_NET,
421
+ to: S_WHATSAPP_NET,
332
422
  type: 'set',
333
423
  xmlns: 'urn:xmpp:whatsapp:dirty',
334
- id: generateMessageTag(),
424
+ id: generateMessageTag()
335
425
  },
336
426
  content: [
337
427
  {
338
428
  tag: 'clean',
339
429
  attrs: {
340
430
  type,
341
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
431
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
342
432
  }
343
433
  }
344
434
  ]
@@ -347,20 +437,31 @@ const makeChatsSocket = (config) => {
347
437
  const newAppStateChunkHandler = (isInitialSync) => {
348
438
  return {
349
439
  onMutation(mutation) {
350
- (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
440
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
351
441
  }
352
442
  };
353
443
  };
354
444
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
445
+ const appStateSyncKeyCache = new Map();
446
+ const getCachedAppStateSyncKey = async (keyId) => {
447
+ if (appStateSyncKeyCache.has(keyId)) {
448
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
449
+ }
450
+ const key = await getAppStateSyncKey(keyId);
451
+ appStateSyncKeyCache.set(keyId, key ?? null);
452
+ return key;
453
+ };
355
454
  // we use this to determine which events to fire
356
455
  // otherwise when we resync from scratch -- all notifications will fire
357
456
  const initialVersionMap = {};
358
457
  const globalMutationMap = {};
359
458
  await authState.keys.transaction(async () => {
360
- var _a;
361
459
  const collectionsToHandle = new Set(collections);
362
460
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
363
461
  const attemptsMap = {};
462
+ // collections that failed and need a full snapshot on retry
463
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
464
+ const forceSnapshotCollections = new Set();
364
465
  // keep executing till all collections are done
365
466
  // sometimes a single patch request will not return all the patches (God knows why)
366
467
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -371,29 +472,34 @@ const makeChatsSocket = (config) => {
371
472
  const result = await authState.keys.get('app-state-sync-version', [name]);
372
473
  let state = result[name];
373
474
  if (state) {
475
+ state = ensureLTHashStateVersion(state);
374
476
  if (typeof initialVersionMap[name] === 'undefined') {
375
477
  initialVersionMap[name] = state.version;
376
478
  }
377
479
  }
378
480
  else {
379
- state = (0, Utils_1.newLTHashState)();
481
+ state = newLTHashState();
380
482
  }
381
483
  states[name] = state;
382
- logger.info(`resyncing ${name} from v${state.version}`);
484
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
485
+ if (shouldForceSnapshot) {
486
+ forceSnapshotCollections.delete(name);
487
+ }
488
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
383
489
  nodes.push({
384
490
  tag: 'collection',
385
491
  attrs: {
386
492
  name,
387
493
  version: state.version.toString(),
388
- // return snapshot if being synced from scratch
389
- 'return_snapshot': (!state.version).toString()
494
+ // return snapshot if syncing from scratch or forcing after a failed attempt
495
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
390
496
  }
391
497
  });
392
498
  }
393
499
  const result = await query({
394
500
  tag: 'iq',
395
501
  attrs: {
396
- to: WABinary_1.S_WHATSAPP_NET,
502
+ to: S_WHATSAPP_NET,
397
503
  xmlns: 'w:sync:app:state',
398
504
  type: 'set'
399
505
  },
@@ -406,13 +512,13 @@ const makeChatsSocket = (config) => {
406
512
  ]
407
513
  });
408
514
  // extract from binary node
409
- const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
515
+ const decoded = await extractSyncdPatches(result, config?.options);
410
516
  for (const key in decoded) {
411
517
  const name = key;
412
518
  const { patches, hasMorePatches, snapshot } = decoded[name];
413
519
  try {
414
520
  if (snapshot) {
415
- const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
521
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
416
522
  states[name] = newState;
417
523
  Object.assign(globalMutationMap, mutationMap);
418
524
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
@@ -420,7 +526,7 @@ const makeChatsSocket = (config) => {
420
526
  }
421
527
  // only process if there are syncd patches
422
528
  if (patches.length) {
423
- const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
529
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
424
530
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
425
531
  logger.info(`synced ${name} to v${newState.version}`);
426
532
  initialVersionMap[name] = newState.version;
@@ -429,28 +535,47 @@ const makeChatsSocket = (config) => {
429
535
  if (hasMorePatches) {
430
536
  logger.info(`${name} has more patches...`);
431
537
  }
432
- else { // collection is done with sync
538
+ else {
539
+ // collection is done with sync
433
540
  collectionsToHandle.delete(name);
434
541
  }
435
542
  }
436
543
  catch (error) {
437
- // if retry attempts overshoot
438
- // or key not found
439
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
440
- || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
441
- || error.name === 'TypeError';
442
- logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
443
- await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
444
- // increment number of retries
445
544
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
446
- if (isIrrecoverableError) {
447
- // stop retrying
545
+ const logData = {
546
+ name,
547
+ attempt: attemptsMap[name],
548
+ version: states[name].version,
549
+ statusCode: error.output?.statusCode,
550
+ errorType: error.name,
551
+ error: error.stack
552
+ };
553
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
554
+ // WA Web treats missing keys as "Blocked" — park the collection
555
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
556
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
557
+ blockedCollections.add(name);
558
+ collectionsToHandle.delete(name);
559
+ }
560
+ else if (isMissingKeyError(error)) {
561
+ // Retry with a snapshot which may use a different key.
562
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
563
+ forceSnapshotCollections.add(name);
564
+ }
565
+ else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
566
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
448
567
  collectionsToHandle.delete(name);
449
568
  }
569
+ else {
570
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
571
+ // force a full snapshot on retry to recover from
572
+ // corrupted local state (e.g. LTHash MAC mismatch)
573
+ forceSnapshotCollections.add(name);
574
+ }
450
575
  }
451
576
  }
452
577
  }
453
- });
578
+ }, authState?.creds?.me?.id || 'resync-app-state');
454
579
  const { onMutation } = newAppStateChunkHandler(isInitialSync);
455
580
  for (const key in globalMutationMap) {
456
581
  onMutation(globalMutationMap[key]);
@@ -462,31 +587,65 @@ const makeChatsSocket = (config) => {
462
587
  * type = "image for the high res picture"
463
588
  */
464
589
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
465
- var _a;
466
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
590
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
591
+ // and never for own profile pic (Chat model for self has no tcToken).
592
+ // Including tctoken for own JID causes the server to never respond.
593
+ const normalizedJid = jidNormalizedUser(jid);
594
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
595
+ const me = authState.creds.me;
596
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
597
+ let tcTokenContent;
598
+ if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
599
+ tcTokenContent = await buildTcTokenFromJid({
600
+ authState,
601
+ jid: normalizedJid,
602
+ getLIDForPN
603
+ });
604
+ }
605
+ jid = jidNormalizedUser(jid);
467
606
  const result = await query({
468
607
  tag: 'iq',
469
608
  attrs: {
470
609
  target: jid,
471
- to: WABinary_1.S_WHATSAPP_NET,
610
+ to: S_WHATSAPP_NET,
472
611
  type: 'get',
473
612
  xmlns: 'w:profile:picture'
474
613
  },
614
+ content: buildProfilePictureQueryContent(type, tcTokenContent)
615
+ }, timeoutMs);
616
+ const child = getBinaryNodeChild(result, 'picture');
617
+ return child?.attrs?.url;
618
+ };
619
+ const createCallLink = async (type, event, timeoutMs) => {
620
+ const result = await query({
621
+ tag: 'call',
622
+ attrs: {
623
+ id: generateMessageTag(),
624
+ to: '@call'
625
+ },
475
626
  content: [
476
- { tag: 'picture', attrs: { type, query: 'url' } }
627
+ {
628
+ tag: 'link_create',
629
+ attrs: { media: type },
630
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
631
+ }
477
632
  ]
478
633
  }, timeoutMs);
479
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
480
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
634
+ const child = getBinaryNodeChild(result, 'link_create');
635
+ return child?.attrs?.token;
481
636
  };
482
637
  const sendPresenceUpdate = async (type, toJid) => {
483
638
  const me = authState.creds.me;
484
- if (type === 'available' || type === 'unavailable') {
639
+ const isAvailableType = type === 'available';
640
+ if (isAvailableType || type === 'unavailable') {
485
641
  if (!me.name) {
486
642
  logger.warn('no name present, ignoring presence update request...');
487
643
  return;
488
644
  }
489
- ev.emit('connection.update', { isOnline: type === 'available' });
645
+ ev.emit('connection.update', { isOnline: isAvailableType });
646
+ if (isAvailableType) {
647
+ void sendUnifiedSession();
648
+ }
490
649
  await sendNode({
491
650
  tag: 'presence',
492
651
  attrs: {
@@ -496,13 +655,13 @@ const makeChatsSocket = (config) => {
496
655
  });
497
656
  }
498
657
  else {
499
- const { server } = (0, WABinary_1.jidDecode)(toJid);
658
+ const { server } = jidDecode(toJid);
500
659
  const isLid = server === 'lid';
501
660
  await sendNode({
502
661
  tag: 'chatstate',
503
662
  attrs: {
504
663
  from: isLid ? me.lid : me.id,
505
- to: toJid,
664
+ to: toJid
506
665
  },
507
666
  content: [
508
667
  {
@@ -517,35 +676,35 @@ const makeChatsSocket = (config) => {
517
676
  * @param toJid the jid to subscribe to
518
677
  * @param tcToken token for subscription, use if present
519
678
  */
520
- const presenceSubscribe = (toJid, tcToken) => (sendNode({
521
- tag: 'presence',
522
- attrs: {
523
- to: toJid,
524
- id: generateMessageTag(),
525
- type: 'subscribe'
526
- },
527
- content: tcToken
528
- ? [
529
- {
530
- tag: 'tctoken',
531
- attrs: {},
532
- content: tcToken
533
- }
534
- ]
535
- : undefined
536
- }));
679
+ const presenceSubscribe = async (toJid) => {
680
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
681
+ const normalizedToJid = jidNormalizedUser(toJid);
682
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
683
+ const tcTokenContent = isUserJid
684
+ ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
685
+ : undefined;
686
+ return sendNode({
687
+ tag: 'presence',
688
+ attrs: {
689
+ to: toJid,
690
+ id: generateMessageTag(),
691
+ type: 'subscribe'
692
+ },
693
+ content: tcTokenContent
694
+ });
695
+ };
537
696
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
538
- var _a;
539
697
  let presence;
540
698
  const jid = attrs.from;
541
699
  const participant = attrs.participant || attrs.from;
542
- if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
700
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
543
701
  return;
544
702
  }
545
703
  if (tag === 'presence') {
546
704
  presence = {
547
705
  lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
548
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
706
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
707
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
549
708
  };
550
709
  }
551
710
  else if (Array.isArray(content)) {
@@ -554,7 +713,7 @@ const makeChatsSocket = (config) => {
554
713
  if (type === 'paused') {
555
714
  type = 'available';
556
715
  }
557
- if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
716
+ if (firstChild.attrs?.media === 'audio') {
558
717
  type = 'recording';
559
718
  }
560
719
  presence = { lastKnownPresence: type };
@@ -570,22 +729,22 @@ const makeChatsSocket = (config) => {
570
729
  const name = patchCreate.type;
571
730
  const myAppStateKeyId = authState.creds.myAppStateKeyId;
572
731
  if (!myAppStateKeyId) {
573
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
732
+ throw new Boom('App state key not present!', { statusCode: 400 });
574
733
  }
575
734
  let initial;
576
735
  let encodeResult;
577
- await processingMutex.mutex(async () => {
736
+ await appStatePatchMutex.mutex(async () => {
578
737
  await authState.keys.transaction(async () => {
579
738
  logger.debug({ patch: patchCreate }, 'applying app patch');
580
739
  await resyncAppState([name], false);
581
740
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
582
- initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
583
- encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
741
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
742
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
584
743
  const { patch, state } = encodeResult;
585
744
  const node = {
586
745
  tag: 'iq',
587
746
  attrs: {
588
- to: WABinary_1.S_WHATSAPP_NET,
747
+ to: S_WHATSAPP_NET,
589
748
  type: 'set',
590
749
  xmlns: 'w:sync:app:state'
591
750
  },
@@ -599,13 +758,13 @@ const makeChatsSocket = (config) => {
599
758
  attrs: {
600
759
  name,
601
760
  version: (state.version - 1).toString(),
602
- 'return_snapshot': 'false'
761
+ return_snapshot: 'false'
603
762
  },
604
763
  content: [
605
764
  {
606
765
  tag: 'patch',
607
766
  attrs: {},
608
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
767
+ content: proto.SyncdPatch.encode(patch).finish()
609
768
  }
610
769
  ]
611
770
  }
@@ -615,54 +774,78 @@ const makeChatsSocket = (config) => {
615
774
  };
616
775
  await query(node);
617
776
  await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
618
- });
777
+ }, authState?.creds?.me?.id || 'app-patch');
619
778
  });
620
779
  if (config.emitOwnEvents) {
621
780
  const { onMutation } = newAppStateChunkHandler(false);
622
- const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
781
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
623
782
  for (const key in mutationMap) {
624
783
  onMutation(mutationMap[key]);
625
784
  }
626
785
  }
627
786
  };
628
- /** sending non-abt props may fix QR scan fail if server expects */
787
+ /** fetch AB props */
629
788
  const fetchProps = async () => {
630
- var _a, _b, _c;
631
789
  const resultNode = await query({
632
790
  tag: 'iq',
633
791
  attrs: {
634
- to: WABinary_1.S_WHATSAPP_NET,
635
- xmlns: 'w',
636
- type: 'get',
792
+ to: S_WHATSAPP_NET,
793
+ xmlns: 'abt',
794
+ type: 'get'
637
795
  },
638
796
  content: [
639
- { tag: 'props', attrs: {
640
- protocol: '2',
641
- hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
642
- } }
797
+ {
798
+ tag: 'props',
799
+ attrs: {
800
+ protocol: '1',
801
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
802
+ }
803
+ }
643
804
  ]
644
805
  });
645
- const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
806
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
646
807
  let props = {};
647
808
  if (propsNode) {
648
- if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
649
- authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
809
+ if (propsNode.attrs?.hash) {
810
+ // on some clients, the hash is returning as undefined
811
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
650
812
  ev.emit('creds.update', authState.creds);
651
813
  }
652
- props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
814
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
815
+ }
816
+ // Extract protocol-relevant AB props (only the ones we need)
817
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
818
+ if (privacyTokenProp !== undefined) {
819
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
820
+ }
821
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
822
+ if (profilePicProp !== undefined) {
823
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
824
+ }
825
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
826
+ if (lidIssueProp !== undefined) {
827
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
653
828
  }
654
- logger.debug('fetched props');
829
+ logger.debug({ serverProps }, 'fetched props');
655
830
  return props;
656
831
  };
657
832
  /**
658
833
  * modify a chat -- mark unread, read etc.
659
834
  * lastMessages must be sorted in reverse chronologically
660
835
  * requires the last messages till the last message received; required for archive & unread
661
- */
836
+ */
662
837
  const chatModify = (mod, jid) => {
663
- const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
838
+ const patch = chatModificationToAppPatch(mod, jid);
664
839
  return appPatch(patch);
665
840
  };
841
+ /**
842
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
843
+ */
844
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
845
+ return chatModify({
846
+ disableLinkPreviews: { isPreviewsDisabled }
847
+ }, '');
848
+ };
666
849
  /**
667
850
  * Star or Unstar a message
668
851
  */
@@ -674,6 +857,32 @@ const makeChatsSocket = (config) => {
674
857
  }
675
858
  }, jid);
676
859
  };
860
+ /**
861
+ * Add or Edit Contact
862
+ */
863
+ const addOrEditContact = (jid, contact) => {
864
+ return chatModify({
865
+ contact
866
+ }, jid);
867
+ };
868
+ /**
869
+ * Remove Contact
870
+ */
871
+ const removeContact = (jid) => {
872
+ return chatModify({
873
+ contact: null
874
+ }, jid);
875
+ };
876
+ /**
877
+ * Adds label
878
+ */
879
+ const addLabel = (jid, labels) => {
880
+ return chatModify({
881
+ addLabel: {
882
+ ...labels
883
+ }
884
+ }, jid);
885
+ };
677
886
  /**
678
887
  * Adds label for the chats
679
888
  */
@@ -716,49 +925,156 @@ const makeChatsSocket = (config) => {
716
925
  }
717
926
  }, jid);
718
927
  };
928
+ /**
929
+ * Add or Edit Quick Reply
930
+ */
931
+ const addOrEditQuickReply = (quickReply) => {
932
+ return chatModify({
933
+ quickReply
934
+ }, '');
935
+ };
936
+ /**
937
+ * Remove Quick Reply
938
+ */
939
+ const removeQuickReply = (timestamp) => {
940
+ return chatModify({
941
+ quickReply: { timestamp, deleted: true }
942
+ }, '');
943
+ };
719
944
  /**
720
945
  * queries need to be fired on connection open
721
946
  * help ensure parity with WA Web
722
947
  * */
723
948
  const executeInitQueries = async () => {
724
- await Promise.all([
725
- fetchProps(),
726
- fetchBlocklist(),
727
- fetchPrivacySettings(),
728
- ]);
949
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
950
+ };
951
+ const isWASystemNotification = (msg) => {
952
+ const content = msg?.message;
953
+ if (!content)
954
+ return false;
955
+ const protoType = content.protocolMessage?.type;
956
+ if (protoType === proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION ||
957
+ protoType === proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE ||
958
+ protoType === proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE ||
959
+ protoType === proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC) {
960
+ return true;
961
+ }
962
+ if (msg.messageStubType && !content.conversation && !content.extendedTextMessage) {
963
+ const stub = msg.messageStubType;
964
+ const SYSTEM_STUB_TYPES = new Set([
965
+ WAMessageStubType.E2E_DEVICE_CHANGED,
966
+ WAMessageStubType.E2E_ENCRYPTED,
967
+ WAMessageStubType.E2E_IDENTITY_CHANGED,
968
+ WAMessageStubType.CIPHERTEXT,
969
+ WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP,
970
+ WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
971
+ ]);
972
+ if (SYSTEM_STUB_TYPES.has(stub))
973
+ return true;
974
+ }
975
+ return false;
729
976
  };
730
977
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
731
- var _a, _b, _c;
978
+ if (isWASystemNotification(msg)) {
979
+ msg.isSystemNotification = true;
980
+ }
732
981
  ev.emit('messages.upsert', { messages: [msg], type });
733
982
  if (!!msg.pushName) {
734
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
735
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
983
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
984
+ jid = jidNormalizedUser(jid);
736
985
  if (!msg.key.fromMe) {
737
986
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
738
987
  }
739
988
  // update our pushname too
740
- if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
989
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
741
990
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
742
991
  }
743
992
  }
744
- const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
993
+ const historyMsg = getHistoryMsg(msg.message);
745
994
  const shouldProcessHistoryMsg = historyMsg
746
- ? (shouldSyncHistoryMessage(historyMsg)
747
- && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
995
+ ? shouldSyncHistoryMessage(historyMsg) &&
996
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
748
997
  : false;
749
- if (historyMsg && !authState.creds.myAppStateKeyId) {
750
- logger.warn('skipping app state sync, as myAppStateKeyId is not set');
751
- pendingAppStateSync = true;
998
+ if (historyMsg && shouldProcessHistoryMsg) {
999
+ const syncType = historyMsg.syncType;
1000
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
1001
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
1002
+ !historySyncStatus.initialBootstrapComplete) {
1003
+ historySyncStatus.initialBootstrapComplete = true;
1004
+ ev.emit('messaging-history.status', {
1005
+ syncType,
1006
+ status: 'complete',
1007
+ explicit: true
1008
+ });
1009
+ }
1010
+ // RECENT with progress === 100 — explicit completion
1011
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
1012
+ historyMsg.progress === 100 &&
1013
+ !historySyncStatus.recentSyncComplete) {
1014
+ historySyncStatus.recentSyncComplete = true;
1015
+ clearTimeout(historySyncPausedTimeout);
1016
+ historySyncPausedTimeout = undefined;
1017
+ ev.emit('messaging-history.status', {
1018
+ syncType,
1019
+ status: 'complete',
1020
+ explicit: true
1021
+ });
1022
+ }
1023
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
1024
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
1025
+ clearTimeout(historySyncPausedTimeout);
1026
+ historySyncPausedTimeout = setTimeout(() => {
1027
+ if (!historySyncStatus.recentSyncComplete) {
1028
+ historySyncStatus.recentSyncComplete = true;
1029
+ ev.emit('messaging-history.status', {
1030
+ syncType: proto.HistorySync.HistorySyncType.RECENT,
1031
+ status: 'paused',
1032
+ explicit: false
1033
+ });
1034
+ }
1035
+ historySyncPausedTimeout = undefined;
1036
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
1037
+ }
1038
+ }
1039
+ // State machine: decide on sync and flush
1040
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
1041
+ if (awaitingSyncTimeout) {
1042
+ clearTimeout(awaitingSyncTimeout);
1043
+ awaitingSyncTimeout = undefined;
1044
+ }
1045
+ if (shouldProcessHistoryMsg) {
1046
+ syncState = SyncState.Syncing;
1047
+ logger.info('Transitioned to Syncing state');
1048
+ // Let doAppStateSync handle the final flush after it's done
1049
+ }
1050
+ else {
1051
+ syncState = SyncState.Online;
1052
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
1053
+ ev.flush();
1054
+ }
752
1055
  }
1056
+ const doAppStateSync = async () => {
1057
+ if (syncState === SyncState.Syncing) {
1058
+ // All collections will be synced, so clear any blocked ones
1059
+ blockedCollections.clear();
1060
+ logger.info('Doing app state sync');
1061
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
1062
+ // Sync is complete, go online and flush everything
1063
+ syncState = SyncState.Online;
1064
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
1065
+ ev.flush();
1066
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1067
+ ev.emit('creds.update', { accountSyncCounter });
1068
+ }
1069
+ };
753
1070
  await Promise.all([
754
1071
  (async () => {
755
- if (historyMsg
756
- && authState.creds.myAppStateKeyId) {
757
- pendingAppStateSync = false;
1072
+ if (shouldProcessHistoryMsg) {
758
1073
  await doAppStateSync();
759
1074
  }
760
1075
  })(),
761
- (0, process_message_1.default)(msg, {
1076
+ processMessage(msg, {
1077
+ signalRepository,
762
1078
  shouldProcessHistoryMsg,
763
1079
  placeholderResendCache,
764
1080
  ev,
@@ -766,31 +1082,19 @@ const makeChatsSocket = (config) => {
766
1082
  keyStore: authState.keys,
767
1083
  logger,
768
1084
  options: config.options,
769
- getMessage: config.getMessage,
1085
+ getMessage
770
1086
  })
771
1087
  ]);
772
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
773
- && pendingAppStateSync) {
1088
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1089
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1090
+ logger.info('App state sync key arrived, triggering app state sync');
774
1091
  await doAppStateSync();
775
- pendingAppStateSync = false;
776
- }
777
- async function doAppStateSync() {
778
- if (!authState.creds.accountSyncCounter) {
779
- logger.info('doing initial app state sync');
780
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
781
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
782
- ev.emit('creds.update', { accountSyncCounter });
783
- if (needToFlushWithAppStateSync) {
784
- logger.debug('flushing with app state sync');
785
- ev.flush();
786
- }
787
- }
788
1092
  }
789
1093
  });
790
1094
  ws.on('CB:presence', handlePresenceUpdate);
791
1095
  ws.on('CB:chatstate', handlePresenceUpdate);
792
1096
  ws.on('CB:ib,,dirty', async (node) => {
793
- const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
1097
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
794
1098
  const type = attrs.type;
795
1099
  switch (type) {
796
1100
  case 'account_sync':
@@ -812,42 +1116,123 @@ const makeChatsSocket = (config) => {
812
1116
  }
813
1117
  });
814
1118
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
815
- var _a;
1119
+ if (connection === 'close') {
1120
+ blockedCollections.clear();
1121
+ clearTimeout(historySyncPausedTimeout);
1122
+ historySyncPausedTimeout = undefined;
1123
+ }
816
1124
  if (connection === 'open') {
817
1125
  if (fireInitQueries) {
818
- executeInitQueries()
819
- .catch(error => onUnexpectedError(error, 'init queries'));
1126
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
820
1127
  }
821
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
822
- .catch(error => onUnexpectedError(error, 'presence update requests'));
1128
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
823
1129
  }
824
- if (receivedPendingNotifications && // if we don't have the app state key
825
- // we keep buffering events until we finally have
826
- // the key and can sync the messages
827
- !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
828
- ev.buffer();
829
- needToFlushWithAppStateSync = true;
1130
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1131
+ return;
1132
+ }
1133
+ historySyncStatus.initialBootstrapComplete = false;
1134
+ historySyncStatus.recentSyncComplete = false;
1135
+ clearTimeout(historySyncPausedTimeout);
1136
+ historySyncPausedTimeout = undefined;
1137
+ syncState = SyncState.AwaitingInitialSync;
1138
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1139
+ ev.buffer();
1140
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1141
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1142
+ }));
1143
+ if (!willSyncHistory) {
1144
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1145
+ syncState = SyncState.Online;
1146
+ setTimeout(() => ev.flush(), 0);
1147
+ return;
1148
+ }
1149
+ // On reconnection (accountSyncCounter > 0), the server does not push
1150
+ // history sync notifications — the device already has its data.
1151
+ // Skip the 20s wait and go online immediately.
1152
+ if (authState.creds.accountSyncCounter > 0) {
1153
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1154
+ syncState = SyncState.Online;
1155
+ setTimeout(() => ev.flush(), 0);
1156
+ return;
1157
+ }
1158
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1159
+ if (awaitingSyncTimeout) {
1160
+ clearTimeout(awaitingSyncTimeout);
1161
+ }
1162
+ awaitingSyncTimeout = setTimeout(() => {
1163
+ if (syncState === SyncState.AwaitingInitialSync) {
1164
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1165
+ syncState = SyncState.Online;
1166
+ ev.flush();
1167
+ // Increment so subsequent reconnections skip the 20s wait.
1168
+ // Late-arriving history is still processed via processMessage
1169
+ // regardless of the state machine phase.
1170
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1171
+ ev.emit('creds.update', { accountSyncCounter });
1172
+ }
1173
+ }, 20000);
1174
+ });
1175
+ // When an app state sync key arrives (myAppStateKeyId is set) and there are
1176
+ // collections blocked on a missing key, trigger a re-sync for just those collections.
1177
+ // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1178
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
1179
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
1180
+ return;
1181
+ }
1182
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
1183
+ if (syncState === SyncState.Syncing) {
1184
+ blockedCollections.clear();
1185
+ return;
1186
+ }
1187
+ const collections = [...blockedCollections];
1188
+ blockedCollections.clear();
1189
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1190
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1191
+ });
1192
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1193
+ try {
1194
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1195
+ }
1196
+ catch (error) {
1197
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
830
1198
  }
831
1199
  });
1200
+ registerSocketEndHandler(() => {
1201
+ if (awaitingSyncTimeout) {
1202
+ clearTimeout(awaitingSyncTimeout);
1203
+ awaitingSyncTimeout = undefined;
1204
+ }
1205
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1206
+ placeholderResendCache.close();
1207
+ }
1208
+ syncState = SyncState.Connecting;
1209
+ privacySettings = undefined;
1210
+ });
832
1211
  return {
833
1212
  ...sock,
1213
+ serverProps,
1214
+ createCallLink,
834
1215
  getBotListV2,
835
- processingMutex,
1216
+ messageMutex,
1217
+ receiptMutex,
1218
+ appStatePatchMutex,
1219
+ notificationMutex,
836
1220
  fetchPrivacySettings,
837
1221
  upsertMessage,
838
1222
  appPatch,
839
1223
  sendPresenceUpdate,
840
1224
  presenceSubscribe,
841
1225
  profilePictureUrl,
842
- onWhatsApp,
843
1226
  fetchBlocklist,
844
- fetchDisappearingDuration,
845
1227
  fetchStatus,
1228
+ fetchDisappearingDuration,
1229
+ findUserId,
846
1230
  updateProfilePicture,
847
1231
  removeProfilePicture,
848
1232
  updateProfileStatus,
849
1233
  updateProfileName,
850
1234
  updateBlockStatus,
1235
+ updateDisableLinkPreviewsPrivacy,
851
1236
  updateCallPrivacy,
852
1237
  updateMessagesPrivacy,
853
1238
  updateLastSeenPrivacy,
@@ -861,11 +1246,17 @@ const makeChatsSocket = (config) => {
861
1246
  resyncAppState,
862
1247
  chatModify,
863
1248
  cleanDirtyBits,
1249
+ addOrEditContact,
1250
+ removeContact,
1251
+ placeholderResendCache,
1252
+ addLabel,
864
1253
  addChatLabel,
865
1254
  removeChatLabel,
866
1255
  addMessageLabel,
867
1256
  removeMessageLabel,
868
- star
1257
+ star,
1258
+ addOrEditQuickReply,
1259
+ removeQuickReply
869
1260
  };
870
1261
  };
871
- exports.makeChatsSocket = makeChatsSocket;
1262
+ //# sourceMappingURL=chats.js.map