@hansaka02/baileys 7.3.2 → 7.3.6

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 (210) hide show
  1. package/lib/Defaults/baileys-version.json +2 -2
  2. package/lib/Defaults/connection.js +51 -0
  3. package/lib/Defaults/constants.js +74 -0
  4. package/lib/Defaults/history.js +19 -0
  5. package/lib/Defaults/index.js +36 -142
  6. package/lib/Defaults/media.js +48 -0
  7. package/lib/Defaults/prefix.js +18 -0
  8. package/lib/Signal/Group/group-session-builder.js +10 -42
  9. package/lib/Signal/Group/group_cipher.js +9 -6
  10. package/lib/Signal/Group/index.js +39 -53
  11. package/lib/Signal/Group/keyhelper.js +8 -41
  12. package/lib/Signal/Group/sender-chain-key.js +5 -18
  13. package/lib/Signal/Group/sender-key-distribution-message.js +7 -7
  14. package/lib/Signal/Group/sender-key-message.js +12 -8
  15. package/lib/Signal/Group/sender-key-record.js +7 -16
  16. package/lib/Signal/Group/sender-key-state.js +15 -61
  17. package/lib/Signal/Group/sender-message-key.js +2 -2
  18. package/lib/Signal/libsignal.js +237 -177
  19. package/lib/Signal/lid-mapping.js +128 -71
  20. package/lib/Socket/Client/types.js +2 -2
  21. package/lib/Socket/Client/websocket.js +25 -16
  22. package/lib/Socket/business.js +46 -33
  23. package/lib/Socket/chats.js +286 -170
  24. package/lib/Socket/community.js +215 -77
  25. package/lib/Socket/groups.js +77 -61
  26. package/lib/Socket/index.js +4 -4
  27. package/lib/Socket/messages-recv.js +629 -457
  28. package/lib/Socket/messages-send.js +645 -656
  29. package/lib/Socket/mex.js +61 -0
  30. package/lib/Socket/newsletter.js +166 -245
  31. package/lib/Socket/socket.js +396 -170
  32. package/lib/Store/index.js +27 -11
  33. package/lib/Store/make-cache-manager-store.js +14 -15
  34. package/lib/Store/make-in-memory-store.js +28 -24
  35. package/lib/Types/LabelAssociation.js +2 -2
  36. package/lib/Types/Message.js +6 -6
  37. package/lib/Types/MexUpdates.js +5 -5
  38. package/lib/Types/Newsletter.js +32 -25
  39. package/lib/Types/State.js +4 -4
  40. package/lib/Types/index.js +28 -12
  41. package/lib/Utils/auth-utils.js +212 -375
  42. package/lib/Utils/baileys-event-stream.js +68 -69
  43. package/lib/Utils/browser-utils.js +43 -0
  44. package/lib/Utils/business.js +63 -53
  45. package/lib/Utils/chat-utils.js +241 -106
  46. package/lib/Utils/crypto.js +25 -45
  47. package/lib/Utils/decode-wa-message.js +361 -311
  48. package/lib/Utils/event-buffer.js +97 -42
  49. package/lib/Utils/generics.js +90 -207
  50. package/lib/Utils/history.js +29 -27
  51. package/lib/Utils/index.js +28 -14
  52. package/lib/Utils/link-preview.js +24 -62
  53. package/lib/Utils/logger.js +5 -5
  54. package/lib/Utils/lt-hash.js +29 -23
  55. package/lib/Utils/make-mutex.js +26 -28
  56. package/lib/Utils/message-retry-manager.js +55 -7
  57. package/lib/Utils/messages-media.js +434 -247
  58. package/lib/Utils/messages.js +963 -917
  59. package/lib/Utils/noise-handler.js +60 -20
  60. package/lib/Utils/pre-key-manager.js +126 -0
  61. package/lib/Utils/process-message.js +216 -141
  62. package/lib/Utils/signal.js +75 -37
  63. package/lib/Utils/use-multi-file-auth-state.js +18 -22
  64. package/lib/Utils/validate-connection.js +96 -66
  65. package/lib/WABinary/constants.js +1268 -1268
  66. package/lib/WABinary/decode.js +62 -34
  67. package/lib/WABinary/encode.js +57 -36
  68. package/lib/WABinary/generic-utils.js +4 -4
  69. package/lib/WABinary/index.js +27 -11
  70. package/lib/WABinary/jid-utils.js +58 -11
  71. package/lib/WAM/constants.js +19064 -11563
  72. package/lib/WAM/encode.js +71 -14
  73. package/lib/WAM/index.js +27 -11
  74. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +20 -16
  75. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  76. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +7 -4
  77. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -2
  78. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -2
  79. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +2 -2
  80. package/lib/WAUSync/Protocols/index.js +27 -11
  81. package/lib/WAUSync/USyncQuery.js +51 -28
  82. package/lib/WAUSync/index.js +27 -11
  83. package/lib/index.js +60 -31
  84. package/package.json +12 -17
  85. package/WAProto/AICommon/AICommon.d.ts +0 -11702
  86. package/WAProto/Adv/Adv.d.ts +0 -643
  87. package/WAProto/BotMetadata/BotMetadata.d.ts +0 -5654
  88. package/WAProto/Cert/Cert.d.ts +0 -613
  89. package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +0 -476
  90. package/WAProto/CompanionReg/CompanionReg.d.ts +0 -1361
  91. package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +0 -577
  92. package/WAProto/E2E/E2E.d.ts +0 -41724
  93. package/WAProto/Ephemeral/Ephemeral.d.ts +0 -114
  94. package/WAProto/HistorySync/HistorySync.d.ts +0 -51700
  95. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +0 -229
  96. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +0 -583
  97. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +0 -42897
  98. package/WAProto/MmsRetry/MmsRetry.d.ts +0 -243
  99. package/WAProto/Protocol/Protocol.d.ts +0 -270
  100. package/WAProto/Reporting/Reporting.d.ts +0 -371
  101. package/WAProto/ServerSync/ServerSync.d.ts +0 -1285
  102. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +0 -1868
  103. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +0 -767
  104. package/WAProto/StatusAttributions/StatusAttributions.d.ts +0 -1027
  105. package/WAProto/SyncAction/SyncAction.d.ts +0 -11193
  106. package/WAProto/UserPassword/UserPassword.d.ts +0 -363
  107. package/WAProto/VnameCert/VnameCert.d.ts +0 -821
  108. package/WAProto/Wa6/Wa6.d.ts +0 -2128
  109. package/WAProto/Web/Web.d.ts +0 -46383
  110. package/WAProto/index.d.ts +0 -55
  111. package/lib/Defaults/index.d.ts +0 -77
  112. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  113. package/lib/Signal/Group/group-session-builder.d.ts +0 -17
  114. package/lib/Signal/Group/group_cipher.d.ts +0 -19
  115. package/lib/Signal/Group/index.d.ts +0 -11
  116. package/lib/Signal/Group/keyhelper.d.ts +0 -16
  117. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  118. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  119. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  120. package/lib/Signal/Group/sender-key-name.d.ts +0 -19
  121. package/lib/Signal/Group/sender-key-record.d.ts +0 -32
  122. package/lib/Signal/Group/sender-key-state.d.ts +0 -44
  123. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  124. package/lib/Signal/libsignal.d.ts +0 -8
  125. package/lib/Signal/lid-mapping.d.ts +0 -28
  126. package/lib/Socket/Client/index.d.ts +0 -2
  127. package/lib/Socket/Client/types.d.ts +0 -16
  128. package/lib/Socket/Client/websocket.d.ts +0 -13
  129. package/lib/Socket/business.d.ts +0 -187
  130. package/lib/Socket/chats.d.ts +0 -97
  131. package/lib/Socket/community.d.ts +0 -129
  132. package/lib/Socket/groups.d.ts +0 -129
  133. package/lib/Socket/index.d.ts +0 -191
  134. package/lib/Socket/messages-recv.d.ts +0 -174
  135. package/lib/Socket/messages-send.d.ts +0 -165
  136. package/lib/Socket/newsletter.d.ts +0 -145
  137. package/lib/Socket/socket.d.ts +0 -45
  138. package/lib/Socket/usync.d.ts +0 -37
  139. package/lib/Socket/usync.js +0 -83
  140. package/lib/Store/index.d.ts +0 -4
  141. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  142. package/lib/Store/make-in-memory-store.d.ts +0 -123
  143. package/lib/Store/make-ordered-dictionary.d.ts +0 -12
  144. package/lib/Store/object-repository.d.ts +0 -10
  145. package/lib/Types/Auth.d.ts +0 -121
  146. package/lib/Types/Bussiness.d.ts +0 -28
  147. package/lib/Types/Call.d.ts +0 -14
  148. package/lib/Types/Chat.d.ts +0 -143
  149. package/lib/Types/Contact.d.ts +0 -23
  150. package/lib/Types/Events.d.ts +0 -226
  151. package/lib/Types/GroupMetadata.d.ts +0 -66
  152. package/lib/Types/Label.d.ts +0 -48
  153. package/lib/Types/LabelAssociation.d.ts +0 -35
  154. package/lib/Types/Message.d.ts +0 -484
  155. package/lib/Types/MexUpdates.d.ts +0 -9
  156. package/lib/Types/Newsletter.d.ts +0 -109
  157. package/lib/Types/Product.d.ts +0 -92
  158. package/lib/Types/Signal.d.ts +0 -98
  159. package/lib/Types/Socket.d.ts +0 -141
  160. package/lib/Types/State.d.ts +0 -41
  161. package/lib/Types/USync.d.ts +0 -26
  162. package/lib/Types/index.d.ts +0 -80
  163. package/lib/Utils/auth-utils.d.ts +0 -21
  164. package/lib/Utils/baileys-event-stream.d.ts +0 -18
  165. package/lib/Utils/business.d.ts +0 -29
  166. package/lib/Utils/chat-utils.d.ts +0 -82
  167. package/lib/Utils/crypto.d.ts +0 -56
  168. package/lib/Utils/decode-wa-message.d.ts +0 -53
  169. package/lib/Utils/event-buffer.d.ts +0 -39
  170. package/lib/Utils/generics.d.ts +0 -117
  171. package/lib/Utils/history.d.ts +0 -23
  172. package/lib/Utils/index.d.ts +0 -20
  173. package/lib/Utils/link-preview.d.ts +0 -23
  174. package/lib/Utils/logger.d.ts +0 -13
  175. package/lib/Utils/lt-hash.d.ts +0 -14
  176. package/lib/Utils/make-mutex.d.ts +0 -9
  177. package/lib/Utils/message-retry-manager.d.ts +0 -88
  178. package/lib/Utils/messages-media.d.ts +0 -135
  179. package/lib/Utils/messages.d.ts +0 -105
  180. package/lib/Utils/noise-handler.d.ts +0 -20
  181. package/lib/Utils/process-message.d.ts +0 -49
  182. package/lib/Utils/signal.d.ts +0 -42
  183. package/lib/Utils/use-mongo-file-auth-state.d.ts +0 -6
  184. package/lib/Utils/use-mongo-file-auth-state.js +0 -84
  185. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  186. package/lib/Utils/use-single-file-auth-state.d.ts +0 -13
  187. package/lib/Utils/use-single-file-auth-state.js +0 -80
  188. package/lib/Utils/validate-connection.d.ts +0 -13
  189. package/lib/WABinary/constants.d.ts +0 -30
  190. package/lib/WABinary/decode.d.ts +0 -9
  191. package/lib/WABinary/encode.d.ts +0 -3
  192. package/lib/WABinary/generic-utils.d.ts +0 -28
  193. package/lib/WABinary/index.d.ts +0 -5
  194. package/lib/WABinary/jid-utils.d.ts +0 -58
  195. package/lib/WABinary/types.d.ts +0 -22
  196. package/lib/WAM/BinaryInfo.d.ts +0 -16
  197. package/lib/WAM/constants.d.ts +0 -47
  198. package/lib/WAM/encode.d.ts +0 -3
  199. package/lib/WAM/index.d.ts +0 -3
  200. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +0 -28
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  202. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -26
  203. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -14
  204. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +0 -10
  205. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -14
  206. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  207. package/lib/WAUSync/USyncQuery.d.ts +0 -31
  208. package/lib/WAUSync/USyncUser.d.ts +0 -12
  209. package/lib/WAUSync/index.d.ts +0 -3
  210. package/lib/index.d.ts +0 -13
@@ -1,42 +1,97 @@
1
1
  "use strict"
2
2
 
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod }
5
- }
6
-
7
3
  Object.defineProperty(exports, "__esModule", { value: true })
8
4
 
9
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
10
- const boom_1 = require("@hapi/boom")
11
- const WAProto_1 = require("../../WAProto")
12
- const Defaults_1 = require("../Defaults")
13
- const Types_1 = require("../Types")
14
- const Utils_1 = require("../Utils")
15
- const make_mutex_1 = require("../Utils/make-mutex")
16
- const WABinary_1 = require("../WABinary")
17
- const WAUSync_1 = require("../WAUSync")
18
- const socket_1 = require("./socket")
5
+ const { default: NodeCache } = require("@cacheable/node-cache")
6
+ const { Boom } = require("@hapi/boom")
7
+ const { proto } = require("../../WAProto")
8
+ const {
9
+ CALL_VIDEO_PREFIX,
10
+ CALL_AUDIO_PREFIX
11
+ } = require("../Defaults/prefix")
12
+ const { DEFAULT_CACHE_TTLS } = require("../Defaults/constants")
13
+ const { PROCESSABLE_HISTORY_TYPES } = require("../Defaults/history")
14
+ const {
15
+ SyncState,
16
+ ALL_WA_PATCH_NAMES
17
+ } = require("../Types")
18
+ const {
19
+ newLTHashState,
20
+ processSyncAction,
21
+ extractSyncdPatches,
22
+ generateProfilePicture,
23
+ decodeSyncdSnapshot,
24
+ decodePatches,
25
+ encodeSyncdPatch,
26
+ chatModificationToAppPatch,
27
+ getHistoryMsg,
28
+ processMessage
29
+ } = require("../Utils")
30
+ const { makeMutex } = require("../Utils/make-mutex")
31
+ const {
32
+ isPnUser,
33
+ getBinaryNodeChild,
34
+ getBinaryNodeChildren,
35
+ jidDecode,
36
+ jidNormalizedUser,
37
+ reduceBinaryNodeToDictionary,
38
+ S_WHATSAPP_NET
39
+ } = require("../WABinary")
40
+ const {
41
+ USyncUser,
42
+ USyncQuery
43
+ } = require("../WAUSync")
44
+ const { makeSocket } = require("./socket")
19
45
  const MAX_SYNC_ATTEMPTS = 2
20
46
 
21
47
  const makeChatsSocket = (config) => {
22
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config
23
- const suki = socket_1.makeSocket(config)
24
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, groupFetchAllParticipating } = suki
48
+ const {
49
+ logger,
50
+ markOnlineOnConnect,
51
+ fireInitQueries,
52
+ appStateMacVerification,
53
+ shouldIgnoreJid,
54
+ shouldSyncHistoryMessage,
55
+ getMessage
56
+ } = config
57
+
58
+ const suki = makeSocket(config)
25
59
 
60
+ const {
61
+ ev,
62
+ ws,
63
+ authState,
64
+ generateMessageTag,
65
+ sendNode,
66
+ query,
67
+ signalRepository,
68
+ onUnexpectedError
69
+ } = suki
70
+
26
71
  let privacySettings
27
- let syncState = Types_1.SyncState.Connecting
72
+ let syncState = SyncState.Connecting
28
73
 
29
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
30
- const processingMutex = make_mutex_1.makeMutex()
74
+ /** this mutex ensures that messages are processed in order */
75
+ const messageMutex = makeMutex()
31
76
 
32
- // Timeout for AwaitingInitialSync State
33
- let awaitingSyncTimeout
77
+ /** this mutex ensures that receipts are processed in order */
78
+ const receiptMutex = makeMutex()
34
79
 
35
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
36
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
37
- useClones: false
38
- })
80
+ /** this mutex ensures that app state patches are processed in order */
81
+ const appStatePatchMutex = makeMutex()
82
+
83
+ /** this mutex ensures that notifications are processed in order */
84
+ const notificationMutex = makeMutex()
85
+
86
+ // Timeout for AwaitingInitialSync state
87
+ let awaitingSyncTimeout
39
88
 
89
+ const placeholderResendCache = config.placeholderResendCache ||
90
+ new NodeCache({
91
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
92
+ useClones: false
93
+ })
94
+
40
95
  if (!config.placeholderResendCache) {
41
96
  config.placeholderResendCache = placeholderResendCache
42
97
  }
@@ -53,14 +108,14 @@ const makeChatsSocket = (config) => {
53
108
  tag: 'iq',
54
109
  attrs: {
55
110
  xmlns: 'privacy',
56
- to: WABinary_1.S_WHATSAPP_NET,
111
+ to: S_WHATSAPP_NET,
57
112
  type: 'get'
58
113
  },
59
114
  content: [
60
115
  { tag: 'privacy', attrs: {} }
61
116
  ]
62
117
  })
63
- privacySettings = WABinary_1.reduceBinaryNodeToDictionary(content?.[0], 'category')
118
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category')
64
119
  }
65
120
  return privacySettings
66
121
  }
@@ -71,7 +126,7 @@ const makeChatsSocket = (config) => {
71
126
  tag: 'iq',
72
127
  attrs: {
73
128
  xmlns: 'privacy',
74
- to: WABinary_1.S_WHATSAPP_NET,
129
+ to: S_WHATSAPP_NET,
75
130
  type: 'set'
76
131
  },
77
132
  content: [{
@@ -124,7 +179,7 @@ const makeChatsSocket = (config) => {
124
179
  tag: 'iq',
125
180
  attrs: {
126
181
  xmlns: 'disappearing_mode',
127
- to: WABinary_1.S_WHATSAPP_NET,
182
+ to: S_WHATSAPP_NET,
128
183
  type: 'set'
129
184
  },
130
185
  content: [{
@@ -141,7 +196,7 @@ const makeChatsSocket = (config) => {
141
196
  tag: 'iq',
142
197
  attrs: {
143
198
  xmlns: 'bot',
144
- to: WABinary_1.S_WHATSAPP_NET,
199
+ to: S_WHATSAPP_NET,
145
200
  type: 'get'
146
201
  },
147
202
  content: [{
@@ -152,13 +207,13 @@ const makeChatsSocket = (config) => {
152
207
  }]
153
208
  })
154
209
 
155
- const botNode = WABinary_1.getBinaryNodeChild(resp, 'bot')
210
+ const botNode = getBinaryNodeChild(resp, 'bot')
156
211
 
157
212
  const botList = []
158
213
 
159
- for(const section of WABinary_1.getBinaryNodeChildren(botNode, 'section')) {
214
+ for(const section of getBinaryNodeChildren(botNode, 'section')) {
160
215
  if(section.attrs.type === 'all') {
161
- for(const bot of WABinary_1.getBinaryNodeChildren(section, 'bot')) {
216
+ for(const bot of getBinaryNodeChildren(section, 'bot')) {
162
217
  botList.push({
163
218
  jid: bot.attrs.jid,
164
219
  personaId: bot.attrs['persona_id']
@@ -171,16 +226,16 @@ const makeChatsSocket = (config) => {
171
226
 
172
227
  const getLidUser = async (jid) => {
173
228
  if (!jid) {
174
- throw new boom_1.Boom('Please input a jid user')
229
+ throw new Boom('Please input a jid user')
175
230
  }
176
231
 
177
- if (!WABinary_1.isJidUser(jid)) {
178
- throw new boom_1.Boom('Invalid JID: Not a user JID!')
232
+ if (!isPnUser(jid)) {
233
+ throw new Boom('Invalid JID: Not a user JID!')
179
234
  }
180
235
 
181
- const targetJid = WABinary_1.jidNormalizedUser(jid)
236
+ const targetJid = jidNormalizedUser(jid)
182
237
 
183
- const usyncQuery = new WAUSync_1.USyncQuery()
238
+ const usyncQuery = new USyncQuery()
184
239
  usyncQuery.protocols.push({
185
240
  name: 'lid',
186
241
  getQueryElement: () => ({
@@ -203,10 +258,10 @@ const makeChatsSocket = (config) => {
203
258
  }
204
259
 
205
260
  const fetchStatus = async (...jids) => {
206
- const usyncQuery = new WAUSync_1.USyncQuery().withStatusProtocol()
261
+ const usyncQuery = new USyncQuery().withStatusProtocol()
207
262
 
208
263
  for (const jid of jids) {
209
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
264
+ usyncQuery.withUser(new USyncUser().withId(jid))
210
265
  }
211
266
 
212
267
  const result = await suki.executeUSyncQuery(usyncQuery)
@@ -215,40 +270,46 @@ const makeChatsSocket = (config) => {
215
270
  return result.list
216
271
  }
217
272
  }
273
+
218
274
  const fetchDisappearingDuration = async (...jids) => {
219
- const usyncQuery = new WAUSync_1.USyncQuery().withDisappearingModeProtocol()
275
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
220
276
 
221
277
  for (const jid of jids) {
222
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
278
+ usyncQuery.withUser(new USyncUser().withId(jid))
223
279
  }
224
280
 
225
281
  const result = await suki.executeUSyncQuery(usyncQuery)
282
+
226
283
  if (result) {
227
284
  return result.list
228
285
  }
229
286
  }
230
287
 
231
288
  /** update the profile picture for yourself or a group */
232
- const updateProfilePicture = async (jid, content) => {
289
+ const updateProfilePicture = async (jid, content, dimensions) => {
233
290
  let targetJid
234
291
 
235
292
  if (!jid) {
236
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
293
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
294
+ }
295
+
296
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
297
+ targetJid = jidNormalizedUser(jid) // in case it is someone other than us
237
298
  }
238
299
 
239
- if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
240
- targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
300
+ else {
301
+ targetJid = undefined
241
302
  }
242
303
 
243
- const { img } = await Utils_1.generateProfilePicture(content)
304
+ const { img } = await generateProfilePicture(content, dimensions)
244
305
 
245
306
  await query({
246
307
  tag: 'iq',
247
308
  attrs: {
248
- target: targetJid,
249
- to: WABinary_1.S_WHATSAPP_NET,
309
+ to: S_WHATSAPP_NET,
250
310
  type: 'set',
251
- xmlns: 'w:profile:picture'
311
+ xmlns: 'w:profile:picture',
312
+ ...(targetJid ? { target: targetJid } : {})
252
313
  },
253
314
  content: [
254
315
  {
@@ -265,20 +326,24 @@ const makeChatsSocket = (config) => {
265
326
  let targetJid
266
327
 
267
328
  if (!jid) {
268
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
329
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
269
330
  }
270
331
 
271
- if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
272
- targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
332
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
333
+ targetJid = jidNormalizedUser(jid) // in case it is someone other than us
334
+ }
335
+
336
+ else {
337
+ targetJid = undefined
273
338
  }
274
339
 
275
340
  await query({
276
341
  tag: 'iq',
277
342
  attrs: {
278
- target: targetJid,
279
- to: WABinary_1.S_WHATSAPP_NET,
343
+ to: S_WHATSAPP_NET,
280
344
  type: 'set',
281
- xmlns: 'w:profile:picture'
345
+ xmlns: 'w:profile:picture',
346
+ ...(targetJid ? { target: targetJid } : {})
282
347
  }
283
348
  })
284
349
  }
@@ -288,7 +353,7 @@ const makeChatsSocket = (config) => {
288
353
  await query({
289
354
  tag: 'iq',
290
355
  attrs: {
291
- to: WABinary_1.S_WHATSAPP_NET,
356
+ to: S_WHATSAPP_NET,
292
357
  type: 'set',
293
358
  xmlns: 'status'
294
359
  },
@@ -311,14 +376,14 @@ const makeChatsSocket = (config) => {
311
376
  tag: 'iq',
312
377
  attrs: {
313
378
  xmlns: 'blocklist',
314
- to: WABinary_1.S_WHATSAPP_NET,
379
+ to: S_WHATSAPP_NET,
315
380
  type: 'get'
316
381
  }
317
382
  })
318
383
 
319
- const listNode = WABinary_1.getBinaryNodeChild(result, 'list')
384
+ const listNode = getBinaryNodeChild(result, 'list')
320
385
 
321
- return WABinary_1.getBinaryNodeChildren(listNode, 'item').map((n) => n.attrs.jid)
386
+ return getBinaryNodeChildren(listNode, 'item').map((n) => n.attrs.jid)
322
387
  }
323
388
 
324
389
  const updateBlockStatus = async (jid, action) => {
@@ -326,7 +391,7 @@ const makeChatsSocket = (config) => {
326
391
  tag: 'iq',
327
392
  attrs: {
328
393
  xmlns: 'blocklist',
329
- to: WABinary_1.S_WHATSAPP_NET,
394
+ to: S_WHATSAPP_NET,
330
395
  type: 'set'
331
396
  },
332
397
  content: [
@@ -359,19 +424,19 @@ const makeChatsSocket = (config) => {
359
424
  }]
360
425
  })
361
426
 
362
- const profileNode = WABinary_1.getBinaryNodeChild(results, 'business_profile')
427
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
363
428
 
364
- const profiles = WABinary_1.getBinaryNodeChild(profileNode, 'profile')
429
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
365
430
 
366
431
  if (profiles) {
367
- const address = WABinary_1.getBinaryNodeChild(profiles, 'address')
368
- const description = WABinary_1.getBinaryNodeChild(profiles, 'description')
369
- const website = WABinary_1.getBinaryNodeChild(profiles, 'website')
370
- const email = WABinary_1.getBinaryNodeChild(profiles, 'email')
371
- const category = WABinary_1.getBinaryNodeChild(WABinary_1.getBinaryNodeChild(profiles, 'categories'), 'category')
372
- const businessHours = WABinary_1.getBinaryNodeChild(profiles, 'business_hours')
432
+ const address = getBinaryNodeChild(profiles, 'address')
433
+ const description = getBinaryNodeChild(profiles, 'description')
434
+ const website = getBinaryNodeChild(profiles, 'website')
435
+ const email = getBinaryNodeChild(profiles, 'email')
436
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
437
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
373
438
  const businessHoursConfig = businessHours
374
- ? WABinary_1.getBinaryNodeChildren(businessHours, 'business_hours_config')
439
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
375
440
  : undefined
376
441
  const websiteStr = website?.content?.toString()
377
442
 
@@ -395,7 +460,7 @@ const makeChatsSocket = (config) => {
395
460
  await sendNode({
396
461
  tag: 'iq',
397
462
  attrs: {
398
- to: WABinary_1.S_WHATSAPP_NET,
463
+ to: S_WHATSAPP_NET,
399
464
  type: 'set',
400
465
  xmlns: 'urn:xmpp:whatsapp:dirty',
401
466
  id: generateMessageTag(),
@@ -415,7 +480,7 @@ const makeChatsSocket = (config) => {
415
480
  const newAppStateChunkHandler = (isInitialSync) => {
416
481
  return {
417
482
  onMutation(mutation) {
418
- Utils_1.processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
483
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
419
484
  }
420
485
  }
421
486
  }
@@ -425,10 +490,13 @@ const makeChatsSocket = (config) => {
425
490
  // otherwise when we resync from scratch -- all notifications will fire
426
491
  const initialVersionMap = {}
427
492
  const globalMutationMap = {}
493
+
428
494
  await authState.keys.transaction(async () => {
429
495
  const collectionsToHandle = new Set(collections)
496
+
430
497
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
431
498
  const attemptsMap = {}
499
+
432
500
  // keep executing till all collections are done
433
501
  // sometimes a single patch request will not return all the patches (God knows why)
434
502
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -438,15 +506,19 @@ const makeChatsSocket = (config) => {
438
506
 
439
507
  for (const name of collectionsToHandle) {
440
508
  const result = await authState.keys.get('app-state-sync-version', [name])
509
+
441
510
  let state = result[name]
511
+
442
512
  if (state) {
443
513
  if (typeof initialVersionMap[name] === 'undefined') {
444
514
  initialVersionMap[name] = state.version
445
515
  }
446
516
  }
517
+
447
518
  else {
448
- state = Utils_1.newLTHashState()
519
+ state = newLTHashState()
449
520
  }
521
+
450
522
  states[name] = state
451
523
  logger.info(`resyncing ${name} from v${state.version}`)
452
524
  nodes.push({
@@ -455,7 +527,7 @@ const makeChatsSocket = (config) => {
455
527
  name,
456
528
  version: state.version.toString(),
457
529
  // return snapshot if being synced from scratch
458
- 'return_snapshot': (!state.version).toString()
530
+ return_snapshot: (!state.version).toString()
459
531
  }
460
532
  })
461
533
  }
@@ -463,7 +535,7 @@ const makeChatsSocket = (config) => {
463
535
  const result = await query({
464
536
  tag: 'iq',
465
537
  attrs: {
466
- to: WABinary_1.S_WHATSAPP_NET,
538
+ to: S_WHATSAPP_NET,
467
539
  xmlns: 'w:sync:app:state',
468
540
  type: 'set'
469
541
  },
@@ -477,62 +549,76 @@ const makeChatsSocket = (config) => {
477
549
  })
478
550
 
479
551
  // extract from binary node
480
- const decoded = await Utils_1.extractSyncdPatches(result, config?.options)
552
+ const decoded = await extractSyncdPatches(result, config?.options)
481
553
 
482
554
  for (const key in decoded) {
483
555
  const name = key
484
556
  const { patches, hasMorePatches, snapshot } = decoded[name]
557
+
485
558
  try {
486
559
  if (snapshot) {
487
- const { state: newState, mutationMap } = await Utils_1.decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot)
560
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot)
561
+
488
562
  states[name] = newState
563
+
489
564
  Object.assign(globalMutationMap, mutationMap)
565
+
490
566
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
567
+
491
568
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
492
569
  }
493
570
 
494
571
  // only process if there are syncd patches
495
572
  if (patches.length) {
496
- const { state: newState, mutationMap } = await Utils_1.decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
573
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
574
+
497
575
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
576
+
498
577
  logger.info(`synced ${name} to v${newState.version}`)
578
+
499
579
  initialVersionMap[name] = newState.version
580
+
500
581
  Object.assign(globalMutationMap, mutationMap)
501
582
  }
502
583
 
503
584
  if (hasMorePatches) {
504
585
  logger.info(`${name} has more patches...`)
505
- }
506
- else { // collection is done with sync
586
+ }
587
+
588
+ else {
589
+ // collection is done with sync
507
590
  collectionsToHandle.delete(name)
508
591
  }
509
- }
592
+ }
593
+
510
594
  catch (error) {
511
595
  // if retry attempts overshoot
512
596
  // or key not found
513
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
514
- || error.output?.statusCode === 404
515
- || error.name === 'TypeError'
597
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
598
+ error.output?.statusCode === 404 ||
599
+ error.name === 'TypeError'
600
+
516
601
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`)
602
+
517
603
  await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
604
+
518
605
  // increment number of retries
519
606
  attemptsMap[name] = (attemptsMap[name] || 0) + 1
520
607
 
521
608
  if (isIrrecoverableError) {
522
609
  // stop retrying
523
- collectionsToHandle.delete(name)
610
+ collectionsToHandle.delete(name);
524
611
  }
525
612
  }
526
613
  }
527
614
  }
528
615
  }, authState?.creds?.me?.id || 'resync-app-state')
529
-
530
616
  const { onMutation } = newAppStateChunkHandler(isInitialSync)
531
617
 
532
618
  for (const key in globalMutationMap) {
533
619
  onMutation(globalMutationMap[key])
534
620
  }
535
- })
621
+ })
536
622
 
537
623
  // source: https://github.com/WhiskeySockets/Baileys/pull/1677
538
624
  const createCallLink = async (type, event, timeoutMs) => {
@@ -562,10 +648,10 @@ const makeChatsSocket = (config) => {
562
648
  }]
563
649
  }, timeoutMs)
564
650
 
565
- const child = WABinary_1.getBinaryNodeChild(result, 'link_create')
651
+ const child = getBinaryNodeChild(result, 'link_create')
566
652
  const token = child?.attrs?.token
567
653
 
568
- return type === 'audio' ? Defaults_1.CALL_AUDIO_PREFIX + token : Defaults_1.CALL_VIDEO_PREFIX + token
654
+ return type === 'audio' ? CALL_AUDIO_PREFIX + token : CALL_VIDEO_PREFIX + token
569
655
  }
570
656
 
571
657
  const sendPresenceUpdate = async (type, toJid) => {
@@ -587,7 +673,7 @@ const makeChatsSocket = (config) => {
587
673
  })
588
674
  }
589
675
  else {
590
- const { server } = WABinary_1.jidDecode(toJid)
676
+ const { server } = jidDecode(toJid)
591
677
 
592
678
  await sendNode({
593
679
  tag: 'chatstate',
@@ -629,10 +715,11 @@ const makeChatsSocket = (config) => {
629
715
 
630
716
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
631
717
  let presence
718
+
632
719
  const jid = attrs.from
633
720
  const participant = attrs.participant || attrs.from
634
721
 
635
- if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
722
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
636
723
  return
637
724
  }
638
725
 
@@ -645,6 +732,7 @@ const makeChatsSocket = (config) => {
645
732
 
646
733
  else if (Array.isArray(content)) {
647
734
  const [firstChild] = content
735
+
648
736
  let type = firstChild.tag
649
737
 
650
738
  if (type === 'paused') {
@@ -672,25 +760,28 @@ const makeChatsSocket = (config) => {
672
760
  const myAppStateKeyId = authState.creds.myAppStateKeyId
673
761
 
674
762
  if (!myAppStateKeyId) {
675
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 })
763
+ throw new Boom('App state key not present!', { statusCode: 400 })
676
764
  }
677
765
 
678
766
  let initial
679
767
  let encodeResult
680
768
 
681
- await processingMutex.mutex(async () => {
769
+ await appStatePatchMutex.mutex(async () => {
682
770
  await authState.keys.transaction(async () => {
683
771
  logger.debug({ patch: patchCreate }, 'applying app patch')
772
+
684
773
  await resyncAppState([name], false)
774
+
685
775
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
686
- initial = currentSyncVersion || Utils_1.newLTHashState()
687
- encodeResult = await Utils_1.encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
688
- const { patch, state } = encodeResult
689
776
 
777
+ initial = currentSyncVersion || newLTHashState()
778
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
779
+
780
+ const { patch, state } = encodeResult
690
781
  const node = {
691
782
  tag: 'iq',
692
783
  attrs: {
693
- to: WABinary_1.S_WHATSAPP_NET,
784
+ to: S_WHATSAPP_NET,
694
785
  type: 'set',
695
786
  xmlns: 'w:sync:app:state'
696
787
  },
@@ -704,13 +795,13 @@ const makeChatsSocket = (config) => {
704
795
  attrs: {
705
796
  name,
706
797
  version: (state.version - 1).toString(),
707
- 'return_snapshot': 'false'
798
+ return_snapshot: 'false'
708
799
  },
709
800
  content: [
710
801
  {
711
802
  tag: 'patch',
712
803
  attrs: {},
713
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
804
+ content: proto.SyncdPatch.encode(patch).finish()
714
805
  }
715
806
  ]
716
807
  }
@@ -718,6 +809,7 @@ const makeChatsSocket = (config) => {
718
809
  }
719
810
  ]
720
811
  }
812
+
721
813
  await query(node)
722
814
  await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
723
815
  }, authState?.creds?.me?.id || 'app-patch')
@@ -725,7 +817,7 @@ const makeChatsSocket = (config) => {
725
817
 
726
818
  if (config.emitOwnEvents) {
727
819
  const { onMutation } = newAppStateChunkHandler(false)
728
- const { mutationMap } = await Utils_1.decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger)
820
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger)
729
821
 
730
822
  for (const key in mutationMap) {
731
823
  onMutation(mutationMap[key])
@@ -735,33 +827,39 @@ const makeChatsSocket = (config) => {
735
827
 
736
828
  /** sending non-abt props may fix QR scan fail if server expects */
737
829
  const fetchProps = async () => {
830
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
738
831
  const resultNode = await query({
739
832
  tag: 'iq',
740
833
  attrs: {
741
- to: WABinary_1.S_WHATSAPP_NET,
834
+ to: S_WHATSAPP_NET,
742
835
  xmlns: 'w',
743
- type: 'get',
836
+ type: 'get'
744
837
  },
745
838
  content: [
746
- { tag: 'props', attrs: {
839
+ {
840
+ tag: 'props',
841
+ attrs: {
747
842
  protocol: '2',
748
843
  hash: authState?.creds?.lastPropHash || ''
749
- } }
844
+ }
845
+ }
750
846
  ]
751
847
  })
752
848
 
753
- const propsNode = WABinary_1.getBinaryNodeChild(resultNode, 'props')
849
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
754
850
  let props = {}
755
851
 
756
852
  if (propsNode) {
757
- if (propsNode.attrs?.hash) { // on some clients, the hash is returning as undefined
853
+ if (propsNode.attrs?.hash) {
854
+ // on some clients, the hash is returning as undefined
758
855
  authState.creds.lastPropHash = propsNode?.attrs?.hash
759
856
  ev.emit('creds.update', authState.creds)
760
857
  }
761
858
 
762
- props = WABinary_1.reduceBinaryNodeToDictionary(propsNode, 'prop')
859
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
763
860
  }
764
861
  logger.debug('fetched props')
862
+
765
863
  return props
766
864
  }
767
865
 
@@ -771,7 +869,7 @@ const makeChatsSocket = (config) => {
771
869
  * requires the last messages till the last message received required for archive & unread
772
870
  */
773
871
  const chatModify = (mod, jid) => {
774
- const patch = Utils_1.chatModificationToAppPatch(mod, jid)
872
+ const patch = chatModificationToAppPatch(mod, jid)
775
873
  return appPatch(patch)
776
874
  }
777
875
 
@@ -918,9 +1016,11 @@ const makeChatsSocket = (config) => {
918
1016
 
919
1017
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
920
1018
  ev.emit('messages.upsert', { messages: [msg], type })
1019
+
921
1020
  if (!!msg.pushName) {
922
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid)
923
- jid = WABinary_1.jidNormalizedUser(jid)
1021
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
1022
+
1023
+ jid = jidNormalizedUser(jid)
924
1024
 
925
1025
  if (!msg.key.fromMe) {
926
1026
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
@@ -932,42 +1032,51 @@ const makeChatsSocket = (config) => {
932
1032
  }
933
1033
  }
934
1034
 
935
- const historyMsg = Utils_1.getHistoryMsg(msg.message)
1035
+ const historyMsg = getHistoryMsg(msg.message)
936
1036
  const shouldProcessHistoryMsg = historyMsg
937
- ? (shouldSyncHistoryMessage(historyMsg)
938
- && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
1037
+ ? shouldSyncHistoryMessage(historyMsg) &&
1038
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
939
1039
  : false
940
1040
 
941
- if (historyMsg && syncState === Types_1.SyncState.AwaitingInitialSync) {
1041
+ // State machine: decide on sync and flush
1042
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
942
1043
  if (awaitingSyncTimeout) {
943
- clearTimeout(awaitingSyncTimeout)
944
- awaitingSyncTimeout = undefined
1044
+ clearTimeout(awaitingSyncTimeout)
1045
+ awaitingSyncTimeout = undefined
945
1046
  }
946
1047
 
947
1048
  if (shouldProcessHistoryMsg) {
948
- syncState = Types_1.SyncState.Syncing
949
- logger.info('Transitioned to Syncing state')
950
- // Let doAppStateSync handle the final flush after it`s done
951
- } else {
952
- syncState = Types_1.SyncState.Online
953
- logger.info('History sync skipped, transitioning to Online state and flushing buffer')
954
- ev.flush()
1049
+ syncState = SyncState.Syncing
1050
+ logger.info('Transitioned to Syncing state')
1051
+ // Let doAppStateSync handle the final flush after it's done
1052
+ }
1053
+
1054
+ else {
1055
+ syncState = SyncState.Online
1056
+
1057
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
1058
+
1059
+ ev.flush()
955
1060
  }
956
1061
  }
957
1062
 
958
1063
  const doAppStateSync = async () => {
959
- if (syncState === Types_1.SyncState.Syncing) {
960
- logger.info('Doing app state sync')
961
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true)
962
-
963
- // Sync is complete, go online and flush everything
964
- syncState = Types_1.SyncState.Online
965
- logger.info('App state sync complete, transitioning to Online state and flushing buffer')
966
- ev.flush()
967
-
968
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
969
- ev.emit('creds.update', { accountSyncCounter })
970
- }
1064
+ if (syncState === SyncState.Syncing) {
1065
+ logger.info('Doing app state sync')
1066
+
1067
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
1068
+
1069
+ // Sync is complete, go online and flush everything
1070
+ syncState = SyncState.Online
1071
+
1072
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
1073
+
1074
+ ev.flush()
1075
+
1076
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
1077
+
1078
+ ev.emit('creds.update', { accountSyncCounter })
1079
+ }
971
1080
  }
972
1081
 
973
1082
  await Promise.all([
@@ -976,8 +1085,8 @@ const makeChatsSocket = (config) => {
976
1085
  await doAppStateSync()
977
1086
  }
978
1087
  })(),
979
- Utils_1.processMessage(msg, {
980
- signalRepository,
1088
+ processMessage(msg, {
1089
+ signalRepository,
981
1090
  shouldProcessHistoryMsg,
982
1091
  placeholderResendCache,
983
1092
  ev,
@@ -985,36 +1094,39 @@ const makeChatsSocket = (config) => {
985
1094
  keyStore: authState.keys,
986
1095
  logger,
987
1096
  options: config.options,
988
- getMessage: config.getMessage,
1097
+ getMessage
989
1098
  })
990
1099
  ])
991
1100
 
992
- if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === Types_1.SyncState.Syncing) {
993
- logger.info('App state sync key arrived, triggering app state sync')
994
- await doAppStateSync()
1101
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1102
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1103
+ logger.info('App state sync key arrived, triggering app state sync')
1104
+ await doAppStateSync()
995
1105
  }
996
1106
  })
997
1107
 
998
1108
  ws.on('CB:presence', handlePresenceUpdate)
999
1109
  ws.on('CB:chatstate', handlePresenceUpdate)
1000
1110
  ws.on('CB:ib,,dirty', async (node) => {
1001
- const { attrs } = WABinary_1.getBinaryNodeChild(node, 'dirty')
1111
+ const { attrs } = getBinaryNodeChild(node, 'dirty')
1002
1112
  const type = attrs.type
1003
1113
 
1004
1114
  switch (type) {
1005
1115
  case 'account_sync':
1006
1116
  if (attrs.timestamp) {
1007
1117
  let { lastAccountSyncTimestamp } = authState.creds
1118
+
1008
1119
  if (lastAccountSyncTimestamp) {
1009
1120
  await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
1010
1121
  }
1122
+
1011
1123
  lastAccountSyncTimestamp = +attrs.timestamp
1124
+
1012
1125
  ev.emit('creds.update', { lastAccountSyncTimestamp })
1013
1126
  }
1014
1127
  break
1015
1128
  case 'groups':
1016
- await groupFetchAllParticipating()
1017
- await cleanDirtyBits('groups')
1129
+ // handled in groups.js
1018
1130
  break
1019
1131
  default:
1020
1132
  logger.info({ node }, 'received unknown sync')
@@ -1025,45 +1137,46 @@ const makeChatsSocket = (config) => {
1025
1137
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1026
1138
  if (connection === 'open') {
1027
1139
  if (fireInitQueries) {
1028
- executeInitQueries()
1029
- .catch(error => onUnexpectedError(error, 'init queries'))
1140
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
1030
1141
  }
1031
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
1032
- .catch(error => onUnexpectedError(error, 'presence update requests'))
1142
+
1143
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'))
1033
1144
  }
1034
1145
 
1035
- if (!receivedPendingNotifications || syncState !== Types_1.SyncState.Connecting) {
1036
- return
1146
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1147
+ return
1037
1148
  }
1038
1149
 
1039
- syncState = Types_1.AwaitingInitialSync
1040
- logger.info('Connection is now AwaitingInitialSync, buffering events')
1041
- ev.buffer()
1150
+ syncState = SyncState.AwaitingInitialSync
1151
+
1152
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
1153
+ ev.buffer()
1042
1154
 
1043
- const willSyncHistory = shouldSyncHistoryMessage(WAProto_1.proto.Message.HistorySyncNotification.fromObject({
1044
- syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
1045
- }))
1155
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1156
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1157
+ }))
1046
1158
 
1047
1159
  if (!willSyncHistory) {
1048
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
1049
- syncState = Types_1.SyncState.Online
1050
- setTimeout(() => ev.flush(), 0)
1051
- return
1160
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
1161
+ syncState = SyncState.Online
1162
+ setTimeout(() => ev.flush(), 0)
1163
+ return
1052
1164
  }
1053
1165
 
1054
- logger.info('History sync is enabled, awaiting notification with a 20s timeout.')
1166
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.')
1055
1167
 
1056
1168
  if (awaitingSyncTimeout) {
1057
- clearTimeout(awaitingSyncTimeout)
1169
+ clearTimeout(awaitingSyncTimeout);
1058
1170
  }
1059
1171
 
1060
1172
  awaitingSyncTimeout = setTimeout(() => {
1061
- if (syncState === Types_1.SyncState.AwaitingInitialSync) {
1062
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
1063
- syncState = Types_1.SyncState.Online
1064
- ev.flush()
1065
- }
1066
- }, 20_000)
1173
+ if (syncState === SyncState.AwaitingInitialSync) {
1174
+ // TODO: investigate
1175
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
1176
+ syncState = SyncState.Online
1177
+ ev.flush()
1178
+ }
1179
+ }, 20000)
1067
1180
  })
1068
1181
 
1069
1182
  return {
@@ -1071,7 +1184,6 @@ const makeChatsSocket = (config) => {
1071
1184
  star,
1072
1185
  addOrEditContact,
1073
1186
  removeContact,
1074
- processingMutex,
1075
1187
  fetchPrivacySettings,
1076
1188
  upsertMessage,
1077
1189
  appPatch,
@@ -1079,6 +1191,10 @@ const makeChatsSocket = (config) => {
1079
1191
  sendPresenceUpdate,
1080
1192
  presenceSubscribe,
1081
1193
  getBotListV2,
1194
+ messageMutex,
1195
+ receiptMutex,
1196
+ appStatePatchMutex,
1197
+ notificationMutex,
1082
1198
  getLidUser,
1083
1199
  fetchBlocklist,
1084
1200
  fetchStatus,