@neykoor/baileys 7.0.0-rc13

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