@baileysmod-ubed/baileys 0.3.17

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