@vanzxysenpai/baileys 0.0.0-stage → 0.0.2

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