@vanzxysenpai/baileys 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (431) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +25 -0
  3. package/NOTICE.md +158 -0
  4. package/README.md +5294 -2
  5. package/VanzxyBanner.js +134 -0
  6. package/WAProto/index.d.ts +13317 -0
  7. package/WAProto/index.js +147553 -0
  8. package/lib/Builders/A2UI.d.ts +131 -0
  9. package/lib/Builders/A2UI.js +343 -0
  10. package/lib/Builders/AIRich.d.ts +1021 -0
  11. package/lib/Builders/AIRich.js +2889 -0
  12. package/lib/Builders/Album.d.ts +51 -0
  13. package/lib/Builders/Album.js +99 -0
  14. package/lib/Builders/Button.d.ts +137449 -0
  15. package/lib/Builders/Button.js +1054 -0
  16. package/lib/Builders/ButtonV2.d.ts +43 -0
  17. package/lib/Builders/ButtonV2.js +175 -0
  18. package/lib/Builders/ButtonV3.d.ts +35 -0
  19. package/lib/Builders/ButtonV3.js +189 -0
  20. package/lib/Builders/Carousel.d.ts +68 -0
  21. package/lib/Builders/Carousel.js +161 -0
  22. package/lib/Builders/Event.d.ts +61 -0
  23. package/lib/Builders/Event.js +118 -0
  24. package/lib/Builders/Expiring.d.ts +17 -0
  25. package/lib/Builders/Expiring.js +27 -0
  26. package/lib/Builders/Poll.d.ts +63 -0
  27. package/lib/Builders/Poll.js +139 -0
  28. package/lib/Builders/VanzxyBaileys.d.ts +42 -0
  29. package/lib/Builders/VanzxyBaileys.js +110 -0
  30. package/lib/Builders/errors.d.ts +25 -0
  31. package/lib/Builders/errors.js +29 -0
  32. package/lib/Builders/index.d.ts +14 -0
  33. package/lib/Builders/index.js +23 -0
  34. package/lib/Builders/shared.d.ts +395 -0
  35. package/lib/Builders/shared.js +738 -0
  36. package/lib/Defaults/bot-jid.d.ts +1 -0
  37. package/lib/Defaults/bot-jid.js +1 -0
  38. package/lib/Defaults/index.d.ts +161 -0
  39. package/lib/Defaults/index.js +165 -0
  40. package/lib/Defaults/version.d.ts +1 -0
  41. package/lib/Defaults/version.js +1 -0
  42. package/lib/Framework/Bot.d.ts +865 -0
  43. package/lib/Framework/Bot.js +230 -0
  44. package/lib/Framework/Context.d.ts +17 -0
  45. package/lib/Framework/Context.js +90 -0
  46. package/lib/Framework/MediaManager.d.ts +15 -0
  47. package/lib/Framework/MediaManager.js +154 -0
  48. package/lib/Framework/SessionManager.d.ts +10 -0
  49. package/lib/Framework/SessionManager.js +34 -0
  50. package/lib/Framework/StatsManager.d.ts +20 -0
  51. package/lib/Framework/StatsManager.js +117 -0
  52. package/lib/Framework/Store/SQLiteStore.d.ts +13 -0
  53. package/lib/Framework/Store/SQLiteStore.js +68 -0
  54. package/lib/Framework/index.d.ts +6 -0
  55. package/lib/Framework/index.js +11 -0
  56. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  57. package/lib/Signal/Group/ciphertext-message.js +11 -0
  58. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  59. package/lib/Signal/Group/group-session-builder.js +29 -0
  60. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  61. package/lib/Signal/Group/group_cipher.js +81 -0
  62. package/lib/Signal/Group/index.d.ts +11 -0
  63. package/lib/Signal/Group/index.js +11 -0
  64. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  65. package/lib/Signal/Group/keyhelper.js +17 -0
  66. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  67. package/lib/Signal/Group/sender-chain-key.js +25 -0
  68. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  69. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  70. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  71. package/lib/Signal/Group/sender-key-message.js +65 -0
  72. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  73. package/lib/Signal/Group/sender-key-name.js +47 -0
  74. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  75. package/lib/Signal/Group/sender-key-record.js +40 -0
  76. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  77. package/lib/Signal/Group/sender-key-state.js +83 -0
  78. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  79. package/lib/Signal/Group/sender-message-key.js +25 -0
  80. package/lib/Signal/libsignal.d.ts +58 -0
  81. package/lib/Signal/libsignal.js +436 -0
  82. package/lib/Signal/lid-mapping.d.ts +20 -0
  83. package/lib/Signal/lid-mapping.js +276 -0
  84. package/lib/Socket/Client/index.d.ts +2 -0
  85. package/lib/Socket/Client/index.js +2 -0
  86. package/lib/Socket/Client/types.d.ts +5 -0
  87. package/lib/Socket/Client/types.js +10 -0
  88. package/lib/Socket/Client/websocket.d.ts +12 -0
  89. package/lib/Socket/Client/websocket.js +53 -0
  90. package/lib/Socket/business.d.ts +674 -0
  91. package/lib/Socket/business.js +379 -0
  92. package/lib/Socket/chats.d.ts +137 -0
  93. package/lib/Socket/chats.js +1299 -0
  94. package/lib/Socket/communities.d.ts +805 -0
  95. package/lib/Socket/communities.js +454 -0
  96. package/lib/Socket/dugong.d.ts +118 -0
  97. package/lib/Socket/dugong.js +810 -0
  98. package/lib/Socket/groups.d.ts +287 -0
  99. package/lib/Socket/groups.js +386 -0
  100. package/lib/Socket/index.d.ts +826 -0
  101. package/lib/Socket/index.js +35 -0
  102. package/lib/Socket/messages-recv.d.ts +613 -0
  103. package/lib/Socket/messages-recv.js +1851 -0
  104. package/lib/Socket/messages-send.d.ts +608 -0
  105. package/lib/Socket/messages-send.js +1574 -0
  106. package/lib/Socket/mex-fallback.d.ts +51 -0
  107. package/lib/Socket/mex-fallback.js +97 -0
  108. package/lib/Socket/mex.d.ts +1 -0
  109. package/lib/Socket/mex.js +41 -0
  110. package/lib/Socket/newsletter-ext.d.ts +47 -0
  111. package/lib/Socket/newsletter-ext.js +262 -0
  112. package/lib/Socket/newsletter.d.ts +285 -0
  113. package/lib/Socket/newsletter.js +223 -0
  114. package/lib/Socket/socket.d.ts +60 -0
  115. package/lib/Socket/socket.js +1001 -0
  116. package/lib/Socket/username.d.ts +842 -0
  117. package/lib/Socket/username.js +156 -0
  118. package/lib/Store/index.d.ts +3 -0
  119. package/lib/Store/index.js +3 -0
  120. package/lib/Store/make-in-memory-store.d.ts +62 -0
  121. package/lib/Store/make-in-memory-store.js +425 -0
  122. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  123. package/lib/Store/make-ordered-dictionary.js +78 -0
  124. package/lib/Store/object-repository.d.ts +10 -0
  125. package/lib/Store/object-repository.js +23 -0
  126. package/lib/Types/Auth.d.ts +1 -0
  127. package/lib/Types/Auth.js +1 -0
  128. package/lib/Types/Bussines.d.ts +1 -0
  129. package/lib/Types/Bussines.js +1 -0
  130. package/lib/Types/Call.d.ts +1 -0
  131. package/lib/Types/Call.js +1 -0
  132. package/lib/Types/Chat.d.ts +1 -0
  133. package/lib/Types/Chat.js +7 -0
  134. package/lib/Types/Contact.d.ts +1 -0
  135. package/lib/Types/Contact.js +1 -0
  136. package/lib/Types/Events.d.ts +1 -0
  137. package/lib/Types/Events.js +1 -0
  138. package/lib/Types/GroupMetadata.d.ts +1 -0
  139. package/lib/Types/GroupMetadata.js +1 -0
  140. package/lib/Types/Label.d.ts +2 -0
  141. package/lib/Types/Label.js +24 -0
  142. package/lib/Types/LabelAssociation.d.ts +2 -0
  143. package/lib/Types/LabelAssociation.js +6 -0
  144. package/lib/Types/Message.d.ts +11 -0
  145. package/lib/Types/Message.js +17 -0
  146. package/lib/Types/Mex.d.ts +2 -0
  147. package/lib/Types/Mex.js +38 -0
  148. package/lib/Types/Product.d.ts +1 -0
  149. package/lib/Types/Product.js +1 -0
  150. package/lib/Types/RichType.d.ts +2 -0
  151. package/lib/Types/RichType.js +22 -0
  152. package/lib/Types/Signal.d.ts +1 -0
  153. package/lib/Types/Signal.js +1 -0
  154. package/lib/Types/Socket.d.ts +1 -0
  155. package/lib/Types/Socket.js +1 -0
  156. package/lib/Types/State.d.ts +5 -0
  157. package/lib/Types/State.js +55 -0
  158. package/lib/Types/USync.d.ts +1 -0
  159. package/lib/Types/USync.js +1 -0
  160. package/lib/Types/index.d.ts +15 -0
  161. package/lib/Types/index.js +27 -0
  162. package/lib/Utils/PersistentStore.d.ts +83 -0
  163. package/lib/Utils/PersistentStore.js +592 -0
  164. package/lib/Utils/anchor-guard.d.ts +31 -0
  165. package/lib/Utils/anchor-guard.js +329 -0
  166. package/lib/Utils/android-stanza-id.d.ts +4 -0
  167. package/lib/Utils/android-stanza-id.js +21 -0
  168. package/lib/Utils/anti-delete.d.ts +62 -0
  169. package/lib/Utils/anti-delete.js +212 -0
  170. package/lib/Utils/auth-secure.d.ts +180 -0
  171. package/lib/Utils/auth-secure.js +791 -0
  172. package/lib/Utils/auth-utils.d.ts +59 -0
  173. package/lib/Utils/auth-utils.js +326 -0
  174. package/lib/Utils/auto-reconnect.d.ts +8 -0
  175. package/lib/Utils/auto-reconnect.js +204 -0
  176. package/lib/Utils/auto-reply.d.ts +35 -0
  177. package/lib/Utils/auto-reply.js +152 -0
  178. package/lib/Utils/bad-mac-handler.d.ts +59 -0
  179. package/lib/Utils/bad-mac-handler.js +119 -0
  180. package/lib/Utils/baileys-event-stream.d.ts +5 -0
  181. package/lib/Utils/baileys-event-stream.js +62 -0
  182. package/lib/Utils/browser-utils.d.ts +9 -0
  183. package/lib/Utils/browser-utils.js +29 -0
  184. package/lib/Utils/business.d.ts +49 -0
  185. package/lib/Utils/business.js +236 -0
  186. package/lib/Utils/button-helper-utils.d.ts +59 -0
  187. package/lib/Utils/button-helper-utils.js +266 -0
  188. package/lib/Utils/button-sender.d.ts +164 -0
  189. package/lib/Utils/button-sender.js +845 -0
  190. package/lib/Utils/chat-control.d.ts +98 -0
  191. package/lib/Utils/chat-control.js +231 -0
  192. package/lib/Utils/chat-history-helpers.d.ts +4 -0
  193. package/lib/Utils/chat-history-helpers.js +70 -0
  194. package/lib/Utils/chat-utils.d.ts +408 -0
  195. package/lib/Utils/chat-utils.js +879 -0
  196. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  197. package/lib/Utils/companion-reg-client-utils.js +39 -0
  198. package/lib/Utils/connection-watchdog.d.ts +10 -0
  199. package/lib/Utils/connection-watchdog.js +74 -0
  200. package/lib/Utils/crypto.d.ts +41 -0
  201. package/lib/Utils/crypto.js +145 -0
  202. package/lib/Utils/decode-wa-message.d.ts +83 -0
  203. package/lib/Utils/decode-wa-message.js +315 -0
  204. package/lib/Utils/disconnect-reason.d.ts +13 -0
  205. package/lib/Utils/disconnect-reason.js +36 -0
  206. package/lib/Utils/event-buffer.d.ts +12 -0
  207. package/lib/Utils/event-buffer.js +640 -0
  208. package/lib/Utils/fetch-timeout.d.ts +4 -0
  209. package/lib/Utils/fetch-timeout.js +14 -0
  210. package/lib/Utils/ffmpeg-path.d.ts +5 -0
  211. package/lib/Utils/ffmpeg-path.js +130 -0
  212. package/lib/Utils/generics.d.ts +79 -0
  213. package/lib/Utils/generics.js +426 -0
  214. package/lib/Utils/group-metadata-cache.d.ts +3 -0
  215. package/lib/Utils/group-metadata-cache.js +25 -0
  216. package/lib/Utils/group-status-detection.d.ts +5 -0
  217. package/lib/Utils/group-status-detection.js +114 -0
  218. package/lib/Utils/history.d.ts +91 -0
  219. package/lib/Utils/history.js +144 -0
  220. package/lib/Utils/html-app.d.ts +14 -0
  221. package/lib/Utils/html-app.js +97 -0
  222. package/lib/Utils/html-multiplayer.d.ts +8 -0
  223. package/lib/Utils/html-multiplayer.js +90 -0
  224. package/lib/Utils/humanizer.d.ts +8 -0
  225. package/lib/Utils/humanizer.js +74 -0
  226. package/lib/Utils/identity-change-handler.d.ts +13 -0
  227. package/lib/Utils/identity-change-handler.js +49 -0
  228. package/lib/Utils/index.d.ts +88 -0
  229. package/lib/Utils/index.js +93 -0
  230. package/lib/Utils/jid-tools.d.ts +3 -0
  231. package/lib/Utils/jid-tools.js +78 -0
  232. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  233. package/lib/Utils/link-preview-metadata.js +90 -0
  234. package/lib/Utils/link-preview.d.ts +12 -0
  235. package/lib/Utils/link-preview.js +84 -0
  236. package/lib/Utils/lock-manager.d.ts +5 -0
  237. package/lib/Utils/lock-manager.js +50 -0
  238. package/lib/Utils/logger.d.ts +2 -0
  239. package/lib/Utils/logger.js +2 -0
  240. package/lib/Utils/lt-hash.d.ts +12 -0
  241. package/lib/Utils/lt-hash.js +26 -0
  242. package/lib/Utils/make-mutex.d.ts +6 -0
  243. package/lib/Utils/make-mutex.js +32 -0
  244. package/lib/Utils/media-messages.d.ts +35 -0
  245. package/lib/Utils/media-messages.js +70 -0
  246. package/lib/Utils/media-processor.d.ts +6 -0
  247. package/lib/Utils/media-processor.js +174 -0
  248. package/lib/Utils/media-set.d.ts +6 -0
  249. package/lib/Utils/media-set.js +169 -0
  250. package/lib/Utils/message-kind.d.ts +26 -0
  251. package/lib/Utils/message-kind.js +138 -0
  252. package/lib/Utils/message-retry-manager.d.ts +79 -0
  253. package/lib/Utils/message-retry-manager.js +264 -0
  254. package/lib/Utils/message-search.d.ts +40 -0
  255. package/lib/Utils/message-search.js +181 -0
  256. package/lib/Utils/messages-media.d.ts +136 -0
  257. package/lib/Utils/messages-media.js +867 -0
  258. package/lib/Utils/messages.d.ts +66 -0
  259. package/lib/Utils/messages.js +2271 -0
  260. package/lib/Utils/meta-ai-msmsg.d.ts +3 -0
  261. package/lib/Utils/meta-ai-msmsg.js +132 -0
  262. package/lib/Utils/meta-ai.d.ts +4 -0
  263. package/lib/Utils/meta-ai.js +75 -0
  264. package/lib/Utils/migrate-auth-state.d.ts +23 -0
  265. package/lib/Utils/migrate-auth-state.js +126 -0
  266. package/lib/Utils/mini-app.d.ts +20 -0
  267. package/lib/Utils/mini-app.js +215 -0
  268. package/lib/Utils/mock-socket.d.ts +67 -0
  269. package/lib/Utils/mock-socket.js +254 -0
  270. package/lib/Utils/modern-messages.d.ts +64 -0
  271. package/lib/Utils/modern-messages.js +497 -0
  272. package/lib/Utils/native-flow.d.ts +19 -0
  273. package/lib/Utils/native-flow.js +112 -0
  274. package/lib/Utils/newsletter-status.d.ts +157 -0
  275. package/lib/Utils/newsletter-status.js +652 -0
  276. package/lib/Utils/noise-handler.d.ts +20 -0
  277. package/lib/Utils/noise-handler.js +200 -0
  278. package/lib/Utils/offline-node-processor.d.ts +9 -0
  279. package/lib/Utils/offline-node-processor.js +39 -0
  280. package/lib/Utils/pairing-utils.d.ts +5 -0
  281. package/lib/Utils/pairing-utils.js +29 -0
  282. package/lib/Utils/passkey.d.ts +4 -0
  283. package/lib/Utils/passkey.js +11 -0
  284. package/lib/Utils/past-participants.d.ts +2 -0
  285. package/lib/Utils/past-participants.js +40 -0
  286. package/lib/Utils/payment-detection.d.ts +40 -0
  287. package/lib/Utils/payment-detection.js +213 -0
  288. package/lib/Utils/payment-guard.d.ts +28 -0
  289. package/lib/Utils/payment-guard.js +143 -0
  290. package/lib/Utils/payment-messages.d.ts +42 -0
  291. package/lib/Utils/payment-messages.js +161 -0
  292. package/lib/Utils/payment-utils.d.ts +75 -0
  293. package/lib/Utils/payment-utils.js +145 -0
  294. package/lib/Utils/phone-utils.d.ts +3 -0
  295. package/lib/Utils/phone-utils.js +29 -0
  296. package/lib/Utils/pre-key-manager.d.ts +25 -0
  297. package/lib/Utils/pre-key-manager.js +105 -0
  298. package/lib/Utils/process-message.d.ts +103 -0
  299. package/lib/Utils/process-message.js +868 -0
  300. package/lib/Utils/qr-terminal.d.ts +1 -0
  301. package/lib/Utils/qr-terminal.js +16 -0
  302. package/lib/Utils/reconnect-backoff.d.ts +25 -0
  303. package/lib/Utils/reconnect-backoff.js +47 -0
  304. package/lib/Utils/reporting-utils.d.ts +12 -0
  305. package/lib/Utils/reporting-utils.js +257 -0
  306. package/lib/Utils/rich-message-utils.d.ts +54 -0
  307. package/lib/Utils/rich-message-utils.js +435 -0
  308. package/lib/Utils/rich-messages.d.ts +298 -0
  309. package/lib/Utils/rich-messages.js +1145 -0
  310. package/lib/Utils/scheduled-message.d.ts +81 -0
  311. package/lib/Utils/scheduled-message.js +101 -0
  312. package/lib/Utils/scheduling.d.ts +59 -0
  313. package/lib/Utils/scheduling.js +139 -0
  314. package/lib/Utils/signal.d.ts +82 -0
  315. package/lib/Utils/signal.js +200 -0
  316. package/lib/Utils/stanza-ack.d.ts +16 -0
  317. package/lib/Utils/stanza-ack.js +37 -0
  318. package/lib/Utils/status-stickers.d.ts +79 -0
  319. package/lib/Utils/status-stickers.js +261 -0
  320. package/lib/Utils/status.d.ts +107 -0
  321. package/lib/Utils/status.js +131 -0
  322. package/lib/Utils/sticker-pack-maker.d.ts +20 -0
  323. package/lib/Utils/sticker-pack-maker.js +112 -0
  324. package/lib/Utils/stickerpack.d.ts +18 -0
  325. package/lib/Utils/stickerpack.js +316 -0
  326. package/lib/Utils/sync-action-utils.d.ts +2 -0
  327. package/lib/Utils/sync-action-utils.js +48 -0
  328. package/lib/Utils/tag.d.ts +8 -0
  329. package/lib/Utils/tag.js +45 -0
  330. package/lib/Utils/tc-token-utils.d.ts +29 -0
  331. package/lib/Utils/tc-token-utils.js +162 -0
  332. package/lib/Utils/templates.d.ts +86 -0
  333. package/lib/Utils/templates.js +148 -0
  334. package/lib/Utils/text-format.d.ts +13 -0
  335. package/lib/Utils/text-format.js +81 -0
  336. package/lib/Utils/text-tools.d.ts +3 -0
  337. package/lib/Utils/text-tools.js +38 -0
  338. package/lib/Utils/ttl-cache.d.ts +29 -0
  339. package/lib/Utils/ttl-cache.js +123 -0
  340. package/lib/Utils/use-cache-manager-auth-state.d.ts +22 -0
  341. package/lib/Utils/use-cache-manager-auth-state.js +86 -0
  342. package/lib/Utils/use-multi-file-auth-state.d.ts +20 -0
  343. package/lib/Utils/use-multi-file-auth-state.js +201 -0
  344. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  345. package/lib/Utils/use-single-file-auth-state.js +111 -0
  346. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  347. package/lib/Utils/use-sqlite-auth-state.js +171 -0
  348. package/lib/Utils/username.d.ts +22 -0
  349. package/lib/Utils/username.js +59 -0
  350. package/lib/Utils/validate-connection.d.ts +43 -0
  351. package/lib/Utils/validate-connection.js +197 -0
  352. package/lib/Utils/vcard.d.ts +40 -0
  353. package/lib/Utils/vcard.js +92 -0
  354. package/lib/Utils/voice-note.d.ts +13 -0
  355. package/lib/Utils/voice-note.js +47 -0
  356. package/lib/VoIP/audio-feeder.d.ts +15 -0
  357. package/lib/VoIP/audio-feeder.js +132 -0
  358. package/lib/VoIP/index.d.ts +22 -0
  359. package/lib/VoIP/index.js +277 -0
  360. package/lib/VoIP/relay-transport.d.ts +16 -0
  361. package/lib/VoIP/relay-transport.js +559 -0
  362. package/lib/VoIP/signaling.d.ts +16 -0
  363. package/lib/VoIP/signaling.js +624 -0
  364. package/lib/VoIP/types.d.ts +11 -0
  365. package/lib/VoIP/types.js +17 -0
  366. package/lib/VoIP/wasm-engine.d.ts +28 -0
  367. package/lib/VoIP/wasm-engine.js +1214 -0
  368. package/lib/VoIP/worker-bootstrap.d.ts +1 -0
  369. package/lib/VoIP/worker-bootstrap.js +1042 -0
  370. package/lib/WABinary/constants.d.ts +61 -0
  371. package/lib/WABinary/constants.js +1466 -0
  372. package/lib/WABinary/decode.d.ts +9 -0
  373. package/lib/WABinary/decode.js +261 -0
  374. package/lib/WABinary/encode.d.ts +2 -0
  375. package/lib/WABinary/encode.js +219 -0
  376. package/lib/WABinary/generic-utils.d.ts +45 -0
  377. package/lib/WABinary/generic-utils.js +285 -0
  378. package/lib/WABinary/index.d.ts +5 -0
  379. package/lib/WABinary/index.js +5 -0
  380. package/lib/WABinary/jid-utils.d.ts +32 -0
  381. package/lib/WABinary/jid-utils.js +102 -0
  382. package/lib/WABinary/types.d.ts +1 -0
  383. package/lib/WABinary/types.js +1 -0
  384. package/lib/WAM/BinaryInfo.d.ts +7 -0
  385. package/lib/WAM/BinaryInfo.js +9 -0
  386. package/lib/WAM/constants.d.ts +34926 -0
  387. package/lib/WAM/constants.js +22852 -0
  388. package/lib/WAM/encode.d.ts +1 -0
  389. package/lib/WAM/encode.js +149 -0
  390. package/lib/WAM/index.d.ts +3 -0
  391. package/lib/WAM/index.js +3 -0
  392. package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +43 -0
  393. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +32 -0
  394. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  395. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  396. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  397. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +60 -0
  398. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  399. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  400. package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +13 -0
  401. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +28 -0
  402. package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +22 -0
  403. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  404. package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +20 -0
  405. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +23 -0
  406. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  407. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  408. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +14 -0
  409. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +24 -0
  410. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  411. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  412. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  413. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  414. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  415. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  416. package/lib/WAUSync/Protocols/index.d.ts +12 -0
  417. package/lib/WAUSync/Protocols/index.js +12 -0
  418. package/lib/WAUSync/USyncQuery.d.ts +25 -0
  419. package/lib/WAUSync/USyncQuery.js +140 -0
  420. package/lib/WAUSync/USyncUser.d.ts +24 -0
  421. package/lib/WAUSync/USyncUser.js +47 -0
  422. package/lib/WAUSync/index.d.ts +3 -0
  423. package/lib/WAUSync/index.js +3 -0
  424. package/lib/assets/wasm/loader.js +5 -0
  425. package/lib/assets/wasm/whatsapp.wasm +0 -0
  426. package/lib/assets/wasm/worker-modules.js +273 -0
  427. package/lib/exports-extra.d.ts +45 -0
  428. package/lib/exports-extra.js +47 -0
  429. package/lib/index.d.ts +16 -0
  430. package/lib/index.js +24 -0
  431. package/package.json +161 -4
@@ -0,0 +1,879 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { LabelAssociationType } from '../Types/LabelAssociation.js';
4
+ import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary/index.js';
5
+ import { aesDecrypt, aesEncrypt, hmacSign } from './crypto.js';
6
+ import { toNumber } from './generics.js';
7
+ import { LT_HASH_ANTI_TAMPERING } from './lt-hash.js';
8
+ import { downloadContentFromMessage } from './messages-media.js';
9
+ import { emitSyncActionResults, processContactAction } from './sync-action-utils.js';
10
+ let expandAppStateKeys;
11
+ try {
12
+ ({ expandAppStateKeys } = await import('whatsapp-rust-bridge'));
13
+ }
14
+ catch (err) {
15
+ const message = '`whatsapp-rust-bridge` failed to load (no prebuilt binary for this platform/arch). ' +
16
+ 'App-state sync is unavailable here. Original error: ' + (err?.message || err);
17
+ expandAppStateKeys = () => { throw new Error(message); };
18
+ }
19
+ const mutationKeys = (keydata) => {
20
+ const keys = expandAppStateKeys(keydata);
21
+ return {
22
+ indexKey: keys.indexKey,
23
+ valueEncryptionKey: keys.valueEncryptionKey,
24
+ valueMacKey: keys.valueMacKey,
25
+ snapshotMacKey: keys.snapshotMacKey,
26
+ patchMacKey: keys.patchMacKey
27
+ };
28
+ };
29
+ const generateMac = (operation, data, keyId, key) => {
30
+ const opByte = operation === proto.SyncdMutation.SyncdOperation.SET ? 0x01 : 0x02;
31
+ const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId;
32
+ const keyData = new Uint8Array(1 + keyIdBuffer.length);
33
+ keyData[0] = opByte;
34
+ keyData.set(keyIdBuffer, 1);
35
+ const last = new Uint8Array(8);
36
+ last[7] = keyData.length;
37
+ const total = new Uint8Array(keyData.length + data.length + last.length);
38
+ total.set(keyData, 0);
39
+ total.set(data, keyData.length);
40
+ total.set(last, keyData.length + data.length);
41
+ const hmac = hmacSign(total, key, 'sha512');
42
+ return hmac.subarray(0, 32);
43
+ };
44
+ const to64BitNetworkOrder = (e) => {
45
+ const buff = Buffer.alloc(8);
46
+ buff.writeUint32BE(e, 4);
47
+ return buff;
48
+ };
49
+ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
50
+ indexValueMap = { ...indexValueMap };
51
+ const addBuffs = [];
52
+ const subBuffs = [];
53
+ return {
54
+ mix: ({ indexMac, valueMac, operation }) => {
55
+ const indexMacBase64 = Buffer.from(indexMac).toString('base64');
56
+ const prevOp = indexValueMap[indexMacBase64];
57
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
58
+ if (!prevOp) {
59
+ // WA Web does not throw here — it logs a warning and skips the subtract.
60
+ // The missing REMOVE will cause an LTHash mismatch, which is handled
61
+ // by the MAC validation layer (snapshot recovery or retry).
62
+ return;
63
+ }
64
+ // remove from index value mac, since this mutation is erased
65
+ delete indexValueMap[indexMacBase64];
66
+ }
67
+ else {
68
+ addBuffs.push(valueMac);
69
+ // add this index into the history map
70
+ indexValueMap[indexMacBase64] = { valueMac };
71
+ }
72
+ if (prevOp) {
73
+ subBuffs.push(prevOp.valueMac);
74
+ }
75
+ },
76
+ finish: () => {
77
+ const result = LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs);
78
+ return {
79
+ hash: Buffer.from(result),
80
+ indexValueMap
81
+ };
82
+ }
83
+ };
84
+ };
85
+ const generateSnapshotMac = (lthash, version, name, key) => {
86
+ const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
87
+ return hmacSign(total, key, 'sha256');
88
+ };
89
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
90
+ const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
91
+ return hmacSign(total, key);
92
+ };
93
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
94
+ export const ensureLTHashStateVersion = (state) => {
95
+ if (typeof state.version !== 'number' || isNaN(state.version)) {
96
+ state.version = 0;
97
+ }
98
+ return state;
99
+ };
100
+ export const MAX_SYNC_ATTEMPTS = 2;
101
+ /**
102
+ * Check if an error is a missing app state sync key.
103
+ * WA Web treats these as "Blocked" (waits for key arrival), not fatal.
104
+ * In Baileys we retry with a snapshot which may use a different key.
105
+ */
106
+ export const isMissingKeyError = (error) => {
107
+ return error?.data?.isMissingKey === true;
108
+ };
109
+ /**
110
+ * Determines if an app state sync error is unrecoverable.
111
+ * TypeError indicates a WASM crash; otherwise we give up after MAX_SYNC_ATTEMPTS.
112
+ * Missing keys are NOT checked here — they are handled separately as "Blocked".
113
+ */
114
+ export const isAppStateSyncIrrecoverable = (error, attempts) => {
115
+ return attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError';
116
+ };
117
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
118
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
119
+ if (!key) {
120
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } });
121
+ }
122
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
123
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
124
+ const indexBuffer = Buffer.from(JSON.stringify(index));
125
+ const dataProto = proto.SyncActionData.fromObject({
126
+ index: indexBuffer,
127
+ value: syncAction,
128
+ padding: new Uint8Array(0),
129
+ version: apiVersion
130
+ });
131
+ const encoded = proto.SyncActionData.encode(dataProto).finish();
132
+ const keyValue = mutationKeys(key.keyData);
133
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
134
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
135
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
136
+ // update LT hash
137
+ const generator = makeLtHashGenerator(state);
138
+ generator.mix({ indexMac, valueMac, operation });
139
+ Object.assign(state, generator.finish());
140
+ state.version += 1;
141
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
142
+ const patch = {
143
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
144
+ snapshotMac: snapshotMac,
145
+ keyId: { id: encKeyId },
146
+ mutations: [
147
+ {
148
+ operation: operation,
149
+ record: {
150
+ index: {
151
+ blob: indexMac
152
+ },
153
+ value: {
154
+ blob: Buffer.concat([encValue, valueMac])
155
+ },
156
+ keyId: { id: encKeyId }
157
+ }
158
+ }
159
+ ]
160
+ };
161
+ const base64Index = indexMac.toString('base64');
162
+ state.indexValueMap[base64Index] = { valueMac };
163
+ return { patch, state };
164
+ };
165
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
166
+ const ltGenerator = makeLtHashGenerator(initialState);
167
+ const derivedKeyCache = new Map();
168
+ // indexKey used to HMAC sign record.index.blob
169
+ // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
170
+ // the remaining record.value.blob[0:-32] is the mac, it the HMAC sign of key.keyId + decoded proto data + length of bytes in keyId
171
+ for (const msgMutation of msgMutations) {
172
+ // if it's a syncdmutation, get the operation property
173
+ // otherwise, if it's only a record -- it'll be a SET mutation
174
+ const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
175
+ const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
176
+ let key;
177
+ try {
178
+ key = await getKey(record.keyId.id);
179
+ }
180
+ catch (err) {
181
+ // Missing-key errors must propagate so the orchestrator can park the
182
+ // collection (Blocked) and retry when APP_STATE_SYNC_KEY_SHARE arrives.
183
+ // Other errors → individual record corruption, skip and keep going.
184
+ if (isMissingKeyError(err))
185
+ throw err;
186
+ continue;
187
+ }
188
+ const content = record.value.blob;
189
+ const encContent = content.subarray(0, -32);
190
+ const ogValueMac = content.subarray(-32);
191
+ if (validateMacs) {
192
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
193
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
194
+ // HMAC verification failed — skip this record
195
+ continue;
196
+ }
197
+ }
198
+ let result;
199
+ try {
200
+ result = aesDecrypt(encContent, key.valueEncryptionKey);
201
+ }
202
+ catch {
203
+ // decrypt failed — skip this record instead of aborting
204
+ continue;
205
+ }
206
+ const syncAction = proto.SyncActionData.decode(result);
207
+ if (validateMacs) {
208
+ const hmac = hmacSign(syncAction.index, key.indexKey);
209
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
210
+ throw new Boom('HMAC index verification failed');
211
+ }
212
+ }
213
+ const indexStr = Buffer.from(syncAction.index).toString();
214
+ onMutation({ syncAction, index: JSON.parse(indexStr) });
215
+ ltGenerator.mix({
216
+ indexMac: record.index.blob,
217
+ valueMac: ogValueMac,
218
+ operation: operation
219
+ });
220
+ }
221
+ return ltGenerator.finish();
222
+ async function getKey(keyId) {
223
+ const base64Key = Buffer.from(keyId).toString('base64');
224
+ const cached = derivedKeyCache.get(base64Key);
225
+ if (cached) {
226
+ return cached;
227
+ }
228
+ const keyEnc = await getAppStateSyncKey(base64Key);
229
+ if (!keyEnc) {
230
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
231
+ data: { isMissingKey: true, msgMutations }
232
+ });
233
+ }
234
+ const keys = mutationKeys(keyEnc.keyData);
235
+ derivedKeyCache.set(base64Key, keys);
236
+ return keys;
237
+ }
238
+ };
239
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
240
+ if (validateMacs) {
241
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64');
242
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
243
+ if (!mainKeyObj) {
244
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } });
245
+ }
246
+ const mainKey = mutationKeys(mainKeyObj.keyData);
247
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
248
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey);
249
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
250
+ throw new Boom('Invalid patch mac');
251
+ }
252
+ }
253
+ const result = await decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
254
+ return result;
255
+ };
256
+ export const extractSyncdPatches = async (result, options) => {
257
+ const syncNode = getBinaryNodeChild(result, 'sync');
258
+ const collectionNodes = getBinaryNodeChildren(syncNode, 'collection');
259
+ const final = {};
260
+ await Promise.all(collectionNodes.map(async (collectionNode) => {
261
+ const patchesNode = getBinaryNodeChild(collectionNode, 'patches');
262
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch');
263
+ const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot');
264
+ const syncds = [];
265
+ const name = collectionNode.attrs.name;
266
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
267
+ let snapshot = undefined;
268
+ if (snapshotNode && !!snapshotNode.content) {
269
+ if (!Buffer.isBuffer(snapshotNode)) {
270
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
271
+ }
272
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content);
273
+ const data = await downloadExternalBlob(blobRef, options);
274
+ snapshot = proto.SyncdSnapshot.decode(data);
275
+ }
276
+ for (let { content } of patches) {
277
+ if (content) {
278
+ if (!Buffer.isBuffer(content)) {
279
+ content = Buffer.from(Object.values(content));
280
+ }
281
+ const syncd = proto.SyncdPatch.decode(content);
282
+ if (!syncd.version) {
283
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
284
+ }
285
+ syncds.push(syncd);
286
+ }
287
+ }
288
+ final[name] = { patches: syncds, hasMorePatches, snapshot };
289
+ }));
290
+ return final;
291
+ };
292
+ export const downloadExternalBlob = async (blob, options) => {
293
+ const stream = await downloadContentFromMessage(blob, 'md-app-state', { options });
294
+ const bufferArray = [];
295
+ for await (const chunk of stream) {
296
+ bufferArray.push(chunk);
297
+ }
298
+ return Buffer.concat(bufferArray);
299
+ };
300
+ export const downloadExternalPatch = async (blob, options) => {
301
+ const buffer = await downloadExternalBlob(blob, options);
302
+ const syncData = proto.SyncdMutations.decode(buffer);
303
+ return syncData;
304
+ };
305
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
306
+ const newState = newLTHashState();
307
+ newState.version = toNumber(snapshot.version.version);
308
+ const mutationMap = {};
309
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
310
+ const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
311
+ ? mutation => {
312
+ const index = mutation.syncAction.index?.toString();
313
+ mutationMap[index] = mutation;
314
+ }
315
+ : () => { }, validateMacs);
316
+ newState.hash = hash;
317
+ newState.indexValueMap = indexValueMap;
318
+ if (validateMacs) {
319
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
320
+ const keyEnc = await getAppStateSyncKey(base64Key);
321
+ if (!keyEnc) {
322
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
323
+ }
324
+ const result = mutationKeys(keyEnc.keyData);
325
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
326
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
327
+ // LTHash verification may fail when decodeSyncdMutations skipped undecryptable
328
+ // records (poisoned server-side snapshot); the aggregate client hash diverges
329
+ // from the server-computed mac. Fall through with a warning so the session stays
330
+ // alive with partial state, symmetric to how decodePatches handles its own
331
+ // LTHash mismatch a few lines below.
332
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state');
333
+ }
334
+ }
335
+ return {
336
+ state: newState,
337
+ mutationMap
338
+ };
339
+ };
340
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
341
+ const newState = {
342
+ ...initial,
343
+ indexValueMap: { ...initial.indexValueMap }
344
+ };
345
+ const mutationMap = {};
346
+ for (const syncd of syncds) {
347
+ const { version, keyId, snapshotMac } = syncd;
348
+ if (syncd.externalMutations) {
349
+ logger?.trace({ name, version }, 'downloading external patch');
350
+ const ref = await downloadExternalPatch(syncd.externalMutations, options);
351
+ logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
352
+ syncd.mutations?.push(...ref.mutations);
353
+ }
354
+ const patchVersion = toNumber(version.version);
355
+ newState.version = patchVersion;
356
+ const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
357
+ let decodeResult;
358
+ try {
359
+ decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
360
+ ? mutation => {
361
+ const index = mutation.syncAction.index?.toString();
362
+ mutationMap[index] = mutation;
363
+ }
364
+ : () => { }, validateMacs);
365
+ }
366
+ catch (err) {
367
+ if (isMissingKeyError(err))
368
+ throw err;
369
+ logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping');
370
+ continue;
371
+ }
372
+ newState.hash = decodeResult.hash;
373
+ newState.indexValueMap = decodeResult.indexValueMap;
374
+ if (validateMacs) {
375
+ const base64Key = Buffer.from(keyId.id).toString('base64');
376
+ const keyEnc = await getAppStateSyncKey(base64Key);
377
+ if (!keyEnc) {
378
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
379
+ }
380
+ const result = mutationKeys(keyEnc.keyData);
381
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
382
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
383
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches');
384
+ break;
385
+ }
386
+ }
387
+ // clear memory used up by the mutations
388
+ syncd.mutations = [];
389
+ }
390
+ return { state: newState, mutationMap };
391
+ };
392
+ export const chatModificationToAppPatch = (mod, jid) => {
393
+ const OP = proto.SyncdMutation.SyncdOperation;
394
+ const getMessageRange = (lastMessages) => {
395
+ let messageRange;
396
+ if (Array.isArray(lastMessages)) {
397
+ const lastMsg = lastMessages[lastMessages.length - 1];
398
+ messageRange = {
399
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
400
+ messages: lastMessages?.length
401
+ ? lastMessages.map(m => {
402
+ if (!m.key?.id || !m.key?.remoteJid) {
403
+ throw new Boom('Incomplete key', { statusCode: 400, data: m });
404
+ }
405
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
406
+ throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
407
+ }
408
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
409
+ throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
410
+ }
411
+ if (m.key.participant) {
412
+ m.key.participant = jidNormalizedUser(m.key.participant);
413
+ }
414
+ return m;
415
+ })
416
+ : undefined
417
+ };
418
+ }
419
+ else {
420
+ messageRange = lastMessages;
421
+ }
422
+ return messageRange;
423
+ };
424
+ let patch;
425
+ if ('mute' in mod) {
426
+ patch = {
427
+ syncAction: {
428
+ muteAction: {
429
+ muted: !!mod.mute,
430
+ muteEndTimestamp: mod.mute || undefined
431
+ }
432
+ },
433
+ index: ['mute', jid],
434
+ type: 'regular_high',
435
+ apiVersion: 2,
436
+ operation: OP.SET
437
+ };
438
+ }
439
+ else if ('archive' in mod) {
440
+ patch = {
441
+ syncAction: {
442
+ archiveChatAction: {
443
+ archived: !!mod.archive,
444
+ messageRange: getMessageRange(mod.lastMessages)
445
+ }
446
+ },
447
+ index: ['archive', jid],
448
+ type: 'regular_low',
449
+ apiVersion: 3,
450
+ operation: OP.SET
451
+ };
452
+ }
453
+ else if ('markRead' in mod) {
454
+ patch = {
455
+ syncAction: {
456
+ markChatAsReadAction: {
457
+ read: mod.markRead,
458
+ messageRange: getMessageRange(mod.lastMessages)
459
+ }
460
+ },
461
+ index: ['markChatAsRead', jid],
462
+ type: 'regular_low',
463
+ apiVersion: 3,
464
+ operation: OP.SET
465
+ };
466
+ }
467
+ else if ('deleteForMe' in mod) {
468
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
469
+ patch = {
470
+ syncAction: {
471
+ deleteMessageForMeAction: {
472
+ deleteMedia,
473
+ messageTimestamp: timestamp
474
+ }
475
+ },
476
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
477
+ type: 'regular_high',
478
+ apiVersion: 3,
479
+ operation: OP.SET
480
+ };
481
+ }
482
+ else if ('clear' in mod) {
483
+ patch = {
484
+ syncAction: {
485
+ clearChatAction: {
486
+ messageRange: getMessageRange(mod.lastMessages)
487
+ }
488
+ },
489
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
490
+ type: 'regular_high',
491
+ apiVersion: 6,
492
+ operation: OP.SET
493
+ };
494
+ }
495
+ else if ('pin' in mod) {
496
+ patch = {
497
+ syncAction: {
498
+ pinAction: {
499
+ pinned: !!mod.pin
500
+ }
501
+ },
502
+ index: ['pin_v1', jid],
503
+ type: 'regular_low',
504
+ apiVersion: 5,
505
+ operation: OP.SET
506
+ };
507
+ }
508
+ else if ('contact' in mod) {
509
+ patch = {
510
+ syncAction: {
511
+ contactAction: mod.contact || {}
512
+ },
513
+ index: ['contact', jid],
514
+ type: 'critical_unblock_low',
515
+ apiVersion: 2,
516
+ operation: mod.contact ? OP.SET : OP.REMOVE
517
+ };
518
+ }
519
+ else if ('disableLinkPreviews' in mod) {
520
+ patch = {
521
+ syncAction: {
522
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
523
+ },
524
+ index: ['setting_disableLinkPreviews'],
525
+ type: 'regular',
526
+ apiVersion: 8,
527
+ operation: OP.SET
528
+ };
529
+ }
530
+ else if ('star' in mod) {
531
+ const key = mod.star.messages[0];
532
+ patch = {
533
+ syncAction: {
534
+ starAction: {
535
+ starred: !!mod.star.star
536
+ }
537
+ },
538
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
539
+ type: 'regular_low',
540
+ apiVersion: 2,
541
+ operation: OP.SET
542
+ };
543
+ }
544
+ else if ('delete' in mod) {
545
+ patch = {
546
+ syncAction: {
547
+ deleteChatAction: {
548
+ messageRange: getMessageRange(mod.lastMessages)
549
+ }
550
+ },
551
+ index: ['deleteChat', jid, '1'],
552
+ type: 'regular_high',
553
+ apiVersion: 6,
554
+ operation: OP.SET
555
+ };
556
+ }
557
+ else if ('pushNameSetting' in mod) {
558
+ patch = {
559
+ syncAction: {
560
+ pushNameSetting: {
561
+ name: mod.pushNameSetting
562
+ }
563
+ },
564
+ index: ['setting_pushName'],
565
+ type: 'critical_block',
566
+ apiVersion: 1,
567
+ operation: OP.SET
568
+ };
569
+ }
570
+ else if ('quickReply' in mod) {
571
+ patch = {
572
+ syncAction: {
573
+ quickReplyAction: {
574
+ count: 0,
575
+ deleted: mod.quickReply.deleted || false,
576
+ keywords: [],
577
+ message: mod.quickReply.message || '',
578
+ shortcut: mod.quickReply.shortcut || ''
579
+ }
580
+ },
581
+ index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
582
+ type: 'regular',
583
+ apiVersion: 2,
584
+ operation: OP.SET
585
+ };
586
+ }
587
+ else if ('addLabel' in mod) {
588
+ patch = {
589
+ syncAction: {
590
+ labelEditAction: {
591
+ name: mod.addLabel.name,
592
+ color: mod.addLabel.color,
593
+ predefinedId: mod.addLabel.predefinedId,
594
+ deleted: mod.addLabel.deleted
595
+ }
596
+ },
597
+ index: ['label_edit', mod.addLabel.id],
598
+ type: 'regular',
599
+ apiVersion: 3,
600
+ operation: OP.SET
601
+ };
602
+ }
603
+ else if ('addChatLabel' in mod) {
604
+ patch = {
605
+ syncAction: {
606
+ labelAssociationAction: {
607
+ labeled: true
608
+ }
609
+ },
610
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
611
+ type: 'regular',
612
+ apiVersion: 3,
613
+ operation: OP.SET
614
+ };
615
+ }
616
+ else if ('removeChatLabel' in mod) {
617
+ patch = {
618
+ syncAction: {
619
+ labelAssociationAction: {
620
+ labeled: false
621
+ }
622
+ },
623
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
624
+ type: 'regular',
625
+ apiVersion: 3,
626
+ operation: OP.SET
627
+ };
628
+ }
629
+ else if ('addMessageLabel' in mod) {
630
+ patch = {
631
+ syncAction: {
632
+ labelAssociationAction: {
633
+ labeled: true
634
+ }
635
+ },
636
+ index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
637
+ type: 'regular',
638
+ apiVersion: 3,
639
+ operation: OP.SET
640
+ };
641
+ }
642
+ else if ('removeMessageLabel' in mod) {
643
+ patch = {
644
+ syncAction: {
645
+ labelAssociationAction: {
646
+ labeled: false
647
+ }
648
+ },
649
+ index: [
650
+ LabelAssociationType.Message,
651
+ mod.removeMessageLabel.labelId,
652
+ jid,
653
+ mod.removeMessageLabel.messageId,
654
+ '0',
655
+ '0'
656
+ ],
657
+ type: 'regular',
658
+ apiVersion: 3,
659
+ operation: OP.SET
660
+ };
661
+ }
662
+ else {
663
+ throw new Boom('not supported');
664
+ }
665
+ patch.syncAction.timestamp = Date.now();
666
+ return patch;
667
+ };
668
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
669
+ const isInitialSync = !!initialSyncOpts;
670
+ const accountSettings = initialSyncOpts?.accountSettings;
671
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
672
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
673
+ if (action?.muteAction) {
674
+ ev.emit('chats.update', [
675
+ {
676
+ id,
677
+ muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
678
+ conditional: getChatUpdateConditional(id, undefined)
679
+ }
680
+ ]);
681
+ }
682
+ else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
683
+ // okay so we've to do some annoying computation here
684
+ // when we're initially syncing the app state
685
+ // there are a few cases we need to handle
686
+ // 1. if the account unarchiveChats setting is true
687
+ // a. if the chat is archived, and no further messages have been received -- simple, keep archived
688
+ // b. if the chat was archived, and the user received messages from the other person afterwards
689
+ // then the chat should be marked unarchved --
690
+ // we compare the timestamp of latest message from the other person to determine this
691
+ // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
692
+ // it'll always take an app state action to mark in unarchived -- which we'll get anyway
693
+ const archiveAction = action?.archiveChatAction;
694
+ const isArchived = archiveAction ? archiveAction.archived : type === 'archive';
695
+ // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
696
+ // // this only applies for the initial sync
697
+ // if(isInitialSync && !isArchived) {
698
+ // isArchived = false
699
+ // }
700
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
701
+ // logger?.debug({ chat: id, syncAction }, 'message range archive')
702
+ ev.emit('chats.update', [
703
+ {
704
+ id,
705
+ archived: isArchived,
706
+ conditional: getChatUpdateConditional(id, msgRange)
707
+ }
708
+ ]);
709
+ }
710
+ else if (action?.markChatAsReadAction) {
711
+ const markReadAction = action.markChatAsReadAction;
712
+ // basically we don't need to fire an "read" update if the chat is being marked as read
713
+ // because the chat is read by default
714
+ // this only applies for the initial sync
715
+ const isNullUpdate = isInitialSync && markReadAction.read;
716
+ ev.emit('chats.update', [
717
+ {
718
+ id,
719
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
720
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
721
+ }
722
+ ]);
723
+ }
724
+ else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
725
+ ev.emit('messages.delete', {
726
+ keys: [
727
+ {
728
+ remoteJid: id,
729
+ id: msgId,
730
+ fromMe: fromMe === '1'
731
+ }
732
+ ]
733
+ });
734
+ }
735
+ else if (action?.contactAction) {
736
+ const results = processContactAction(action.contactAction, id, logger);
737
+ emitSyncActionResults(ev, results);
738
+ }
739
+ else if (action?.pushNameSetting) {
740
+ const name = action?.pushNameSetting?.name;
741
+ if (name && me?.name !== name) {
742
+ ev.emit('creds.update', { me: { ...me, name } });
743
+ }
744
+ }
745
+ else if (action?.pinAction) {
746
+ ev.emit('chats.update', [
747
+ {
748
+ id,
749
+ pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
750
+ conditional: getChatUpdateConditional(id, undefined)
751
+ }
752
+ ]);
753
+ }
754
+ else if (action?.unarchiveChatsSetting) {
755
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
756
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } });
757
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
758
+ if (accountSettings) {
759
+ accountSettings.unarchiveChats = unarchiveChats;
760
+ }
761
+ }
762
+ else if (action?.starAction || type === 'star') {
763
+ let starred = action?.starAction?.starred;
764
+ if (typeof starred !== 'boolean') {
765
+ starred = syncAction.index[syncAction.index.length - 1] === '1';
766
+ }
767
+ ev.emit('messages.update', [
768
+ {
769
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
770
+ update: { starred }
771
+ }
772
+ ]);
773
+ }
774
+ else if (action?.deleteChatAction || type === 'deleteChat') {
775
+ if (!isInitialSync) {
776
+ ev.emit('chats.delete', [id]);
777
+ }
778
+ }
779
+ else if (action?.labelEditAction) {
780
+ const { name, color, deleted, predefinedId } = action.labelEditAction;
781
+ ev.emit('labels.edit', {
782
+ id: id,
783
+ name: name,
784
+ color: color,
785
+ deleted: deleted,
786
+ predefinedId: predefinedId ? String(predefinedId) : undefined
787
+ });
788
+ }
789
+ else if (action?.labelAssociationAction) {
790
+ ev.emit('labels.association', {
791
+ type: action.labelAssociationAction.labeled ? 'add' : 'remove',
792
+ association: type === LabelAssociationType.Chat
793
+ ? {
794
+ type: LabelAssociationType.Chat,
795
+ chatId: syncAction.index[2],
796
+ labelId: syncAction.index[1]
797
+ }
798
+ : {
799
+ type: LabelAssociationType.Message,
800
+ chatId: syncAction.index[2],
801
+ messageId: syncAction.index[3],
802
+ labelId: syncAction.index[1]
803
+ }
804
+ });
805
+ }
806
+ else if (action?.localeSetting?.locale) {
807
+ ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale });
808
+ }
809
+ else if (action?.timeFormatAction) {
810
+ ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction });
811
+ }
812
+ else if (action?.pnForLidChatAction) {
813
+ if (action.pnForLidChatAction.pnJid) {
814
+ ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid });
815
+ }
816
+ }
817
+ else if (action?.privacySettingRelayAllCalls) {
818
+ ev.emit('settings.update', {
819
+ setting: 'privacySettingRelayAllCalls',
820
+ value: action.privacySettingRelayAllCalls
821
+ });
822
+ }
823
+ else if (action?.statusPrivacy) {
824
+ ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy });
825
+ }
826
+ else if (action?.lockChatAction) {
827
+ ev.emit('chats.lock', { id: id, locked: !!action.lockChatAction.locked });
828
+ }
829
+ else if (action?.privacySettingDisableLinkPreviewsAction) {
830
+ ev.emit('settings.update', {
831
+ setting: 'disableLinkPreviews',
832
+ value: action.privacySettingDisableLinkPreviewsAction
833
+ });
834
+ }
835
+ else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
836
+ ev.emit('settings.update', {
837
+ setting: 'notificationActivitySetting',
838
+ value: action.notificationActivitySettingAction.notificationActivitySetting
839
+ });
840
+ }
841
+ else if (action?.lidContactAction) {
842
+ ev.emit('contacts.upsert', [
843
+ {
844
+ id: id,
845
+ name: action.lidContactAction.fullName ||
846
+ action.lidContactAction.firstName ||
847
+ action.lidContactAction.username ||
848
+ undefined,
849
+ username: action.lidContactAction.username || undefined,
850
+ lid: id,
851
+ phoneNumber: undefined
852
+ }
853
+ ]);
854
+ }
855
+ else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
856
+ ev.emit('settings.update', {
857
+ setting: 'channelsPersonalisedRecommendation',
858
+ value: action.privacySettingChannelsPersonalisedRecommendationAction
859
+ });
860
+ }
861
+ else {
862
+ logger?.debug({ syncAction, id }, 'unprocessable update');
863
+ }
864
+ function getChatUpdateConditional(id, msgRange) {
865
+ return isInitialSync
866
+ ? data => {
867
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
868
+ if (chat) {
869
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
870
+ }
871
+ }
872
+ : undefined;
873
+ }
874
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
875
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
876
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
877
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
878
+ }
879
+ };