zapo-js 0.1.1 → 0.2.0

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 (589) hide show
  1. package/README.md +20 -4
  2. package/dist/appstate/WaAppStateCrypto.js +19 -26
  3. package/dist/appstate/WaAppStateSyncClient.js +293 -181
  4. package/dist/appstate/WaAppStateSyncResponseParser.js +16 -5
  5. package/dist/appstate/constants.js +4 -3
  6. package/dist/appstate/{store/sqlite.js → encoding.js} +13 -8
  7. package/dist/appstate/index.js +8 -6
  8. package/dist/appstate/utils.js +9 -34
  9. package/dist/auth/WaAuthClient.js +43 -61
  10. package/dist/auth/flow/WaAuthCredentialsFlow.js +22 -15
  11. package/dist/auth/index.js +1 -8
  12. package/dist/auth/pairing/WaPairingCodeCrypto.js +6 -4
  13. package/dist/auth/pairing/WaPairingFlow.js +34 -26
  14. package/dist/auth/pairing/WaQrFlow.js +37 -24
  15. package/dist/client/WaClient.js +275 -324
  16. package/dist/client/WaClientFactory.js +500 -133
  17. package/dist/client/connection/WaConnectionManager.js +301 -0
  18. package/dist/client/connection/WaKeyShareCoordinator.js +63 -0
  19. package/dist/client/connection/WaReceiptQueue.js +51 -0
  20. package/dist/client/coordinators/WaAppStateMutationCoordinator.js +471 -0
  21. package/dist/client/coordinators/WaBusinessCoordinator.js +241 -0
  22. package/dist/client/coordinators/WaGroupCoordinator.js +30 -16
  23. package/dist/client/coordinators/WaIncomingNodeCoordinator.js +21 -27
  24. package/dist/client/coordinators/WaMessageDispatchCoordinator.js +439 -701
  25. package/dist/client/coordinators/WaPassiveTasksCoordinator.js +74 -31
  26. package/dist/client/coordinators/WaPrivacyCoordinator.js +134 -0
  27. package/dist/client/coordinators/WaProfileCoordinator.js +212 -0
  28. package/dist/client/coordinators/WaRetryCoordinator.js +242 -57
  29. package/dist/client/coordinators/WaStreamControlCoordinator.js +18 -11
  30. package/dist/client/coordinators/WaTrustedContactTokenCoordinator.js +166 -0
  31. package/dist/client/dirty.js +74 -48
  32. package/dist/client/events/chat.js +4 -3
  33. package/dist/client/events/devices.js +72 -0
  34. package/dist/client/events/group.js +62 -47
  35. package/dist/client/events/identity.js +22 -0
  36. package/dist/client/events/privacy-token.js +39 -0
  37. package/dist/client/history-sync.js +94 -63
  38. package/dist/client/incoming.js +60 -27
  39. package/dist/client/mailbox.js +24 -23
  40. package/dist/client/messages.js +107 -31
  41. package/dist/client/messaging/fanout.js +199 -0
  42. package/dist/client/messaging/key-protocol.js +130 -0
  43. package/dist/client/messaging/participants.js +193 -0
  44. package/dist/client/persistence/WriteBehindPersistence.js +129 -0
  45. package/dist/client/tokens/cs-token.js +50 -0
  46. package/dist/client/tokens/tc-token.js +25 -0
  47. package/dist/crypto/core/hkdf.js +3 -8
  48. package/dist/crypto/core/index.js +2 -5
  49. package/dist/crypto/core/keys.js +6 -7
  50. package/dist/crypto/core/nonce.js +2 -0
  51. package/dist/crypto/core/primitives.js +12 -23
  52. package/dist/crypto/core/random.js +26 -23
  53. package/dist/crypto/curves/Ed25519.js +7 -8
  54. package/dist/crypto/curves/X25519.js +38 -22
  55. package/dist/crypto/index.js +1 -3
  56. package/dist/crypto/math/constants.js +13 -36
  57. package/dist/crypto/math/edwards.js +171 -44
  58. package/dist/crypto/math/fe.js +706 -0
  59. package/dist/crypto/math/mod.js +10 -3
  60. package/dist/esm/appstate/WaAppStateCrypto.js +7 -14
  61. package/dist/esm/appstate/WaAppStateSyncClient.js +284 -172
  62. package/dist/esm/appstate/WaAppStateSyncResponseParser.js +17 -6
  63. package/dist/esm/appstate/constants.js +3 -2
  64. package/dist/esm/appstate/{store/sqlite.js → encoding.js} +13 -8
  65. package/dist/esm/appstate/index.js +2 -2
  66. package/dist/esm/appstate/utils.js +8 -30
  67. package/dist/esm/auth/WaAuthClient.js +43 -61
  68. package/dist/esm/auth/flow/WaAuthCredentialsFlow.js +22 -15
  69. package/dist/esm/auth/index.js +0 -3
  70. package/dist/esm/auth/pairing/WaPairingCodeCrypto.js +6 -4
  71. package/dist/esm/auth/pairing/WaPairingFlow.js +28 -20
  72. package/dist/esm/auth/pairing/WaQrFlow.js +37 -24
  73. package/dist/esm/client/WaClient.js +275 -324
  74. package/dist/esm/client/WaClientFactory.js +501 -134
  75. package/dist/esm/client/connection/WaConnectionManager.js +297 -0
  76. package/dist/esm/client/connection/WaKeyShareCoordinator.js +59 -0
  77. package/dist/esm/client/connection/WaReceiptQueue.js +47 -0
  78. package/dist/esm/client/coordinators/WaAppStateMutationCoordinator.js +467 -0
  79. package/dist/esm/client/coordinators/WaBusinessCoordinator.js +238 -0
  80. package/dist/esm/client/coordinators/WaGroupCoordinator.js +23 -9
  81. package/dist/esm/client/coordinators/WaIncomingNodeCoordinator.js +21 -27
  82. package/dist/esm/client/coordinators/WaMessageDispatchCoordinator.js +443 -705
  83. package/dist/esm/client/coordinators/WaPassiveTasksCoordinator.js +74 -31
  84. package/dist/esm/client/coordinators/WaPrivacyCoordinator.js +131 -0
  85. package/dist/esm/client/coordinators/WaProfileCoordinator.js +209 -0
  86. package/dist/esm/client/coordinators/WaRetryCoordinator.js +244 -59
  87. package/dist/esm/client/coordinators/WaStreamControlCoordinator.js +19 -12
  88. package/dist/esm/client/coordinators/WaTrustedContactTokenCoordinator.js +162 -0
  89. package/dist/esm/client/dirty.js +69 -43
  90. package/dist/esm/client/events/chat.js +4 -3
  91. package/dist/esm/client/events/devices.js +68 -0
  92. package/dist/esm/client/events/group.js +53 -39
  93. package/dist/esm/client/events/identity.js +19 -0
  94. package/dist/esm/client/events/privacy-token.js +36 -0
  95. package/dist/esm/client/history-sync.js +91 -60
  96. package/dist/esm/client/incoming.js +61 -28
  97. package/dist/esm/client/mailbox.js +24 -23
  98. package/dist/esm/client/messages.js +108 -32
  99. package/dist/esm/client/messaging/fanout.js +196 -0
  100. package/dist/esm/client/messaging/key-protocol.js +127 -0
  101. package/dist/esm/client/messaging/participants.js +190 -0
  102. package/dist/esm/client/persistence/WriteBehindPersistence.js +125 -0
  103. package/dist/esm/client/tokens/cs-token.js +46 -0
  104. package/dist/esm/client/tokens/tc-token.js +18 -0
  105. package/dist/esm/crypto/core/hkdf.js +3 -8
  106. package/dist/esm/crypto/core/index.js +2 -3
  107. package/dist/esm/crypto/core/keys.js +3 -4
  108. package/dist/esm/crypto/core/nonce.js +2 -0
  109. package/dist/esm/crypto/core/primitives.js +12 -22
  110. package/dist/esm/crypto/core/random.js +25 -23
  111. package/dist/esm/crypto/curves/Ed25519.js +4 -5
  112. package/dist/esm/crypto/curves/X25519.js +35 -19
  113. package/dist/esm/crypto/index.js +0 -1
  114. package/dist/esm/crypto/math/constants.js +12 -35
  115. package/dist/esm/crypto/math/edwards.js +174 -47
  116. package/dist/esm/crypto/math/fe.js +691 -0
  117. package/dist/esm/crypto/math/mod.js +10 -1
  118. package/dist/esm/index.js +1 -1
  119. package/dist/esm/infra/log/ConsoleLogger.js +18 -17
  120. package/dist/esm/infra/log/PinoLogger.js +15 -9
  121. package/dist/esm/infra/log/types.js +11 -1
  122. package/dist/esm/infra/perf/BackgroundQueue.js +478 -0
  123. package/dist/esm/infra/perf/BoundedTaskQueue.js +16 -18
  124. package/dist/esm/infra/perf/PromiseDedup.js +20 -0
  125. package/dist/esm/infra/perf/SharedExclusiveGate.js +109 -0
  126. package/dist/esm/infra/perf/StoreLock.js +77 -0
  127. package/dist/esm/media/WaMediaCrypto.js +96 -16
  128. package/dist/esm/media/WaMediaTransferClient.js +251 -91
  129. package/dist/esm/media/conn.js +10 -6
  130. package/dist/esm/media/constants.js +6 -2
  131. package/dist/esm/message/WaMessageClient.js +30 -32
  132. package/dist/esm/message/ack.js +6 -6
  133. package/dist/esm/message/addon-crypto.js +59 -0
  134. package/dist/esm/message/content.js +195 -9
  135. package/dist/esm/message/icdc.js +76 -0
  136. package/dist/esm/message/incoming.js +129 -122
  137. package/dist/esm/message/index.js +2 -0
  138. package/dist/esm/message/phash.js +3 -1
  139. package/dist/esm/message/reporting-token.js +425 -0
  140. package/dist/esm/message/use-case-secret.js +49 -0
  141. package/dist/esm/protocol/appstate.js +27 -0
  142. package/dist/esm/protocol/browser.js +10 -18
  143. package/dist/esm/protocol/constants.js +6 -3
  144. package/dist/esm/protocol/defaults.js +6 -0
  145. package/dist/esm/protocol/index.js +2 -11
  146. package/dist/esm/protocol/jid.js +133 -52
  147. package/dist/esm/protocol/media.js +3 -3
  148. package/dist/esm/protocol/message.js +61 -1
  149. package/dist/esm/protocol/nodes.js +4 -0
  150. package/dist/esm/protocol/notification.js +3 -1
  151. package/dist/esm/protocol/privacy-token.js +17 -0
  152. package/dist/esm/protocol/privacy.js +55 -0
  153. package/dist/esm/protocol/stream.js +26 -1
  154. package/dist/esm/protocol/usync.js +11 -0
  155. package/dist/esm/retry/codec.js +216 -0
  156. package/dist/esm/retry/constants.js +1 -1
  157. package/dist/esm/retry/index.js +3 -2
  158. package/dist/esm/retry/parse.js +88 -86
  159. package/dist/esm/retry/replay.js +54 -51
  160. package/dist/esm/retry/tracker.js +94 -0
  161. package/dist/esm/signal/api/SignalDeviceSyncApi.js +276 -92
  162. package/dist/esm/signal/api/SignalDigestSyncApi.js +17 -8
  163. package/dist/esm/signal/api/SignalIdentitySyncApi.js +67 -37
  164. package/dist/esm/signal/api/SignalMissingPreKeysSyncApi.js +86 -67
  165. package/dist/esm/signal/api/SignalRotateKeyApi.js +4 -2
  166. package/dist/esm/signal/api/SignalSessionSyncApi.js +36 -34
  167. package/dist/esm/signal/api/result-map.js +10 -0
  168. package/dist/esm/signal/constants.js +0 -4
  169. package/dist/esm/signal/crypto/WaAdvSignature.js +13 -9
  170. package/dist/esm/signal/{store/sqlite.js → encoding.js} +93 -60
  171. package/dist/esm/signal/group/SenderKeyChain.js +28 -23
  172. package/dist/esm/signal/group/SenderKeyCodec.js +5 -6
  173. package/dist/esm/signal/group/SenderKeyManager.js +144 -115
  174. package/dist/esm/signal/index.js +2 -0
  175. package/dist/esm/signal/registration/keygen.js +6 -2
  176. package/dist/esm/signal/registration/utils.js +1 -0
  177. package/dist/esm/signal/session/SignalProtocol.js +164 -53
  178. package/dist/esm/signal/session/SignalRatchet.js +24 -15
  179. package/dist/esm/signal/session/SignalSession.js +14 -9
  180. package/dist/esm/signal/session/resolver.js +221 -0
  181. package/dist/esm/store/contracts/privacy-token.store.js +1 -0
  182. package/dist/esm/store/createStore.js +100 -188
  183. package/dist/esm/store/index.js +1 -10
  184. package/dist/esm/store/locks/appstate.lock.js +26 -0
  185. package/dist/esm/store/locks/auth.lock.js +15 -0
  186. package/dist/esm/store/locks/contact.lock.js +20 -0
  187. package/dist/esm/store/locks/device-list.lock.js +20 -0
  188. package/dist/esm/store/locks/message.lock.js +21 -0
  189. package/dist/esm/store/locks/participants.lock.js +20 -0
  190. package/dist/esm/store/locks/privacy-token.lock.js +18 -0
  191. package/dist/esm/store/locks/retry.lock.js +29 -0
  192. package/dist/esm/store/locks/sender-key.lock.js +52 -0
  193. package/dist/esm/store/locks/signal.lock.js +63 -0
  194. package/dist/esm/store/locks/thread.lock.js +21 -0
  195. package/dist/esm/store/noop.store.js +4 -7
  196. package/dist/esm/store/providers/memory/appstate.store.js +38 -16
  197. package/dist/esm/store/providers/memory/contact.store.js +5 -0
  198. package/dist/esm/store/providers/memory/device-list.store.js +12 -34
  199. package/dist/esm/store/providers/memory/message.store.js +11 -5
  200. package/dist/esm/store/providers/memory/participants.store.js +1 -8
  201. package/dist/esm/store/providers/memory/privacy-token.store.js +43 -0
  202. package/dist/esm/store/providers/memory/retry.store.js +77 -2
  203. package/dist/esm/store/providers/memory/sender-key.store.js +11 -8
  204. package/dist/esm/store/providers/memory/signal.store.js +47 -18
  205. package/dist/esm/store/providers/memory/thread.store.js +5 -0
  206. package/dist/esm/transport/WaComms.js +28 -24
  207. package/dist/esm/transport/WaWebSocket.js +115 -18
  208. package/dist/esm/transport/binary/constants.js +0 -30
  209. package/dist/esm/transport/binary/decoder.js +8 -8
  210. package/dist/esm/transport/binary/encoder.js +10 -9
  211. package/dist/esm/transport/binary/index.js +0 -1
  212. package/dist/esm/transport/index.js +1 -0
  213. package/dist/esm/transport/keepalive/WaKeepAlive.js +2 -8
  214. package/dist/esm/transport/node/WaNodeOrchestrator.js +25 -21
  215. package/dist/esm/transport/node/WaNodeTransport.js +0 -3
  216. package/dist/esm/transport/node/builders/{accountSync.js → account-sync.js} +16 -36
  217. package/dist/esm/transport/node/builders/business.js +129 -0
  218. package/dist/esm/transport/node/builders/global.js +370 -0
  219. package/dist/esm/transport/node/builders/index.js +7 -3
  220. package/dist/esm/transport/node/builders/message.js +63 -230
  221. package/dist/esm/transport/node/builders/pairing.js +2 -27
  222. package/dist/esm/transport/node/builders/privacy-token.js +41 -0
  223. package/dist/esm/transport/node/builders/privacy.js +48 -0
  224. package/dist/esm/transport/node/builders/profile.js +70 -0
  225. package/dist/esm/transport/node/builders/retry.js +10 -22
  226. package/dist/esm/transport/node/builders/usync.js +45 -0
  227. package/dist/esm/transport/node/helpers.js +125 -5
  228. package/dist/esm/transport/node/usync.js +5 -0
  229. package/dist/esm/transport/node/xml.js +35 -14
  230. package/dist/esm/transport/noise/WaClientPayload.js +10 -10
  231. package/dist/esm/transport/noise/WaFrameCodec.js +48 -33
  232. package/dist/esm/transport/noise/WaNoiseCert.js +4 -7
  233. package/dist/esm/transport/noise/WaNoiseSession.js +77 -29
  234. package/dist/esm/transport/noise/WaNoiseSocket.js +8 -4
  235. package/dist/esm/transport/proxy.js +27 -0
  236. package/dist/esm/transport/stream/parse.js +17 -48
  237. package/dist/esm/util/bytes.js +67 -45
  238. package/dist/esm/util/coercion.js +6 -14
  239. package/dist/esm/util/index.js +5 -0
  240. package/dist/esm/util/primitives.js +40 -14
  241. package/dist/index.js +7 -1
  242. package/dist/infra/log/ConsoleLogger.js +18 -17
  243. package/dist/infra/log/PinoLogger.js +15 -9
  244. package/dist/infra/log/types.js +12 -0
  245. package/dist/infra/perf/BackgroundQueue.js +482 -0
  246. package/dist/infra/perf/BoundedTaskQueue.js +16 -18
  247. package/dist/infra/perf/PromiseDedup.js +24 -0
  248. package/dist/infra/perf/SharedExclusiveGate.js +113 -0
  249. package/dist/infra/perf/StoreLock.js +81 -0
  250. package/dist/media/WaMediaCrypto.js +95 -15
  251. package/dist/media/WaMediaTransferClient.js +284 -91
  252. package/dist/media/conn.js +10 -6
  253. package/dist/media/constants.js +6 -2
  254. package/dist/message/WaMessageClient.js +31 -33
  255. package/dist/message/ack.js +6 -6
  256. package/dist/message/addon-crypto.js +65 -0
  257. package/dist/message/content.js +198 -9
  258. package/dist/message/icdc.js +81 -0
  259. package/dist/message/incoming.js +127 -120
  260. package/dist/message/index.js +2 -0
  261. package/dist/message/phash.js +3 -1
  262. package/dist/message/reporting-token.js +429 -0
  263. package/dist/message/use-case-secret.js +55 -0
  264. package/dist/protocol/appstate.js +28 -1
  265. package/dist/protocol/browser.js +10 -18
  266. package/dist/protocol/constants.js +26 -1
  267. package/dist/protocol/defaults.js +6 -0
  268. package/dist/protocol/index.js +23 -42
  269. package/dist/protocol/jid.js +140 -52
  270. package/dist/protocol/media.js +3 -3
  271. package/dist/protocol/message.js +62 -2
  272. package/dist/protocol/nodes.js +4 -0
  273. package/dist/protocol/notification.js +3 -1
  274. package/dist/protocol/privacy-token.js +20 -0
  275. package/dist/protocol/privacy.js +58 -0
  276. package/dist/protocol/stream.js +27 -2
  277. package/dist/protocol/usync.js +14 -0
  278. package/dist/retry/codec.js +220 -0
  279. package/dist/retry/constants.js +1 -1
  280. package/dist/retry/index.js +7 -5
  281. package/dist/retry/parse.js +88 -85
  282. package/dist/retry/replay.js +52 -49
  283. package/dist/retry/tracker.js +97 -0
  284. package/dist/signal/api/SignalDeviceSyncApi.js +273 -89
  285. package/dist/signal/api/SignalDigestSyncApi.js +17 -8
  286. package/dist/signal/api/SignalIdentitySyncApi.js +66 -36
  287. package/dist/signal/api/SignalMissingPreKeysSyncApi.js +82 -63
  288. package/dist/signal/api/SignalRotateKeyApi.js +4 -2
  289. package/dist/signal/api/SignalSessionSyncApi.js +36 -34
  290. package/dist/signal/api/result-map.js +13 -0
  291. package/dist/signal/constants.js +1 -5
  292. package/dist/signal/crypto/WaAdvSignature.js +11 -7
  293. package/dist/signal/{store/sqlite.js → encoding.js} +94 -61
  294. package/dist/signal/group/SenderKeyChain.js +27 -22
  295. package/dist/signal/group/SenderKeyCodec.js +5 -6
  296. package/dist/signal/group/SenderKeyManager.js +144 -115
  297. package/dist/signal/index.js +15 -1
  298. package/dist/signal/registration/keygen.js +6 -2
  299. package/dist/signal/registration/utils.js +1 -0
  300. package/dist/signal/session/SignalProtocol.js +164 -53
  301. package/dist/signal/session/SignalRatchet.js +24 -15
  302. package/dist/signal/session/SignalSession.js +14 -9
  303. package/dist/signal/session/resolver.js +224 -0
  304. package/dist/store/contracts/privacy-token.store.js +2 -0
  305. package/dist/store/createStore.js +100 -188
  306. package/dist/store/index.js +15 -33
  307. package/dist/store/locks/appstate.lock.js +29 -0
  308. package/dist/store/locks/auth.lock.js +18 -0
  309. package/dist/store/locks/contact.lock.js +23 -0
  310. package/dist/store/locks/device-list.lock.js +23 -0
  311. package/dist/store/locks/message.lock.js +24 -0
  312. package/dist/store/locks/participants.lock.js +23 -0
  313. package/dist/store/locks/privacy-token.lock.js +21 -0
  314. package/dist/store/locks/retry.lock.js +32 -0
  315. package/dist/store/locks/sender-key.lock.js +55 -0
  316. package/dist/store/locks/signal.lock.js +66 -0
  317. package/dist/store/locks/thread.lock.js +24 -0
  318. package/dist/store/noop.store.js +4 -7
  319. package/dist/store/providers/memory/appstate.store.js +36 -14
  320. package/dist/store/providers/memory/contact.store.js +5 -0
  321. package/dist/store/providers/memory/device-list.store.js +12 -34
  322. package/dist/store/providers/memory/message.store.js +11 -5
  323. package/dist/store/providers/memory/participants.store.js +1 -8
  324. package/dist/store/providers/memory/privacy-token.store.js +47 -0
  325. package/dist/store/providers/memory/retry.store.js +77 -2
  326. package/dist/store/providers/memory/sender-key.store.js +14 -11
  327. package/dist/store/providers/memory/signal.store.js +54 -25
  328. package/dist/store/providers/memory/thread.store.js +5 -0
  329. package/dist/transport/WaComms.js +30 -26
  330. package/dist/transport/WaWebSocket.js +148 -18
  331. package/dist/transport/binary/constants.js +1 -31
  332. package/dist/transport/binary/decoder.js +8 -8
  333. package/dist/transport/binary/encoder.js +10 -9
  334. package/dist/transport/binary/index.js +0 -4
  335. package/dist/transport/index.js +7 -1
  336. package/dist/transport/keepalive/WaKeepAlive.js +1 -7
  337. package/dist/transport/node/WaNodeOrchestrator.js +25 -21
  338. package/dist/transport/node/WaNodeTransport.js +0 -3
  339. package/dist/transport/node/builders/{accountSync.js → account-sync.js} +15 -35
  340. package/dist/transport/node/builders/business.js +137 -0
  341. package/dist/transport/node/builders/global.js +375 -0
  342. package/dist/transport/node/builders/index.js +29 -17
  343. package/dist/transport/node/builders/message.js +64 -236
  344. package/dist/transport/node/builders/pairing.js +2 -29
  345. package/dist/transport/node/builders/privacy-token.js +46 -0
  346. package/dist/transport/node/builders/privacy.js +55 -0
  347. package/dist/transport/node/builders/profile.js +78 -0
  348. package/dist/transport/node/builders/retry.js +9 -21
  349. package/dist/transport/node/builders/usync.js +49 -0
  350. package/dist/transport/node/helpers.js +131 -4
  351. package/dist/transport/node/usync.js +8 -0
  352. package/dist/transport/node/xml.js +35 -14
  353. package/dist/transport/noise/WaClientPayload.js +13 -13
  354. package/dist/transport/noise/WaFrameCodec.js +47 -32
  355. package/dist/transport/noise/WaNoiseCert.js +5 -8
  356. package/dist/transport/noise/WaNoiseSession.js +77 -29
  357. package/dist/transport/noise/WaNoiseSocket.js +8 -4
  358. package/dist/transport/proxy.js +34 -0
  359. package/dist/transport/stream/parse.js +20 -52
  360. package/dist/types/appstate/WaAppStateCrypto.d.ts +0 -1
  361. package/dist/types/appstate/WaAppStateSyncClient.d.ts +5 -2
  362. package/dist/types/appstate/constants.d.ts +1 -0
  363. package/dist/types/appstate/encoding.d.ts +7 -0
  364. package/dist/types/appstate/index.d.ts +3 -3
  365. package/dist/types/appstate/utils.d.ts +0 -3
  366. package/dist/types/auth/WaAuthClient.d.ts +10 -12
  367. package/dist/types/auth/flow/WaAuthCredentialsFlow.d.ts +1 -1
  368. package/dist/types/auth/index.d.ts +0 -4
  369. package/dist/types/auth/pairing/WaQrFlow.d.ts +1 -1
  370. package/dist/types/auth/types.d.ts +7 -9
  371. package/dist/types/client/WaClient.d.ts +42 -25
  372. package/dist/types/client/WaClientFactory.d.ts +33 -26
  373. package/dist/types/client/connection/WaConnectionManager.d.ts +66 -0
  374. package/dist/types/client/connection/WaKeyShareCoordinator.d.ts +14 -0
  375. package/dist/types/client/connection/WaReceiptQueue.d.ts +13 -0
  376. package/dist/types/client/coordinators/WaAppStateMutationCoordinator.d.ts +46 -0
  377. package/dist/types/client/coordinators/WaBusinessCoordinator.d.ts +57 -0
  378. package/dist/types/client/coordinators/WaIncomingNodeCoordinator.d.ts +3 -2
  379. package/dist/types/client/coordinators/WaMessageDispatchCoordinator.d.ts +29 -38
  380. package/dist/types/client/coordinators/WaPassiveTasksCoordinator.d.ts +4 -0
  381. package/dist/types/client/coordinators/WaPrivacyCoordinator.d.ts +26 -0
  382. package/dist/types/client/coordinators/WaProfileCoordinator.d.ts +36 -0
  383. package/dist/types/client/coordinators/WaRetryCoordinator.d.ts +8 -0
  384. package/dist/types/client/coordinators/WaStreamControlCoordinator.d.ts +3 -2
  385. package/dist/types/client/coordinators/WaTrustedContactTokenCoordinator.d.ts +45 -0
  386. package/dist/types/client/dirty.d.ts +1 -0
  387. package/dist/types/client/events/devices.d.ts +20 -0
  388. package/dist/types/client/events/group.d.ts +2 -1
  389. package/dist/types/client/events/identity.d.ts +9 -0
  390. package/dist/types/client/events/privacy-token.d.ts +7 -0
  391. package/dist/types/client/history-sync.d.ts +9 -6
  392. package/dist/types/client/incoming.d.ts +3 -1
  393. package/dist/types/client/index.d.ts +1 -1
  394. package/dist/types/client/mailbox.d.ts +3 -5
  395. package/dist/types/client/messages.d.ts +1 -2
  396. package/dist/types/client/messaging/fanout.d.ts +14 -0
  397. package/dist/types/client/messaging/key-protocol.d.ts +18 -0
  398. package/dist/types/client/messaging/participants.d.ts +13 -0
  399. package/dist/types/client/persistence/WriteBehindPersistence.d.ts +34 -0
  400. package/dist/types/client/tokens/cs-token.d.ts +10 -0
  401. package/dist/types/client/tokens/tc-token.d.ts +5 -0
  402. package/dist/types/client/types.d.ts +75 -4
  403. package/dist/types/crypto/core/hkdf.d.ts +0 -6
  404. package/dist/types/crypto/core/index.d.ts +2 -3
  405. package/dist/types/crypto/core/nonce.d.ts +2 -0
  406. package/dist/types/crypto/core/primitives.d.ts +0 -1
  407. package/dist/types/crypto/core/random.d.ts +2 -7
  408. package/dist/types/crypto/index.d.ts +0 -1
  409. package/dist/types/crypto/math/constants.d.ts +4 -2
  410. package/dist/types/crypto/math/fe.d.ts +30 -0
  411. package/dist/types/crypto/math/mod.d.ts +0 -2
  412. package/dist/types/crypto/math/types.d.ts +11 -4
  413. package/dist/types/index.d.ts +5 -3
  414. package/dist/types/infra/log/ConsoleLogger.d.ts +2 -1
  415. package/dist/types/infra/log/PinoLogger.d.ts +1 -1
  416. package/dist/types/infra/log/types.d.ts +1 -0
  417. package/dist/types/infra/perf/BackgroundQueue.d.ts +58 -0
  418. package/dist/types/infra/perf/BoundedTaskQueue.d.ts +1 -1
  419. package/dist/types/infra/perf/PromiseDedup.d.ts +4 -0
  420. package/dist/types/infra/perf/SharedExclusiveGate.d.ts +17 -0
  421. package/dist/types/infra/perf/StoreLock.d.ts +10 -0
  422. package/dist/types/media/WaMediaCrypto.d.ts +3 -2
  423. package/dist/types/media/WaMediaTransferClient.d.ts +16 -15
  424. package/dist/types/media/constants.d.ts +1 -1
  425. package/dist/types/media/index.d.ts +1 -1
  426. package/dist/types/media/types.d.ts +15 -2
  427. package/dist/types/message/addon-crypto.d.ts +25 -0
  428. package/dist/types/message/content.d.ts +8 -0
  429. package/dist/types/message/icdc.d.ts +13 -0
  430. package/dist/types/message/index.d.ts +2 -0
  431. package/dist/types/message/reporting-token.d.ts +18 -0
  432. package/dist/types/message/types.d.ts +45 -6
  433. package/dist/types/message/use-case-secret.d.ts +20 -0
  434. package/dist/types/protocol/appstate.d.ts +47 -0
  435. package/dist/types/protocol/constants.d.ts +8 -3
  436. package/dist/types/protocol/defaults.d.ts +6 -0
  437. package/dist/types/protocol/index.d.ts +2 -11
  438. package/dist/types/protocol/jid.d.ts +22 -5
  439. package/dist/types/protocol/message.d.ts +60 -0
  440. package/dist/types/protocol/nodes.d.ts +4 -0
  441. package/dist/types/protocol/notification.d.ts +2 -0
  442. package/dist/types/protocol/privacy-token.d.ts +17 -0
  443. package/dist/types/protocol/privacy.d.ts +75 -0
  444. package/dist/types/protocol/stream.d.ts +30 -0
  445. package/dist/types/protocol/usync.d.ts +11 -0
  446. package/dist/types/retry/codec.d.ts +3 -0
  447. package/dist/types/retry/index.d.ts +4 -3
  448. package/dist/types/retry/parse.d.ts +5 -2
  449. package/dist/types/retry/replay.d.ts +0 -4
  450. package/dist/types/retry/tracker.d.ts +20 -0
  451. package/dist/types/retry/types.d.ts +10 -4
  452. package/dist/types/signal/api/SignalDeviceSyncApi.d.ts +15 -2
  453. package/dist/types/signal/api/SignalDigestSyncApi.d.ts +6 -0
  454. package/dist/types/signal/api/SignalIdentitySyncApi.d.ts +2 -0
  455. package/dist/types/signal/api/SignalRotateKeyApi.d.ts +4 -5
  456. package/dist/types/signal/api/SignalSessionSyncApi.d.ts +8 -6
  457. package/dist/types/signal/api/result-map.d.ts +1 -0
  458. package/dist/types/signal/constants.d.ts +0 -3
  459. package/dist/types/signal/{store/sqlite.d.ts → encoding.d.ts} +3 -3
  460. package/dist/types/signal/group/SenderKeyCodec.d.ts +4 -6
  461. package/dist/types/signal/group/SenderKeyManager.d.ts +10 -5
  462. package/dist/types/signal/index.d.ts +3 -0
  463. package/dist/types/signal/session/SignalProtocol.d.ts +19 -4
  464. package/dist/types/signal/session/resolver.d.ts +22 -0
  465. package/dist/types/store/contracts/appstate.store.d.ts +4 -1
  466. package/dist/types/store/contracts/contact.store.d.ts +1 -0
  467. package/dist/types/store/contracts/device-list.store.d.ts +0 -3
  468. package/dist/types/store/contracts/message.store.d.ts +1 -0
  469. package/dist/types/store/contracts/participants.store.d.ts +0 -1
  470. package/dist/types/store/contracts/privacy-token.store.d.ts +16 -0
  471. package/dist/types/store/contracts/retry.store.d.ts +7 -0
  472. package/dist/types/store/contracts/sender-key.store.d.ts +0 -1
  473. package/dist/types/store/contracts/signal.store.d.ts +13 -0
  474. package/dist/types/store/contracts/thread.store.d.ts +1 -0
  475. package/dist/types/store/createStore.d.ts +1 -1
  476. package/dist/types/store/index.d.ts +5 -13
  477. package/dist/types/store/locks/appstate.lock.d.ts +3 -0
  478. package/dist/types/store/locks/auth.lock.d.ts +3 -0
  479. package/dist/types/store/locks/contact.lock.d.ts +3 -0
  480. package/dist/types/store/locks/device-list.lock.d.ts +2 -0
  481. package/dist/types/store/locks/message.lock.d.ts +3 -0
  482. package/dist/types/store/locks/participants.lock.d.ts +2 -0
  483. package/dist/types/store/locks/privacy-token.lock.d.ts +2 -0
  484. package/dist/types/store/locks/retry.lock.d.ts +2 -0
  485. package/dist/types/store/locks/sender-key.lock.d.ts +3 -0
  486. package/dist/types/store/locks/signal.lock.d.ts +3 -0
  487. package/dist/types/store/locks/thread.lock.d.ts +3 -0
  488. package/dist/types/store/providers/memory/appstate.store.d.ts +3 -1
  489. package/dist/types/store/providers/memory/contact.store.d.ts +1 -0
  490. package/dist/types/store/providers/memory/device-list.store.d.ts +0 -3
  491. package/dist/types/store/providers/memory/message.store.d.ts +1 -0
  492. package/dist/types/store/providers/memory/participants.store.d.ts +0 -1
  493. package/dist/types/store/providers/memory/privacy-token.store.d.ts +13 -0
  494. package/dist/types/store/providers/memory/retry.store.d.ts +8 -0
  495. package/dist/types/store/providers/memory/sender-key.store.d.ts +0 -1
  496. package/dist/types/store/providers/memory/signal.store.d.ts +8 -1
  497. package/dist/types/store/providers/memory/thread.store.d.ts +1 -0
  498. package/dist/types/store/types.d.ts +49 -58
  499. package/dist/types/transport/WaWebSocket.d.ts +3 -1
  500. package/dist/types/transport/binary/constants.d.ts +0 -30
  501. package/dist/types/transport/binary/index.d.ts +0 -1
  502. package/dist/types/transport/index.d.ts +2 -1
  503. package/dist/types/transport/keepalive/WaKeepAlive.d.ts +0 -1
  504. package/dist/types/transport/node/WaNodeOrchestrator.d.ts +3 -4
  505. package/dist/types/transport/node/WaNodeTransport.d.ts +0 -9
  506. package/dist/types/transport/node/builders/business.d.ts +29 -0
  507. package/dist/types/transport/node/builders/global.d.ts +102 -0
  508. package/dist/types/transport/node/builders/group.d.ts +4 -6
  509. package/dist/types/transport/node/builders/index.d.ts +7 -3
  510. package/dist/types/transport/node/builders/message.d.ts +20 -30
  511. package/dist/types/transport/node/builders/pairing.d.ts +0 -2
  512. package/dist/types/transport/node/builders/privacy-token.d.ts +9 -0
  513. package/dist/types/transport/node/builders/privacy.d.ts +7 -0
  514. package/dist/types/transport/node/builders/profile.d.ts +8 -0
  515. package/dist/types/transport/node/builders/retry.d.ts +2 -5
  516. package/dist/types/transport/node/builders/usync.d.ts +21 -0
  517. package/dist/types/transport/node/helpers.d.ts +13 -0
  518. package/dist/types/transport/node/usync.d.ts +2 -0
  519. package/dist/types/transport/noise/WaFrameCodec.d.ts +3 -0
  520. package/dist/types/transport/noise/WaNoiseSession.d.ts +4 -2
  521. package/dist/types/transport/noise/WaNoiseSocket.d.ts +4 -2
  522. package/dist/types/transport/proxy.d.ts +6 -0
  523. package/dist/types/transport/stream/parse.d.ts +0 -1
  524. package/dist/types/transport/types.d.ts +18 -1
  525. package/dist/types/util/bytes.d.ts +5 -0
  526. package/dist/types/util/index.d.ts +5 -0
  527. package/dist/types/util/primitives.d.ts +2 -0
  528. package/dist/util/bytes.js +72 -46
  529. package/dist/util/coercion.js +6 -14
  530. package/dist/util/index.js +23 -0
  531. package/dist/util/primitives.js +42 -14
  532. package/package.json +52 -9
  533. package/proto/index.js +1 -1
  534. package/dist/crypto/core/constants.js +0 -4
  535. package/dist/crypto/core/encoding.js +0 -29
  536. package/dist/esm/crypto/core/constants.js +0 -1
  537. package/dist/esm/crypto/core/encoding.js +0 -25
  538. package/dist/esm/retry/outbound.js +0 -83
  539. package/dist/esm/store/providers/sqlite/BaseSqliteStore.js +0 -37
  540. package/dist/esm/store/providers/sqlite/appstate.store.js +0 -169
  541. package/dist/esm/store/providers/sqlite/auth.store.js +0 -176
  542. package/dist/esm/store/providers/sqlite/connection.js +0 -240
  543. package/dist/esm/store/providers/sqlite/contact.store.js +0 -61
  544. package/dist/esm/store/providers/sqlite/device-list.store.js +0 -155
  545. package/dist/esm/store/providers/sqlite/message.store.js +0 -119
  546. package/dist/esm/store/providers/sqlite/migrations.js +0 -347
  547. package/dist/esm/store/providers/sqlite/participants.store.js +0 -85
  548. package/dist/esm/store/providers/sqlite/retry.store.js +0 -144
  549. package/dist/esm/store/providers/sqlite/sender-key.store.js +0 -203
  550. package/dist/esm/store/providers/sqlite/signal.store.js +0 -353
  551. package/dist/esm/store/providers/sqlite/thread.store.js +0 -72
  552. package/dist/esm/util/base64.js +0 -18
  553. package/dist/esm/util/signal-address.js +0 -5
  554. package/dist/retry/outbound.js +0 -88
  555. package/dist/store/providers/sqlite/BaseSqliteStore.js +0 -41
  556. package/dist/store/providers/sqlite/appstate.store.js +0 -173
  557. package/dist/store/providers/sqlite/auth.store.js +0 -180
  558. package/dist/store/providers/sqlite/connection.js +0 -276
  559. package/dist/store/providers/sqlite/contact.store.js +0 -65
  560. package/dist/store/providers/sqlite/device-list.store.js +0 -159
  561. package/dist/store/providers/sqlite/message.store.js +0 -123
  562. package/dist/store/providers/sqlite/migrations.js +0 -350
  563. package/dist/store/providers/sqlite/participants.store.js +0 -89
  564. package/dist/store/providers/sqlite/retry.store.js +0 -148
  565. package/dist/store/providers/sqlite/sender-key.store.js +0 -207
  566. package/dist/store/providers/sqlite/signal.store.js +0 -357
  567. package/dist/store/providers/sqlite/thread.store.js +0 -76
  568. package/dist/types/appstate/store/sqlite.d.ts +0 -21
  569. package/dist/types/crypto/core/constants.d.ts +0 -1
  570. package/dist/types/crypto/core/encoding.d.ts +0 -11
  571. package/dist/types/retry/outbound.d.ts +0 -4
  572. package/dist/types/store/providers/sqlite/BaseSqliteStore.d.ts +0 -12
  573. package/dist/types/store/providers/sqlite/appstate.store.d.ts +0 -15
  574. package/dist/types/store/providers/sqlite/auth.store.d.ts +0 -10
  575. package/dist/types/store/providers/sqlite/connection.d.ts +0 -10
  576. package/dist/types/store/providers/sqlite/contact.store.d.ts +0 -10
  577. package/dist/types/store/providers/sqlite/device-list.store.d.ts +0 -18
  578. package/dist/types/store/providers/sqlite/message.store.d.ts +0 -11
  579. package/dist/types/store/providers/sqlite/migrations.d.ts +0 -3
  580. package/dist/types/store/providers/sqlite/participants.store.d.ts +0 -13
  581. package/dist/types/store/providers/sqlite/retry.store.d.ts +0 -16
  582. package/dist/types/store/providers/sqlite/sender-key.store.d.ts +0 -25
  583. package/dist/types/store/providers/sqlite/signal.store.d.ts +0 -46
  584. package/dist/types/store/providers/sqlite/thread.store.d.ts +0 -11
  585. package/dist/types/util/base64.d.ts +0 -4
  586. package/dist/types/util/signal-address.d.ts +0 -2
  587. package/dist/util/base64.js +0 -24
  588. package/dist/util/signal-address.js +0 -8
  589. /package/dist/types/transport/node/builders/{accountSync.d.ts → account-sync.d.ts} +0 -0
@@ -6,15 +6,15 @@ const utils_1 = require("../appstate/utils");
6
6
  const chat_1 = require("./events/chat");
7
7
  const history_sync_1 = require("./history-sync");
8
8
  const mailbox_1 = require("./mailbox");
9
+ const WriteBehindPersistence_1 = require("./persistence/WriteBehindPersistence");
9
10
  const WaClientFactory_1 = require("./WaClientFactory");
10
11
  const ConsoleLogger_1 = require("../infra/log/ConsoleLogger");
11
12
  const _proto_1 = require("../proto.js");
12
13
  const constants_1 = require("../protocol/constants");
13
14
  const jid_1 = require("../protocol/jid");
14
15
  const query_1 = require("../transport/node/query");
15
- const WaComms_1 = require("../transport/WaComms");
16
- const base64_1 = require("../util/base64");
17
16
  const bytes_1 = require("../util/bytes");
17
+ const bytes_2 = require("../util/bytes");
18
18
  const primitives_1 = require("../util/primitives");
19
19
  const SYNC_RELATED_PROTOCOL_TYPES = new Set([
20
20
  _proto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_REQUEST,
@@ -27,15 +27,10 @@ const WA_APP_STATE_KEY_SHARE_MAX_RETRIES = 2;
27
27
  class WaClient extends node_events_1.EventEmitter {
28
28
  constructor(options, logger = new ConsoleLogger_1.ConsoleLogger('info')) {
29
29
  super();
30
- this.clockSkewMs = null;
31
- this.mediaConnCache = null;
32
- this.comms = null;
33
- this.pairingReconnectPromise = null;
34
30
  this.connectPromise = null;
35
- this.danglingReceipts = [];
36
- this.appStateKeyShareWaiters = new Set();
37
- this.appStateKeyShareVersion = 0;
38
- this.appStateBootstrapKeyShareWaitDone = false;
31
+ this.acceptingIncomingEvents = true;
32
+ this.activeIncomingHandlers = 0;
33
+ this.incomingHandlersDrainedWaiters = [];
39
34
  const base = (0, WaClientFactory_1.resolveWaClientBase)(options, logger);
40
35
  this.options = base.options;
41
36
  this.logger = base.logger;
@@ -43,36 +38,34 @@ class WaClient extends node_events_1.EventEmitter {
43
38
  this.contactStore = base.sessionStore.contacts;
44
39
  this.messageStore = base.sessionStore.messages;
45
40
  this.participantsStore = base.sessionStore.participants;
41
+ this.privacyTokenStore = base.sessionStore.privacyToken;
46
42
  this.deviceListStore = base.sessionStore.deviceList;
47
43
  this.retryStore = base.sessionStore.retry;
48
44
  this.signalStore = base.sessionStore.signal;
49
45
  this.senderKeyStore = base.sessionStore.senderKey;
50
46
  this.threadStore = base.sessionStore.threads;
51
- const host = {
52
- sendNode: (node) => this.sendNode(node),
53
- query: (node, timeoutMs) => this.query(node, timeoutMs),
54
- queryWithContext: this.queryWithContext.bind(this),
55
- syncAppState: () => this.syncAppState().then(() => { }),
56
- emitEvent: this.emit.bind(this),
57
- handleIncomingMessageEvent: this.handleIncomingMessageEvent.bind(this),
58
- handleError: this.handleError.bind(this),
59
- scheduleReconnectAfterPairing: this.scheduleReconnectAfterPairing.bind(this),
60
- updateClockSkewFromSuccess: this.updateClockSkewFromSuccess.bind(this),
61
- getComms: () => this.comms,
62
- getMediaConnCache: () => this.mediaConnCache,
63
- setMediaConnCache: (mediaConn) => {
64
- this.mediaConnCache = mediaConn;
65
- },
66
- disconnect: this.disconnect.bind(this),
67
- clearStoredState: this.clearStoredState.bind(this),
68
- connect: this.connect.bind(this),
69
- shouldQueueDanglingReceipt: (node, error) => this.shouldQueueDanglingReceipt(node, error),
70
- enqueueDanglingReceipt: this.enqueueDanglingReceipt.bind(this),
71
- takeDanglingReceipts: () => this.danglingReceipts.splice(0)
72
- };
47
+ this.writeBehind = new WriteBehindPersistence_1.WriteBehindPersistence({
48
+ messageStore: this.messageStore,
49
+ threadStore: this.threadStore,
50
+ contactStore: this.contactStore
51
+ }, this.logger, this.options.writeBehind);
73
52
  const dependencies = (0, WaClientFactory_1.buildWaClientDependencies)({
74
53
  base,
75
- host
54
+ runtime: {
55
+ sendNode: (node) => this.sendNode(node),
56
+ query: (node, timeoutMs) => this.query(node, timeoutMs),
57
+ queryWithContext: this.queryWithContext.bind(this),
58
+ syncAppState: () => this.syncAppState().then(() => { }),
59
+ syncAppStateWithOptions: (syncOptions) => this.syncAppState(syncOptions),
60
+ emitEvent: this.emit.bind(this),
61
+ handleIncomingMessageEvent: this.handleIncomingMessageEvent.bind(this),
62
+ handleError: this.handleError.bind(this),
63
+ handleIncomingFrame: this.handleIncomingFrame.bind(this),
64
+ clearStoredState: this.clearStoredState.bind(this),
65
+ resumeIncomingEvents: () => {
66
+ this.acceptingIncomingEvents = true;
67
+ }
68
+ }
76
69
  });
77
70
  Object.assign(this, dependencies);
78
71
  this.bindNodeTransportEvents();
@@ -90,7 +83,7 @@ class WaClient extends node_events_1.EventEmitter {
90
83
  return super.emit(event, ...args);
91
84
  }
92
85
  getState() {
93
- const connected = this.comms !== null && this.comms.getCommsState().connected;
86
+ const connected = this.connectionManager.isConnected();
94
87
  this.logger.trace('wa client state requested', { connected });
95
88
  return this.authClient.getState(connected);
96
89
  }
@@ -98,7 +91,7 @@ class WaClient extends node_events_1.EventEmitter {
98
91
  return this.authClient.getCurrentCredentials();
99
92
  }
100
93
  getClockSkewMs() {
101
- return this.clockSkewMs;
94
+ return this.connectionManager.getClockSkewMs();
102
95
  }
103
96
  async sendNode(node) {
104
97
  try {
@@ -106,13 +99,13 @@ class WaClient extends node_events_1.EventEmitter {
106
99
  }
107
100
  catch (error) {
108
101
  const normalized = (0, primitives_1.toError)(error);
109
- if (this.shouldQueueDanglingReceipt(node, normalized)) {
110
- this.enqueueDanglingReceipt(node);
102
+ if (this.receiptQueue.shouldQueue(node, normalized)) {
103
+ this.receiptQueue.enqueue(node);
111
104
  this.logger.warn('queued dangling receipt after send failure', {
112
105
  id: node.attrs.id,
113
106
  to: node.attrs.to,
114
107
  message: normalized.message,
115
- queueSize: this.danglingReceipts.length
108
+ queueSize: this.receiptQueue.size()
116
109
  });
117
110
  return;
118
111
  }
@@ -120,7 +113,7 @@ class WaClient extends node_events_1.EventEmitter {
120
113
  }
121
114
  }
122
115
  async query(node, timeoutMs = this.options.iqTimeoutMs ?? constants_1.WA_DEFAULTS.IQ_TIMEOUT_MS) {
123
- if (!this.comms || !this.comms.getCommsState().connected) {
116
+ if (!this.connectionManager.isConnected()) {
124
117
  throw new Error('client is not connected');
125
118
  }
126
119
  this.logger.debug('wa client query', { tag: node.tag, id: node.attrs.id, timeoutMs });
@@ -143,57 +136,64 @@ class WaClient extends node_events_1.EventEmitter {
143
136
  });
144
137
  }
145
138
  async handleIncomingMessageEvent(event) {
146
- this.emit('message', event);
147
- void (0, mailbox_1.persistIncomingMailboxEntities)({
148
- logger: this.logger,
149
- contactStore: this.contactStore,
150
- messageStore: this.messageStore,
151
- event
152
- });
153
- const protocolMessage = event.message?.protocolMessage;
154
- if (!protocolMessage) {
139
+ if (!this.tryEnterIncomingHandler()) {
155
140
  return;
156
141
  }
157
- const protocolEvent = {
158
- ...event,
159
- protocolMessage
160
- };
161
- this.emit('message_protocol', protocolEvent);
162
- const protocolType = protocolMessage.type;
163
- if (protocolType === null || protocolType === undefined) {
164
- this.logger.debug('incoming protocol message without type', {
165
- id: event.stanzaId,
166
- from: event.chatJid
142
+ try {
143
+ this.emit('message', event);
144
+ void (0, mailbox_1.persistIncomingMailboxEntities)({
145
+ logger: this.logger,
146
+ writeBehind: this.writeBehind,
147
+ event
167
148
  });
168
- return;
169
- }
170
- if (protocolType === _proto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_REQUEST) {
171
- await this.handleIncomingAppStateSyncKeyRequest(event, protocolMessage);
172
- return;
173
- }
174
- if (protocolType === _proto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE) {
175
- await this.handleIncomingAppStateSyncKeyShare(event, protocolMessage);
176
- return;
177
- }
178
- if (protocolType === _proto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION) {
179
- if (this.options.history?.enabled && protocolMessage.historySyncNotification) {
180
- await this.handleHistorySyncNotification(protocolMessage.historySyncNotification);
149
+ const protocolMessage = event.message?.protocolMessage;
150
+ if (!protocolMessage) {
151
+ return;
181
152
  }
182
- return;
183
- }
184
- if (SYNC_RELATED_PROTOCOL_TYPES.has(protocolType)) {
185
- this.logger.info('incoming sync-related protocol message', {
153
+ const protocolEvent = {
154
+ ...event,
155
+ protocolMessage
156
+ };
157
+ this.emit('message_protocol', protocolEvent);
158
+ const protocolType = protocolMessage.type;
159
+ if (protocolType === null || protocolType === undefined) {
160
+ this.logger.debug('incoming protocol message without type', {
161
+ id: event.stanzaId,
162
+ from: event.chatJid
163
+ });
164
+ return;
165
+ }
166
+ if (protocolType === _proto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_REQUEST) {
167
+ await this.handleIncomingAppStateSyncKeyRequest(event, protocolMessage);
168
+ return;
169
+ }
170
+ if (protocolType === _proto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE) {
171
+ await this.handleIncomingAppStateSyncKeyShare(event, protocolMessage);
172
+ return;
173
+ }
174
+ if (protocolType === _proto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION) {
175
+ if (this.options.history?.enabled && protocolMessage.historySyncNotification) {
176
+ await this.handleHistorySyncNotification(protocolMessage.historySyncNotification);
177
+ }
178
+ return;
179
+ }
180
+ if (SYNC_RELATED_PROTOCOL_TYPES.has(protocolType)) {
181
+ this.logger.info('incoming sync-related protocol message', {
182
+ id: event.stanzaId,
183
+ from: event.chatJid,
184
+ protocolType
185
+ });
186
+ return;
187
+ }
188
+ this.logger.debug('incoming protocol message received', {
186
189
  id: event.stanzaId,
187
190
  from: event.chatJid,
188
191
  protocolType
189
192
  });
190
- return;
191
193
  }
192
- this.logger.debug('incoming protocol message received', {
193
- id: event.stanzaId,
194
- from: event.chatJid,
195
- protocolType
196
- });
194
+ finally {
195
+ this.leaveIncomingHandler();
196
+ }
197
197
  }
198
198
  async handleIncomingAppStateSyncKeyShare(event, protocolMessage) {
199
199
  const share = protocolMessage.appStateSyncKeyShare;
@@ -212,9 +212,8 @@ class WaClient extends node_events_1.EventEmitter {
212
212
  imported
213
213
  });
214
214
  if (imported > 0) {
215
- const hadWaiters = this.appStateKeyShareWaiters.size > 0;
216
- this.appStateKeyShareVersion += 1;
217
- this.notifyAppStateKeyShareWaiters(true);
215
+ const hadWaiters = this.keyShareCoordinator.hasWaiters();
216
+ this.keyShareCoordinator.notifyReceived();
218
217
  if (hadWaiters) {
219
218
  this.logger.debug('app-state key share imported and waiters released', {
220
219
  id: event.stanzaId,
@@ -283,9 +282,18 @@ class WaClient extends node_events_1.EventEmitter {
283
282
  });
284
283
  return;
285
284
  }
286
- const requestedKeys = await Promise.all(requestedKeyIds.map((keyId) => this.appStateStore.getSyncKey(keyId)));
287
- const availableKeys = requestedKeys.filter((key) => key !== null);
288
- const missingKeyIds = requestedKeyIds.filter((_, index) => requestedKeys[index] === null);
285
+ const requestedKeys = await this.appStateStore.getSyncKeysBatch(requestedKeyIds);
286
+ const availableKeys = [];
287
+ const missingKeyIds = [];
288
+ for (let i = 0; i < requestedKeys.length; i += 1) {
289
+ const key = requestedKeys[i];
290
+ if (key !== null) {
291
+ availableKeys.push(key);
292
+ }
293
+ else {
294
+ missingKeyIds.push(requestedKeyIds[i]);
295
+ }
296
+ }
289
297
  try {
290
298
  await this.messageDispatch.sendAppStateSyncKeyShare(requesterDeviceJid, availableKeys, missingKeyIds);
291
299
  this.logger.info('responded to app-state key request', {
@@ -311,8 +319,8 @@ class WaClient extends node_events_1.EventEmitter {
311
319
  const deduped = new Map();
312
320
  for (const key of request.keyIds ?? []) {
313
321
  try {
314
- const keyId = (0, base64_1.decodeProtoBytes)(key.keyId, 'appStateSyncKeyRequest.keyIds[].keyId');
315
- const keyHex = (0, bytes_1.bytesToHex)(keyId);
322
+ const keyId = (0, bytes_1.decodeProtoBytes)(key.keyId, 'appStateSyncKeyRequest.keyIds[].keyId');
323
+ const keyHex = (0, bytes_2.bytesToHex)(keyId);
316
324
  if (deduped.has(keyHex)) {
317
325
  continue;
318
326
  }
@@ -332,20 +340,18 @@ class WaClient extends node_events_1.EventEmitter {
332
340
  return false;
333
341
  }
334
342
  const candidateUser = (0, jid_1.toUserJid)(candidateJid);
335
- const meUsers = [credentials.meJid, credentials.meLid]
336
- .filter((value) => !!value)
337
- .map((jid) => (0, jid_1.toUserJid)(jid));
338
- return meUsers.includes(candidateUser);
343
+ return ((!!credentials.meJid && (0, jid_1.toUserJid)(credentials.meJid) === candidateUser) ||
344
+ (!!credentials.meLid && (0, jid_1.toUserJid)(credentials.meLid) === candidateUser));
339
345
  }
340
346
  async handleHistorySyncNotification(notification) {
341
347
  try {
342
348
  await (0, history_sync_1.processHistorySyncNotification)({
343
349
  logger: this.logger,
344
350
  mediaTransfer: this.mediaTransfer,
345
- contactStore: this.contactStore,
346
- messageStore: this.messageStore,
347
- threadStore: this.threadStore,
348
- emitEvent: this.emit.bind(this)
351
+ writeBehind: this.writeBehind,
352
+ emitEvent: this.emit.bind(this),
353
+ onPrivacyTokens: (conversations) => this.trustedContactToken.hydrateFromHistorySync(conversations),
354
+ onNctSalt: (salt) => this.trustedContactToken.hydrateNctSaltFromHistorySync(salt)
349
355
  }, notification);
350
356
  }
351
357
  catch (error) {
@@ -372,144 +378,118 @@ class WaClient extends node_events_1.EventEmitter {
372
378
  this.logger.trace('wa client connect already in-flight');
373
379
  return this.connectPromise;
374
380
  }
375
- this.connectPromise = this.connectInternal().finally(() => {
381
+ this.acceptingIncomingEvents = true;
382
+ this.connectPromise = this.connectionManager
383
+ .connect((frame) => this.handleIncomingFrame(frame))
384
+ .then(() => {
385
+ this.emit('connection', {
386
+ status: 'open',
387
+ reason: 'connected',
388
+ code: null,
389
+ isLogout: false,
390
+ isNewLogin: this.connectionManager.wasNewLogin()
391
+ });
392
+ })
393
+ .finally(() => {
376
394
  this.connectPromise = null;
377
395
  });
378
396
  return this.connectPromise;
379
397
  }
380
- async connectInternal() {
381
- if (this.comms) {
382
- this.logger.trace('wa client connect skipped: comms already created');
383
- return;
384
- }
385
- this.logger.info('wa client connect start');
386
- let credentials = await this.authClient.loadOrCreateCredentials();
387
- try {
388
- await this.startCommsWithCredentials(credentials);
389
- }
390
- catch (error) {
391
- if (credentials.routingInfo) {
392
- this.logger.warn('connect failed with routing info, retrying without routing info', {
393
- message: (0, primitives_1.toError)(error).message
394
- });
395
- await this.disconnect();
396
- credentials = await this.authClient.clearRoutingInfo();
397
- await this.startCommsWithCredentials(credentials);
398
- }
399
- else {
400
- await this.disconnect();
401
- throw error;
402
- }
403
- }
404
- this.logger.info('wa client connected');
405
- this.emit('connection_open', {});
406
- }
407
- scheduleReconnectAfterPairing() {
408
- this.logger.debug('wa client scheduling reconnect after pairing');
409
- setTimeout(() => {
410
- void this.reconnectAsRegisteredAfterPairing().catch((error) => {
411
- this.handleError((0, primitives_1.toError)(error));
398
+ async disconnect() {
399
+ await this.pauseIncomingEventsAndWaitDrain();
400
+ const writeBehindFlush = await this.writeBehind.flush(this.options.writeBehind?.flushTimeoutMs);
401
+ if (writeBehindFlush.remaining > 0) {
402
+ this.logger.warn('disconnect continuing with pending write-behind entries', {
403
+ remaining: writeBehindFlush.remaining
412
404
  });
413
- }, 0);
414
- }
415
- async reconnectAsRegisteredAfterPairing() {
416
- if (this.pairingReconnectPromise) {
417
- this.logger.trace('pairing reconnect already in-flight');
418
- return this.pairingReconnectPromise;
419
405
  }
420
- this.pairingReconnectPromise = this.reconnectAsRegisteredAfterPairingInternal().finally(() => {
421
- this.pairingReconnectPromise = null;
406
+ this.keyShareCoordinator.notifyDisconnected();
407
+ await this.connectionManager.disconnect();
408
+ this.emit('connection', {
409
+ status: 'close',
410
+ reason: 'client_disconnected',
411
+ code: null,
412
+ isLogout: false,
413
+ isNewLogin: false
422
414
  });
423
- return this.pairingReconnectPromise;
424
- }
425
- async reconnectAsRegisteredAfterPairingInternal() {
426
- const credentials = this.authClient.getCurrentCredentials();
427
- if (!credentials?.meJid) {
428
- this.logger.trace('pairing reconnect skipped: still unregistered');
429
- return;
430
- }
431
- const currentComms = this.comms;
432
- if (!currentComms) {
433
- this.logger.trace('pairing reconnect skipped: no active comms');
434
- return;
435
- }
436
- this.logger.info('pairing completed, restarting comms as registered');
437
- this.keepAlive.stop();
438
- this.nodeOrchestrator.clearPending(new Error('restarting comms after pairing'));
439
- this.clearCommsBinding();
440
- try {
441
- await currentComms.stopComms();
442
- }
443
- catch (error) {
444
- this.logger.warn('failed to stop pre-registration comms', {
445
- message: (0, primitives_1.toError)(error).message
446
- });
447
- }
448
- try {
449
- await this.startCommsWithCredentials(credentials);
450
- }
451
- catch (error) {
452
- this.logger.warn('pairing reconnect failed while starting registered comms', {
453
- message: (0, primitives_1.toError)(error).message
454
- });
455
- throw error;
456
- }
457
- }
458
- async disconnect() {
459
- this.logger.info('wa client disconnect start');
460
- this.keepAlive.stop();
461
- this.notifyAppStateKeyShareWaiters(false);
462
- this.appStateBootstrapKeyShareWaitDone = false;
463
- await this.authClient.clearTransientState();
464
- this.nodeOrchestrator.clearPending(new Error('client disconnected'));
465
- this.clockSkewMs = null;
466
- this.mediaConnCache = null;
467
- this.passiveTasks.resetInFlightState();
468
- const comms = this.comms;
469
- this.clearCommsBinding();
470
- if (comms) {
471
- await comms.stopComms();
472
- this.logger.info('wa client disconnected');
473
- this.emit('connection_close', {});
474
- }
475
415
  }
476
416
  async requestPairingCode(phoneNumber, shouldShowPushNotification = false) {
477
- if (!this.comms || !this.authClient.getCurrentCredentials()) {
417
+ if (!this.connectionManager.isConnected() || !this.authClient.getCurrentCredentials()) {
478
418
  throw new Error('client is not connected');
479
419
  }
480
420
  this.logger.debug('wa client request pairing code');
481
421
  return this.authClient.requestPairingCode(phoneNumber, shouldShowPushNotification);
482
422
  }
483
423
  async fetchPairingCountryCodeIso() {
484
- if (!this.comms || !this.authClient.getCurrentCredentials()) {
424
+ if (!this.connectionManager.isConnected() || !this.authClient.getCurrentCredentials()) {
485
425
  throw new Error('client is not connected');
486
426
  }
487
427
  this.logger.trace('wa client fetch pairing country code iso');
488
428
  return this.authClient.fetchPairingCountryCodeIso();
489
429
  }
490
- async sendMessage(to, content, options = {}) {
430
+ async getLidsByPhoneNumbers(phoneNumbers) {
431
+ if (!this.connectionManager.isConnected() || !this.authClient.getCurrentCredentials()) {
432
+ throw new Error('client is not connected');
433
+ }
434
+ const normalizedPhoneJids = new Array(phoneNumbers.length);
435
+ for (let index = 0; index < phoneNumbers.length; index += 1) {
436
+ normalizedPhoneJids[index] = (0, jid_1.parsePhoneJid)(phoneNumbers[index]);
437
+ }
438
+ this.logger.trace('wa client query lids by phone numbers', {
439
+ phones: normalizedPhoneJids.length
440
+ });
441
+ return this.signalDeviceSync.queryLidsByPhoneJids(normalizedPhoneJids);
442
+ }
443
+ sendMessage(to, content, options = {}) {
491
444
  return this.messageDispatch.sendMessage(to, content, options);
492
445
  }
493
446
  async syncSignalSession(jid, reasonIdentity = false) {
494
447
  await this.messageDispatch.syncSignalSession(jid, reasonIdentity);
448
+ if (reasonIdentity) {
449
+ this.trustedContactToken.reissueOnIdentityChange(jid).catch((err) => this.logger.warn('tc token reissue on identity change failed', {
450
+ jid,
451
+ message: (0, primitives_1.toError)(err).message
452
+ }));
453
+ }
454
+ }
455
+ get chat() {
456
+ return this.chatCoordinator;
495
457
  }
496
- async sendReceipt(input) {
497
- await this.messageDispatch.sendReceipt(input);
458
+ get group() {
459
+ return this.groupCoordinator;
460
+ }
461
+ get privacy() {
462
+ return this.privacyCoordinator;
463
+ }
464
+ get profile() {
465
+ return this.profileCoordinator;
466
+ }
467
+ get business() {
468
+ return this.businessCoordinator;
469
+ }
470
+ sendReceipt(input) {
471
+ return this.messageDispatch.sendReceipt(input);
472
+ }
473
+ flushAppStateMutations() {
474
+ return this.chatCoordinator.flushMutations();
475
+ }
476
+ flushWriteBehind(timeoutMs) {
477
+ return this.writeBehind.flush(timeoutMs);
498
478
  }
499
479
  async exportAppState() {
500
480
  return this.appStateSync.exportState();
501
481
  }
502
482
  async syncAppState(options = {}) {
503
- if (!this.comms) {
483
+ if (!this.connectionManager.isConnected()) {
504
484
  throw new Error('client is not connected');
505
485
  }
506
486
  const shouldWaitForKeyShare = (await this.appStateStore.getActiveSyncKey()) === null;
507
- if (shouldWaitForKeyShare && !this.appStateBootstrapKeyShareWaitDone) {
508
- this.appStateBootstrapKeyShareWaitDone = true;
487
+ if (shouldWaitForKeyShare && !this.keyShareCoordinator.isBootstrapDone()) {
488
+ this.keyShareCoordinator.markBootstrapDone();
509
489
  this.logger.info('app-state bootstrap pre-sync waiting for key share', {
510
490
  timeoutMs: WA_APP_STATE_KEY_SHARE_WAIT_TIMEOUT_MS
511
491
  });
512
- const received = await this.waitForAppStateKeyShare(WA_APP_STATE_KEY_SHARE_WAIT_TIMEOUT_MS);
492
+ const received = await this.keyShareCoordinator.waitForShare(WA_APP_STATE_KEY_SHARE_WAIT_TIMEOUT_MS);
513
493
  if (received) {
514
494
  this.logger.info('app-state bootstrap pre-sync received key share, continuing sync');
515
495
  }
@@ -526,17 +506,16 @@ class WaClient extends node_events_1.EventEmitter {
526
506
  return syncResult;
527
507
  }
528
508
  let retryCount = 0;
529
- let observedKeyShareVersion = this.appStateKeyShareVersion;
530
- while (blockedCollections.length > 0 &&
531
- retryCount < WA_APP_STATE_KEY_SHARE_MAX_RETRIES) {
532
- const hasFreshShare = this.appStateKeyShareVersion !== observedKeyShareVersion;
509
+ let observedKeyShareVersion = this.keyShareCoordinator.getVersion();
510
+ while (blockedCollections.length > 0 && retryCount < WA_APP_STATE_KEY_SHARE_MAX_RETRIES) {
511
+ const hasFreshShare = this.keyShareCoordinator.getVersion() !== observedKeyShareVersion;
533
512
  if (!hasFreshShare) {
534
513
  this.logger.info('app-state bootstrap waiting for key share', {
535
514
  blockedCollections: blockedCollections.join(','),
536
515
  timeoutMs: WA_APP_STATE_KEY_SHARE_WAIT_TIMEOUT_MS,
537
516
  retryCount: retryCount + 1
538
517
  });
539
- const received = await this.waitForAppStateKeyShare(WA_APP_STATE_KEY_SHARE_WAIT_TIMEOUT_MS);
518
+ const received = await this.keyShareCoordinator.waitForShare(WA_APP_STATE_KEY_SHARE_WAIT_TIMEOUT_MS);
540
519
  if (!received) {
541
520
  this.logger.warn('app-state bootstrap key share wait timed out', {
542
521
  blockedCollections: blockedCollections.join(','),
@@ -545,7 +524,7 @@ class WaClient extends node_events_1.EventEmitter {
545
524
  break;
546
525
  }
547
526
  }
548
- observedKeyShareVersion = this.appStateKeyShareVersion;
527
+ observedKeyShareVersion = this.keyShareCoordinator.getVersion();
549
528
  retryCount += 1;
550
529
  this.logger.info('app-state bootstrap retrying sync after key share', {
551
530
  retryCount,
@@ -572,41 +551,13 @@ class WaClient extends node_events_1.EventEmitter {
572
551
  });
573
552
  }
574
553
  getBlockedAppStateCollections(syncResult) {
575
- return syncResult.collections
576
- .filter((entry) => entry.state === constants_1.WA_APP_STATE_COLLECTION_STATES.BLOCKED)
577
- .map((entry) => entry.collection);
578
- }
579
- async waitForAppStateKeyShare(timeoutMs) {
580
- return new Promise((resolve) => {
581
- let settled = false;
582
- let timeoutHandle = null;
583
- const waiter = (received) => {
584
- if (settled) {
585
- return;
586
- }
587
- settled = true;
588
- if (timeoutHandle) {
589
- clearTimeout(timeoutHandle);
590
- timeoutHandle = null;
591
- }
592
- this.appStateKeyShareWaiters.delete(waiter);
593
- resolve(received);
594
- };
595
- this.appStateKeyShareWaiters.add(waiter);
596
- timeoutHandle = setTimeout(() => {
597
- waiter(false);
598
- }, timeoutMs);
599
- });
600
- }
601
- notifyAppStateKeyShareWaiters(received) {
602
- if (this.appStateKeyShareWaiters.size === 0) {
603
- return;
604
- }
605
- const waiters = [...this.appStateKeyShareWaiters.values()];
606
- this.appStateKeyShareWaiters.clear();
607
- for (const waiter of waiters) {
608
- waiter(received);
554
+ const blocked = [];
555
+ for (const entry of syncResult.collections) {
556
+ if (entry.state === constants_1.WA_APP_STATE_COLLECTION_STATES.BLOCKED) {
557
+ blocked.push(entry.collection);
558
+ }
609
559
  }
560
+ return blocked;
610
561
  }
611
562
  emitChatEventsFromAppStateSyncResult(syncResult) {
612
563
  const shouldEmitSnapshotMutations = this.options.chatEvents?.emitSnapshotMutations === true;
@@ -630,6 +581,7 @@ class WaClient extends node_events_1.EventEmitter {
630
581
  continue;
631
582
  }
632
583
  try {
584
+ this.handleNctSaltMutation(mutation);
633
585
  const event = (0, chat_1.parseChatEventFromAppStateMutation)(mutation);
634
586
  if (!event) {
635
587
  continue;
@@ -647,103 +599,102 @@ class WaClient extends node_events_1.EventEmitter {
647
599
  }
648
600
  }
649
601
  }
650
- async startCommsWithCredentials(credentials) {
651
- this.logger.debug('starting comms with credentials', {
652
- registered: credentials.meJid !== null && credentials.meJid !== undefined
653
- });
654
- const commsConfig = this.authClient.buildCommsConfig(this.options);
655
- const comms = new WaComms_1.WaComms(commsConfig, this.logger);
656
- this.mediaConnCache = null;
657
- this.nodeTransport.bindComms(comms);
658
- try {
659
- comms.startComms(async (frame) => this.handleIncomingFrame(frame));
660
- await comms.waitForConnection(commsConfig.connectTimeoutMs);
661
- this.comms = comms;
662
- this.logger.info('comms connected');
663
- comms.startHandlingRequests();
664
- if (credentials.meJid) {
665
- this.keepAlive.start();
666
- }
667
- else {
668
- this.keepAlive.stop();
669
- }
670
- const serverStaticKey = comms.getServerStaticKey();
671
- if (!serverStaticKey) {
672
- this.logger.trace('no server static key available to persist');
673
- }
674
- else {
675
- await this.authClient.persistServerStaticKey(serverStaticKey);
676
- this.logger.debug('persisted server static key after comms connect');
677
- }
678
- this.passiveTasks.startPassiveTasksAfterConnect();
602
+ handleNctSaltMutation(mutation) {
603
+ const nctAction = mutation.value?.nctSaltSyncAction;
604
+ if (!nctAction) {
605
+ return;
679
606
  }
680
- catch (error) {
681
- this.clearCommsBinding();
682
- try {
683
- await comms.stopComms();
684
- }
685
- catch (stopError) {
686
- this.logger.warn('failed to cleanup comms after connection start failure', {
687
- message: (0, primitives_1.toError)(stopError).message
688
- });
689
- }
690
- throw error;
607
+ if (mutation.operation === 'set' && nctAction.salt) {
608
+ this.trustedContactToken.handleNctSaltSync(nctAction.salt).catch((err) => this.logger.warn('nct salt sync set failed', {
609
+ message: (0, primitives_1.toError)(err).message
610
+ }));
611
+ }
612
+ else if (mutation.operation === 'remove') {
613
+ this.trustedContactToken.handleNctSaltSync(null).catch((err) => this.logger.warn('nct salt sync remove failed', {
614
+ message: (0, primitives_1.toError)(err).message
615
+ }));
691
616
  }
692
617
  }
693
- shouldQueueDanglingReceipt(node, error) {
694
- if (node.tag !== constants_1.WA_MESSAGE_TAGS.RECEIPT) {
618
+ async clearStoredState() {
619
+ await this.pauseIncomingEventsAndWaitDrain();
620
+ const writeBehindDestroy = await this.writeBehind.destroy(this.options.writeBehind?.flushTimeoutMs);
621
+ if (writeBehindDestroy.remaining > 0) {
622
+ throw new Error(`clear stored state aborted: write-behind did not fully drain (remaining=${writeBehindDestroy.remaining})`);
623
+ }
624
+ const danglingReceipts = this.receiptQueue.take();
625
+ if (danglingReceipts.length > 0) {
626
+ this.logger.debug('cleared dangling receipts while clearing stored state', {
627
+ count: danglingReceipts.length
628
+ });
629
+ }
630
+ const s = this.options.logoutStoreClear;
631
+ const shouldClear = (key) => s === undefined || s[key] !== false;
632
+ if (shouldClear('auth'))
633
+ await this.authClient.clearStoredCredentials();
634
+ if (shouldClear('appState'))
635
+ await this.appStateStore.clear();
636
+ if (shouldClear('contacts'))
637
+ await this.contactStore.clear();
638
+ if (shouldClear('messages'))
639
+ await this.messageStore.clear();
640
+ if (shouldClear('participants'))
641
+ await this.participantsStore.clear();
642
+ if (shouldClear('deviceList'))
643
+ await this.deviceListStore.clear();
644
+ if (shouldClear('retry'))
645
+ await this.retryStore.clear();
646
+ if (shouldClear('signal'))
647
+ await this.signalStore.clear();
648
+ if (shouldClear('senderKey'))
649
+ await this.senderKeyStore.clear();
650
+ if (shouldClear('threads'))
651
+ await this.threadStore.clear();
652
+ if (shouldClear('privacyToken'))
653
+ await this.privacyTokenStore.clear();
654
+ }
655
+ tryEnterIncomingHandler() {
656
+ if (!this.acceptingIncomingEvents) {
695
657
  return false;
696
658
  }
697
- const normalized = error.message.trim().toLowerCase();
698
- return (normalized === 'comms is not connected' ||
699
- normalized === 'websocket is not connected' ||
700
- normalized === 'noise session socket closed' ||
701
- normalized.startsWith('socket closed ('));
659
+ this.activeIncomingHandlers += 1;
660
+ if (this.acceptingIncomingEvents) {
661
+ return true;
662
+ }
663
+ this.leaveIncomingHandler();
664
+ return false;
702
665
  }
703
- enqueueDanglingReceipt(node) {
704
- if (this.danglingReceipts.length >= constants_1.WA_DEFAULTS.MAX_DANGLING_RECEIPTS) {
705
- this.danglingReceipts.shift();
666
+ leaveIncomingHandler() {
667
+ if (this.activeIncomingHandlers <= 0) {
668
+ return;
669
+ }
670
+ this.activeIncomingHandlers -= 1;
671
+ if (this.activeIncomingHandlers === 0) {
672
+ this.notifyIncomingHandlersDrained();
706
673
  }
707
- this.danglingReceipts.push(node.content === undefined
708
- ? {
709
- tag: node.tag,
710
- attrs: { ...node.attrs }
711
- }
712
- : {
713
- tag: node.tag,
714
- attrs: { ...node.attrs },
715
- content: node.content
716
- });
717
674
  }
718
- async clearStoredState() {
719
- await this.authClient.clearStoredCredentials();
720
- await this.appStateStore.clear();
721
- await this.contactStore.clear();
722
- await this.messageStore.clear();
723
- await this.participantsStore.clear();
724
- await this.deviceListStore.clear();
725
- await this.retryStore.clear();
726
- await this.signalStore.clear();
727
- await this.senderKeyStore.clear();
728
- await this.threadStore.clear();
675
+ async pauseIncomingEventsAndWaitDrain() {
676
+ this.acceptingIncomingEvents = false;
677
+ if (this.activeIncomingHandlers === 0) {
678
+ return;
679
+ }
680
+ await new Promise((resolve) => {
681
+ this.incomingHandlersDrainedWaiters[this.incomingHandlersDrainedWaiters.length] =
682
+ resolve;
683
+ });
684
+ }
685
+ notifyIncomingHandlersDrained() {
686
+ if (this.incomingHandlersDrainedWaiters.length === 0) {
687
+ return;
688
+ }
689
+ const waitersLength = this.incomingHandlersDrainedWaiters.length;
690
+ for (let index = 0; index < waitersLength; index += 1) {
691
+ this.incomingHandlersDrainedWaiters[index]();
692
+ }
693
+ this.incomingHandlersDrainedWaiters.length = 0;
729
694
  }
730
695
  handleError(error) {
731
696
  this.logger.error('wa client error', { message: error.message });
732
697
  this.emit('client_error', { error });
733
698
  }
734
- clearCommsBinding() {
735
- this.notifyAppStateKeyShareWaiters(false);
736
- this.comms = null;
737
- this.nodeTransport.bindComms(null);
738
- }
739
- updateClockSkewFromSuccess(serverUnixSeconds) {
740
- const serverMs = serverUnixSeconds * 1000;
741
- const nowMs = Date.now();
742
- this.clockSkewMs = serverMs - nowMs;
743
- this.logger.debug('updated clock skew from success', {
744
- serverUnixSeconds,
745
- clockSkewMs: this.clockSkewMs
746
- });
747
- }
748
699
  }
749
700
  exports.WaClient = WaClient;