@ryuhan/baileys 1.0.10 → 2.0.1

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