@hbmodsofc/baileys 1.7.7 → 2.0.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 (155) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/index.js +157084 -24729
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.d.ts +8 -12
  5. package/lib/Defaults/index.js +124 -90
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/group_cipher.d.ts +1 -0
  8. package/lib/Signal/Group/group_cipher.js +39 -28
  9. package/lib/Signal/Group/queue-job.d.ts +1 -0
  10. package/lib/Signal/Group/queue-job.js +57 -0
  11. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  12. package/lib/Signal/Group/sender-chain-key.js +2 -9
  13. package/lib/Signal/Group/sender-key-distribution-message.js +3 -3
  14. package/lib/Signal/Group/sender-key-message.js +3 -3
  15. package/lib/Signal/Group/sender-key-state.d.ts +4 -4
  16. package/lib/Signal/Group/sender-key-state.js +16 -47
  17. package/lib/Signal/libsignal.d.ts +3 -7
  18. package/lib/Signal/libsignal.js +39 -224
  19. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +3 -1
  20. package/lib/Socket/Client/index.d.ts +3 -2
  21. package/lib/Socket/Client/index.js +3 -2
  22. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  23. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  24. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  25. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +16 -10
  26. package/lib/Socket/business.d.ts +78 -94
  27. package/lib/Socket/business.js +11 -130
  28. package/lib/Socket/chats.d.ts +233 -63
  29. package/lib/Socket/chats.js +184 -234
  30. package/lib/Socket/groups.d.ts +41 -62
  31. package/lib/Socket/groups.js +64 -76
  32. package/lib/Socket/hbmods.d.ts +253 -0
  33. package/lib/Socket/hbmods.js +1 -0
  34. package/lib/Socket/index.d.ts +83 -129
  35. package/lib/Socket/index.js +6 -13
  36. package/lib/Socket/messages-recv.d.ts +48 -59
  37. package/lib/Socket/messages-recv.js +371 -516
  38. package/lib/Socket/messages-send.d.ts +67 -86
  39. package/lib/Socket/messages-send.js +1 -1091
  40. package/lib/Socket/newsletter.d.ts +64 -76
  41. package/lib/Socket/newsletter.js +1 -184
  42. package/lib/Socket/registration.d.ts +267 -0
  43. package/lib/Socket/registration.js +166 -0
  44. package/lib/Socket/socket.d.ts +13 -19
  45. package/lib/Socket/socket.js +1 -805
  46. package/lib/Socket/usync.d.ts +36 -0
  47. package/lib/Socket/usync.js +70 -0
  48. package/lib/Types/Auth.d.ts +10 -4
  49. package/lib/Types/Call.d.ts +1 -1
  50. package/lib/Types/Chat.d.ts +9 -29
  51. package/lib/Types/Chat.js +1 -7
  52. package/lib/Types/Contact.d.ts +1 -5
  53. package/lib/Types/Events.d.ts +14 -55
  54. package/lib/Types/GroupMetadata.d.ts +5 -15
  55. package/lib/Types/Label.d.ts +0 -11
  56. package/lib/Types/Label.js +1 -1
  57. package/lib/Types/LabelAssociation.js +1 -1
  58. package/lib/Types/Message.d.ts +49 -75
  59. package/lib/Types/Message.js +7 -10
  60. package/lib/Types/Newsletter.d.ts +98 -129
  61. package/lib/Types/Newsletter.js +38 -33
  62. package/lib/Types/Product.d.ts +1 -1
  63. package/lib/Types/Signal.d.ts +1 -29
  64. package/lib/Types/Socket.d.ts +22 -48
  65. package/lib/Types/State.d.ts +2 -13
  66. package/lib/Types/State.js +0 -12
  67. package/lib/Types/USync.d.ts +1 -1
  68. package/lib/Types/index.d.ts +3 -10
  69. package/lib/Types/index.js +2 -2
  70. package/lib/Utils/auth-utils.d.ts +3 -3
  71. package/lib/Utils/auth-utils.js +102 -378
  72. package/lib/Utils/baileys-event-stream.js +1 -1
  73. package/lib/Utils/business.d.ts +2 -2
  74. package/lib/Utils/business.js +13 -19
  75. package/lib/Utils/chat-utils.d.ts +22 -21
  76. package/lib/Utils/chat-utils.js +154 -201
  77. package/lib/Utils/crypto.d.ts +19 -18
  78. package/lib/Utils/crypto.js +37 -78
  79. package/lib/Utils/decode-wa-message.d.ts +7 -34
  80. package/lib/Utils/decode-wa-message.js +66 -138
  81. package/lib/Utils/event-buffer.d.ts +8 -6
  82. package/lib/Utils/event-buffer.js +43 -81
  83. package/lib/Utils/generics.d.ts +27 -27
  84. package/lib/Utils/generics.js +133 -128
  85. package/lib/Utils/history.d.ts +5 -9
  86. package/lib/Utils/history.js +23 -17
  87. package/lib/Utils/index.d.ts +0 -2
  88. package/lib/Utils/index.js +0 -2
  89. package/lib/Utils/link-preview.d.ts +4 -4
  90. package/lib/Utils/link-preview.js +12 -40
  91. package/lib/Utils/logger.d.ts +3 -11
  92. package/lib/Utils/lt-hash.d.ts +8 -8
  93. package/lib/Utils/lt-hash.js +24 -23
  94. package/lib/Utils/make-mutex.d.ts +2 -2
  95. package/lib/Utils/make-mutex.js +2 -3
  96. package/lib/Utils/messages-media.d.ts +41 -37
  97. package/lib/Utils/messages-media.js +368 -252
  98. package/lib/Utils/messages.d.ts +15 -13
  99. package/lib/Utils/messages.js +261 -274
  100. package/lib/Utils/noise-handler.d.ts +15 -13
  101. package/lib/Utils/noise-handler.js +26 -20
  102. package/lib/Utils/process-message.d.ts +8 -9
  103. package/lib/Utils/process-message.js +93 -157
  104. package/lib/Utils/signal.d.ts +5 -6
  105. package/lib/Utils/signal.js +29 -37
  106. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  107. package/lib/Utils/use-multi-file-auth-state.js +7 -12
  108. package/lib/Utils/validate-connection.d.ts +6 -5
  109. package/lib/Utils/validate-connection.js +97 -39
  110. package/lib/WABinary/constants.d.ts +27 -24
  111. package/lib/WABinary/constants.js +13 -1276
  112. package/lib/WABinary/decode.d.ts +4 -3
  113. package/lib/WABinary/decode.js +14 -28
  114. package/lib/WABinary/encode.d.ts +2 -1
  115. package/lib/WABinary/encode.js +147 -134
  116. package/lib/WABinary/generic-utils.d.ts +7 -4
  117. package/lib/WABinary/generic-utils.js +125 -40
  118. package/lib/WABinary/jid-utils.d.ts +8 -13
  119. package/lib/WABinary/jid-utils.js +16 -27
  120. package/lib/WAM/BinaryInfo.d.ts +11 -2
  121. package/lib/WAM/constants.d.ts +2 -3
  122. package/lib/WAM/constants.js +2359 -2252
  123. package/lib/WAM/encode.d.ts +2 -1
  124. package/lib/WAM/encode.js +11 -8
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +2 -2
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +4 -3
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  128. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +5 -5
  129. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  130. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +5 -5
  131. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +6 -5
  133. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +2 -2
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -1
  135. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -4
  136. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +3 -11
  137. package/lib/WAUSync/USyncQuery.d.ts +2 -2
  138. package/lib/WAUSync/USyncQuery.js +15 -19
  139. package/lib/WAUSync/USyncUser.d.ts +5 -5
  140. package/lib/WAUSync/index.d.ts +1 -1
  141. package/lib/WAUSync/index.js +1 -1
  142. package/package.json +102 -102
  143. package/lib/Signal/lid-mapping.d.ts +0 -26
  144. package/lib/Signal/lid-mapping.js +0 -146
  145. package/lib/Socket/communities.d.ts +0 -232
  146. package/lib/Socket/communities.js +0 -402
  147. package/lib/Socket/mex.d.ts +0 -2
  148. package/lib/Socket/mex.js +0 -45
  149. package/lib/Types/Bussines.d.ts +0 -24
  150. package/lib/Types/Bussines.js +0 -2
  151. package/lib/Utils/lidToJid-test.d.ts +0 -11
  152. package/lib/Utils/lidToJid-test.js +0 -27
  153. package/lib/Utils/message-retry-manager.d.ts +0 -81
  154. package/lib/Utils/message-retry-manager.js +0 -152
  155. /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -2,15 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.processSyncAction = exports.chatModificationToAppPatch = exports.decodePatches = exports.decodeSyncdSnapshot = exports.downloadExternalPatch = exports.downloadExternalBlob = exports.extractSyncdPatches = exports.decodeSyncdPatch = exports.decodeSyncdMutations = exports.encodeSyncdPatch = exports.newLTHashState = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
- const index_js_1 = require("../../WAProto/index.js");
5
+ const WAProto_1 = require("../../WAProto");
6
6
  const LabelAssociation_1 = require("../Types/LabelAssociation");
7
7
  const WABinary_1 = require("../WABinary");
8
8
  const crypto_1 = require("./crypto");
9
9
  const generics_1 = require("./generics");
10
10
  const lt_hash_1 = require("./lt-hash");
11
11
  const messages_media_1 = require("./messages-media");
12
- const mutationKeys = async (keydata) => {
13
- const expanded = await (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
12
+ const mutationKeys = (keydata) => {
13
+ const expanded = (0, crypto_1.hkdf)(keydata, 160, { info: 'WhatsApp Mutation Keys' });
14
14
  return {
15
15
  indexKey: expanded.slice(0, 32),
16
16
  valueEncryptionKey: expanded.slice(32, 64),
@@ -23,10 +23,10 @@ const generateMac = (operation, data, keyId, key) => {
23
23
  const getKeyData = () => {
24
24
  let r;
25
25
  switch (operation) {
26
- case index_js_1.proto.SyncdMutation.SyncdOperation.SET:
26
+ case WAProto_1.proto.SyncdMutation.SyncdOperation.SET:
27
27
  r = 0x01;
28
28
  break;
29
- case index_js_1.proto.SyncdMutation.SyncdOperation.REMOVE:
29
+ case WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE:
30
30
  r = 0x02;
31
31
  break;
32
32
  }
@@ -53,7 +53,7 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
53
53
  mix: ({ indexMac, valueMac, operation }) => {
54
54
  const indexMacBase64 = Buffer.from(indexMac).toString('base64');
55
55
  const prevOp = indexValueMap[indexMacBase64];
56
- if (operation === index_js_1.proto.SyncdMutation.SyncdOperation.REMOVE) {
56
+ if (operation === WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE) {
57
57
  if (!prevOp) {
58
58
  throw new boom_1.Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
59
59
  }
@@ -69,9 +69,9 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
69
69
  subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
70
70
  }
71
71
  },
72
- finish: async () => {
72
+ finish: () => {
73
73
  const hashArrayBuffer = new Uint8Array(hash).buffer;
74
- const result = await lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
74
+ const result = lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
75
75
  const buffer = Buffer.from(result);
76
76
  return {
77
77
  hash: buffer,
@@ -81,11 +81,20 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
81
81
  };
82
82
  };
83
83
  const generateSnapshotMac = (lthash, version, name, key) => {
84
- const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
84
+ const total = Buffer.concat([
85
+ lthash,
86
+ to64BitNetworkOrder(version),
87
+ Buffer.from(name, 'utf-8')
88
+ ]);
85
89
  return (0, crypto_1.hmacSign)(total, key, 'sha256');
86
90
  };
87
91
  const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
88
- const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
92
+ const total = Buffer.concat([
93
+ snapshotMac,
94
+ ...valueMacs,
95
+ to64BitNetworkOrder(version),
96
+ Buffer.from(type, 'utf-8')
97
+ ]);
89
98
  return (0, crypto_1.hmacSign)(total, key);
90
99
  };
91
100
  const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
@@ -98,21 +107,21 @@ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation
98
107
  const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
99
108
  state = { ...state, indexValueMap: { ...state.indexValueMap } };
100
109
  const indexBuffer = Buffer.from(JSON.stringify(index));
101
- const dataProto = index_js_1.proto.SyncActionData.create({
110
+ const dataProto = WAProto_1.proto.SyncActionData.fromObject({
102
111
  index: indexBuffer,
103
112
  value: syncAction,
104
113
  padding: new Uint8Array(0),
105
114
  version: apiVersion
106
115
  });
107
- const encoded = index_js_1.proto.SyncActionData.encode(dataProto).finish();
108
- const keyValue = await mutationKeys(key.keyData);
116
+ const encoded = WAProto_1.proto.SyncActionData.encode(dataProto).finish();
117
+ const keyValue = mutationKeys(key.keyData);
109
118
  const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
110
119
  const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
111
120
  const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
112
121
  // update LT hash
113
122
  const generator = makeLtHashGenerator(state);
114
123
  generator.mix({ indexMac, valueMac, operation });
115
- Object.assign(state, await generator.finish());
124
+ Object.assign(state, generator.finish());
116
125
  state.version += 1;
117
126
  const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
118
127
  const patch = {
@@ -147,8 +156,8 @@ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncK
147
156
  for (const msgMutation of msgMutations) {
148
157
  // if it's a syncdmutation, get the operation property
149
158
  // otherwise, if it's only a record -- it'll be a SET mutation
150
- const operation = 'operation' in msgMutation ? msgMutation.operation : index_js_1.proto.SyncdMutation.SyncdOperation.SET;
151
- const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
159
+ const operation = 'operation' in msgMutation ? msgMutation.operation : WAProto_1.proto.SyncdMutation.SyncdOperation.SET;
160
+ const record = ('record' in msgMutation && !!msgMutation.record) ? msgMutation.record : msgMutation;
152
161
  const key = await getKey(record.keyId.id);
153
162
  const content = Buffer.from(record.value.blob);
154
163
  const encContent = content.slice(0, -32);
@@ -160,7 +169,7 @@ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncK
160
169
  }
161
170
  }
162
171
  const result = (0, crypto_1.aesDecrypt)(encContent, key.valueEncryptionKey);
163
- const syncAction = index_js_1.proto.SyncActionData.decode(result);
172
+ const syncAction = WAProto_1.proto.SyncActionData.decode(result);
164
173
  if (validateMacs) {
165
174
  const hmac = (0, crypto_1.hmacSign)(syncAction.index, key.indexKey);
166
175
  if (Buffer.compare(hmac, record.index.blob) !== 0) {
@@ -175,15 +184,12 @@ const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncK
175
184
  operation: operation
176
185
  });
177
186
  }
178
- return await ltGenerator.finish();
187
+ return ltGenerator.finish();
179
188
  async function getKey(keyId) {
180
189
  const base64Key = Buffer.from(keyId).toString('base64');
181
190
  const keyEnc = await getAppStateSyncKey(base64Key);
182
191
  if (!keyEnc) {
183
- throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`, {
184
- statusCode: 404,
185
- data: { msgMutations }
186
- });
192
+ throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`, { statusCode: 404, data: { msgMutations } });
187
193
  }
188
194
  return mutationKeys(keyEnc.keyData);
189
195
  }
@@ -196,7 +202,7 @@ const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onM
196
202
  if (!mainKeyObj) {
197
203
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
198
204
  }
199
- const mainKey = await mutationKeys(mainKeyObj.keyData);
205
+ const mainKey = mutationKeys(mainKeyObj.keyData);
200
206
  const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
201
207
  const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, (0, generics_1.toNumber)(msg.version.version), name, mainKey.patchMacKey);
202
208
  if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
@@ -223,16 +229,16 @@ const extractSyncdPatches = async (result, options) => {
223
229
  if (!Buffer.isBuffer(snapshotNode)) {
224
230
  snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
225
231
  }
226
- const blobRef = index_js_1.proto.ExternalBlobReference.decode(snapshotNode.content);
232
+ const blobRef = WAProto_1.proto.ExternalBlobReference.decode(snapshotNode.content);
227
233
  const data = await (0, exports.downloadExternalBlob)(blobRef, options);
228
- snapshot = index_js_1.proto.SyncdSnapshot.decode(data);
234
+ snapshot = WAProto_1.proto.SyncdSnapshot.decode(data);
229
235
  }
230
236
  for (let { content } of patches) {
231
237
  if (content) {
232
238
  if (!Buffer.isBuffer(content)) {
233
239
  content = Buffer.from(Object.values(content));
234
240
  }
235
- const syncd = index_js_1.proto.SyncdPatch.decode(content);
241
+ const syncd = WAProto_1.proto.SyncdPatch.decode(content);
236
242
  if (!syncd.version) {
237
243
  syncd.version = { version: +collectionNode.attrs.version + 1 };
238
244
  }
@@ -255,7 +261,7 @@ const downloadExternalBlob = async (blob, options) => {
255
261
  exports.downloadExternalBlob = downloadExternalBlob;
256
262
  const downloadExternalPatch = async (blob, options) => {
257
263
  const buffer = await (0, exports.downloadExternalBlob)(blob, options);
258
- const syncData = index_js_1.proto.SyncdMutations.decode(buffer);
264
+ const syncData = WAProto_1.proto.SyncdMutations.decode(buffer);
259
265
  return syncData;
260
266
  };
261
267
  exports.downloadExternalPatch = downloadExternalPatch;
@@ -263,10 +269,12 @@ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVe
263
269
  const newState = (0, exports.newLTHashState)();
264
270
  newState.version = (0, generics_1.toNumber)(snapshot.version.version);
265
271
  const mutationMap = {};
266
- const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
272
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined'
273
+ || newState.version > minimumVersionNumber;
267
274
  const { hash, indexValueMap } = await (0, exports.decodeSyncdMutations)(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
268
- ? mutation => {
269
- const index = mutation.syncAction.index?.toString();
275
+ ? (mutation) => {
276
+ var _a;
277
+ const index = (_a = mutation.syncAction.index) === null || _a === void 0 ? void 0 : _a.toString();
270
278
  mutationMap[index] = mutation;
271
279
  }
272
280
  : () => { }, validateMacs);
@@ -278,7 +286,7 @@ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVe
278
286
  if (!keyEnc) {
279
287
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
280
288
  }
281
- const result = await mutationKeys(keyEnc.keyData);
289
+ const result = mutationKeys(keyEnc.keyData);
282
290
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
283
291
  if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
284
292
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
@@ -291,28 +299,31 @@ const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVe
291
299
  };
292
300
  exports.decodeSyncdSnapshot = decodeSyncdSnapshot;
293
301
  const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
302
+ var _a;
294
303
  const newState = {
295
304
  ...initial,
296
305
  indexValueMap: { ...initial.indexValueMap }
297
306
  };
298
307
  const mutationMap = {};
299
- for (const syncd of syncds) {
308
+ for (let i = 0; i < syncds.length; i++) {
309
+ const syncd = syncds[i];
300
310
  const { version, keyId, snapshotMac } = syncd;
301
311
  if (syncd.externalMutations) {
302
- logger?.trace({ name, version }, 'downloading external patch');
312
+ logger === null || logger === void 0 ? void 0 : logger.trace({ name, version }, 'downloading external patch');
303
313
  const ref = await (0, exports.downloadExternalPatch)(syncd.externalMutations, options);
304
- logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
305
- syncd.mutations?.push(...ref.mutations);
314
+ logger === null || logger === void 0 ? void 0 : logger.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
315
+ (_a = syncd.mutations) === null || _a === void 0 ? void 0 : _a.push(...ref.mutations);
306
316
  }
307
317
  const patchVersion = (0, generics_1.toNumber)(version.version);
308
318
  newState.version = patchVersion;
309
319
  const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
310
320
  const decodeResult = await (0, exports.decodeSyncdPatch)(syncd, name, newState, getAppStateSyncKey, shouldMutate
311
321
  ? mutation => {
312
- const index = mutation.syncAction.index?.toString();
322
+ var _a;
323
+ const index = (_a = mutation.syncAction.index) === null || _a === void 0 ? void 0 : _a.toString();
313
324
  mutationMap[index] = mutation;
314
325
  }
315
- : () => { }, true);
326
+ : (() => { }), true);
316
327
  newState.hash = decodeResult.hash;
317
328
  newState.indexValueMap = decodeResult.indexValueMap;
318
329
  if (validateMacs) {
@@ -321,7 +332,7 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
321
332
  if (!keyEnc) {
322
333
  throw new boom_1.Boom(`failed to find key "${base64Key}" to decode mutation`);
323
334
  }
324
- const result = await mutationKeys(keyEnc.keyData);
335
+ const result = mutationKeys(keyEnc.keyData);
325
336
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
326
337
  if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
327
338
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
@@ -334,30 +345,29 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
334
345
  };
335
346
  exports.decodePatches = decodePatches;
336
347
  const chatModificationToAppPatch = (mod, jid) => {
337
- const OP = index_js_1.proto.SyncdMutation.SyncdOperation;
348
+ const OP = WAProto_1.proto.SyncdMutation.SyncdOperation;
338
349
  const getMessageRange = (lastMessages) => {
339
350
  let messageRange;
340
351
  if (Array.isArray(lastMessages)) {
341
352
  const lastMsg = lastMessages[lastMessages.length - 1];
342
353
  messageRange = {
343
- lastMessageTimestamp: lastMsg?.messageTimestamp,
344
- messages: lastMessages?.length
345
- ? lastMessages.map(m => {
346
- if (!m.key?.id || !m.key?.remoteJid) {
347
- throw new boom_1.Boom('Incomplete key', { statusCode: 400, data: m });
348
- }
349
- if ((0, WABinary_1.isJidGroup)(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
350
- throw new boom_1.Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
351
- }
352
- if (!m.messageTimestamp || !(0, generics_1.toNumber)(m.messageTimestamp)) {
353
- throw new boom_1.Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
354
- }
355
- if (m.key.participant) {
356
- m.key.participant = (0, WABinary_1.jidNormalizedUser)(m.key.participant);
357
- }
358
- return m;
359
- })
360
- : undefined
354
+ lastMessageTimestamp: lastMsg === null || lastMsg === void 0 ? void 0 : lastMsg.messageTimestamp,
355
+ messages: (lastMessages === null || lastMessages === void 0 ? void 0 : lastMessages.length) ? lastMessages.map(m => {
356
+ var _a, _b;
357
+ if (!((_a = m.key) === null || _a === void 0 ? void 0 : _a.id) || !((_b = m.key) === null || _b === void 0 ? void 0 : _b.remoteJid)) {
358
+ throw new boom_1.Boom('Incomplete key', { statusCode: 400, data: m });
359
+ }
360
+ if ((0, WABinary_1.isJidGroup)(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
361
+ throw new boom_1.Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
362
+ }
363
+ if (!m.messageTimestamp || !(0, generics_1.toNumber)(m.messageTimestamp)) {
364
+ throw new boom_1.Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
365
+ }
366
+ if (m.key.participant) {
367
+ m.key.participant = (0, WABinary_1.jidNormalizedUser)(m.key.participant);
368
+ }
369
+ return m;
370
+ }) : undefined
361
371
  };
362
372
  }
363
373
  else {
@@ -408,33 +418,25 @@ const chatModificationToAppPatch = (mod, jid) => {
408
418
  operation: OP.SET
409
419
  };
410
420
  }
411
- else if ('deleteForMe' in mod) {
412
- const { timestamp, key, deleteMedia } = mod.deleteForMe;
413
- patch = {
414
- syncAction: {
415
- deleteMessageForMeAction: {
416
- deleteMedia,
417
- messageTimestamp: timestamp
418
- }
419
- },
420
- index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
421
- type: 'regular_high',
422
- apiVersion: 3,
423
- operation: OP.SET
424
- };
425
- }
426
421
  else if ('clear' in mod) {
427
- patch = {
428
- syncAction: {
429
- clearChatAction: {
430
- messageRange: getMessageRange(mod.lastMessages)
431
- }
432
- },
433
- index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
434
- type: 'regular_high',
435
- apiVersion: 6,
436
- operation: OP.SET
437
- };
422
+ if (mod.clear === 'all') {
423
+ throw new boom_1.Boom('not supported');
424
+ }
425
+ else {
426
+ const key = mod.clear.messages[0];
427
+ patch = {
428
+ syncAction: {
429
+ deleteMessageForMeAction: {
430
+ deleteMedia: false,
431
+ messageTimestamp: key.timestamp
432
+ }
433
+ },
434
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
435
+ type: 'regular_high',
436
+ apiVersion: 3,
437
+ operation: OP.SET
438
+ };
439
+ }
438
440
  }
439
441
  else if ('pin' in mod) {
440
442
  patch = {
@@ -449,28 +451,6 @@ const chatModificationToAppPatch = (mod, jid) => {
449
451
  operation: OP.SET
450
452
  };
451
453
  }
452
- else if ('contact' in mod) {
453
- patch = {
454
- syncAction: {
455
- contactAction: mod.contact || {}
456
- },
457
- index: ['contact', jid],
458
- type: 'critical_unblock_low',
459
- apiVersion: 2,
460
- operation: mod.contact ? OP.SET : OP.REMOVE
461
- };
462
- }
463
- else if ('disableLinkPreviews' in mod) {
464
- patch = {
465
- syncAction: {
466
- privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
467
- },
468
- index: ['setting_disableLinkPreviews'],
469
- type: 'regular',
470
- apiVersion: 8,
471
- operation: OP.SET
472
- };
473
- }
474
454
  else if ('star' in mod) {
475
455
  const key = mod.star.messages[0];
476
456
  patch = {
@@ -489,7 +469,7 @@ const chatModificationToAppPatch = (mod, jid) => {
489
469
  patch = {
490
470
  syncAction: {
491
471
  deleteChatAction: {
492
- messageRange: getMessageRange(mod.lastMessages)
472
+ messageRange: getMessageRange(mod.lastMessages),
493
473
  }
494
474
  },
495
475
  index: ['deleteChat', jid, '1'],
@@ -508,86 +488,60 @@ const chatModificationToAppPatch = (mod, jid) => {
508
488
  index: ['setting_pushName'],
509
489
  type: 'critical_block',
510
490
  apiVersion: 1,
511
- operation: OP.SET
512
- };
513
- }
514
- else if ('quickReply' in mod) {
515
- patch = {
516
- syncAction: {
517
- quickReplyAction: {
518
- count: 0,
519
- deleted: mod.quickReply.deleted || false,
520
- keywords: [],
521
- message: mod.quickReply.message || '',
522
- shortcut: mod.quickReply.shortcut || ''
523
- }
524
- },
525
- index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
526
- type: 'regular',
527
- apiVersion: 2,
528
- operation: OP.SET
529
- };
530
- }
531
- else if ('addLabel' in mod) {
532
- patch = {
533
- syncAction: {
534
- labelEditAction: {
535
- name: mod.addLabel.name,
536
- color: mod.addLabel.color,
537
- predefinedId: mod.addLabel.predefinedId,
538
- deleted: mod.addLabel.deleted
539
- }
540
- },
541
- index: ['label_edit', mod.addLabel.id],
542
- type: 'regular',
543
- apiVersion: 3,
544
- operation: OP.SET
491
+ operation: OP.SET,
545
492
  };
546
493
  }
547
494
  else if ('addChatLabel' in mod) {
548
495
  patch = {
549
496
  syncAction: {
550
497
  labelAssociationAction: {
551
- labeled: true
498
+ labeled: true,
552
499
  }
553
500
  },
554
501
  index: [LabelAssociation_1.LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
555
502
  type: 'regular',
556
503
  apiVersion: 3,
557
- operation: OP.SET
504
+ operation: OP.SET,
558
505
  };
559
506
  }
560
507
  else if ('removeChatLabel' in mod) {
561
508
  patch = {
562
509
  syncAction: {
563
510
  labelAssociationAction: {
564
- labeled: false
511
+ labeled: false,
565
512
  }
566
513
  },
567
514
  index: [LabelAssociation_1.LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
568
515
  type: 'regular',
569
516
  apiVersion: 3,
570
- operation: OP.SET
517
+ operation: OP.SET,
571
518
  };
572
519
  }
573
520
  else if ('addMessageLabel' in mod) {
574
521
  patch = {
575
522
  syncAction: {
576
523
  labelAssociationAction: {
577
- labeled: true
524
+ labeled: true,
578
525
  }
579
526
  },
580
- index: [LabelAssociation_1.LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
527
+ index: [
528
+ LabelAssociation_1.LabelAssociationType.Message,
529
+ mod.addMessageLabel.labelId,
530
+ jid,
531
+ mod.addMessageLabel.messageId,
532
+ '0',
533
+ '0'
534
+ ],
581
535
  type: 'regular',
582
536
  apiVersion: 3,
583
- operation: OP.SET
537
+ operation: OP.SET,
584
538
  };
585
539
  }
586
540
  else if ('removeMessageLabel' in mod) {
587
541
  patch = {
588
542
  syncAction: {
589
543
  labelAssociationAction: {
590
- labeled: false
544
+ labeled: false,
591
545
  }
592
546
  },
593
547
  index: [
@@ -600,7 +554,7 @@ const chatModificationToAppPatch = (mod, jid) => {
600
554
  ],
601
555
  type: 'regular',
602
556
  apiVersion: 3,
603
- operation: OP.SET
557
+ operation: OP.SET,
604
558
  };
605
559
  }
606
560
  else {
@@ -611,20 +565,23 @@ const chatModificationToAppPatch = (mod, jid) => {
611
565
  };
612
566
  exports.chatModificationToAppPatch = chatModificationToAppPatch;
613
567
  const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
568
+ var _a, _b, _c, _d;
614
569
  const isInitialSync = !!initialSyncOpts;
615
- const accountSettings = initialSyncOpts?.accountSettings;
616
- logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
570
+ const accountSettings = initialSyncOpts === null || initialSyncOpts === void 0 ? void 0 : initialSyncOpts.accountSettings;
571
+ logger === null || logger === void 0 ? void 0 : logger.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
617
572
  const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
618
- if (action?.muteAction) {
573
+ if (action === null || action === void 0 ? void 0 : action.muteAction) {
619
574
  ev.emit('chats.update', [
620
575
  {
621
576
  id,
622
- muteEndTime: action.muteAction?.muted ? (0, generics_1.toNumber)(action.muteAction.muteEndTimestamp) : null,
577
+ muteEndTime: ((_a = action.muteAction) === null || _a === void 0 ? void 0 : _a.muted)
578
+ ? (0, generics_1.toNumber)(action.muteAction.muteEndTimestamp)
579
+ : null,
623
580
  conditional: getChatUpdateConditional(id, undefined)
624
581
  }
625
582
  ]);
626
583
  }
627
- else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
584
+ else if ((action === null || action === void 0 ? void 0 : action.archiveChatAction) || type === 'archive' || type === 'unarchive') {
628
585
  // okay so we've to do some annoying computation here
629
586
  // when we're initially syncing the app state
630
587
  // there are a few cases we need to handle
@@ -635,38 +592,36 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
635
592
  // we compare the timestamp of latest message from the other person to determine this
636
593
  // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
637
594
  // it'll always take an app state action to mark in unarchived -- which we'll get anyway
638
- const archiveAction = action?.archiveChatAction;
639
- const isArchived = archiveAction ? archiveAction.archived : type === 'archive';
595
+ const archiveAction = action === null || action === void 0 ? void 0 : action.archiveChatAction;
596
+ const isArchived = archiveAction
597
+ ? archiveAction.archived
598
+ : type === 'archive';
640
599
  // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
641
600
  // // this only applies for the initial sync
642
601
  // if(isInitialSync && !isArchived) {
643
602
  // isArchived = false
644
603
  // }
645
- const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
604
+ const msgRange = !(accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats) ? undefined : archiveAction === null || archiveAction === void 0 ? void 0 : archiveAction.messageRange;
646
605
  // logger?.debug({ chat: id, syncAction }, 'message range archive')
647
- ev.emit('chats.update', [
648
- {
606
+ ev.emit('chats.update', [{
649
607
  id,
650
608
  archived: isArchived,
651
609
  conditional: getChatUpdateConditional(id, msgRange)
652
- }
653
- ]);
610
+ }]);
654
611
  }
655
- else if (action?.markChatAsReadAction) {
612
+ else if (action === null || action === void 0 ? void 0 : action.markChatAsReadAction) {
656
613
  const markReadAction = action.markChatAsReadAction;
657
614
  // basically we don't need to fire an "read" update if the chat is being marked as read
658
615
  // because the chat is read by default
659
616
  // this only applies for the initial sync
660
617
  const isNullUpdate = isInitialSync && markReadAction.read;
661
- ev.emit('chats.update', [
662
- {
618
+ ev.emit('chats.update', [{
663
619
  id,
664
- unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
665
- conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
666
- }
667
- ]);
620
+ unreadCount: isNullUpdate ? null : !!(markReadAction === null || markReadAction === void 0 ? void 0 : markReadAction.read) ? 0 : -1,
621
+ conditional: getChatUpdateConditional(id, markReadAction === null || markReadAction === void 0 ? void 0 : markReadAction.messageRange)
622
+ }]);
668
623
  }
669
- else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
624
+ else if ((action === null || action === void 0 ? void 0 : action.deleteMessageForMeAction) || type === 'deleteMessageForMe') {
670
625
  ev.emit('messages.delete', {
671
626
  keys: [
672
627
  {
@@ -677,41 +632,37 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
677
632
  ]
678
633
  });
679
634
  }
680
- else if (action?.contactAction) {
681
- ev.emit('contacts.upsert', [
682
- {
683
- id: id,
684
- name: action.contactAction.fullName,
685
- lid: action.contactAction.lidJid || undefined,
686
- phoneNumber: action.contactAction.pnJid || undefined
687
- }
688
- ]);
689
- }
690
- else if (action?.pushNameSetting) {
691
- const name = action?.pushNameSetting?.name;
692
- if (name && me?.name !== name) {
635
+ else if (action === null || action === void 0 ? void 0 : action.contactAction) {
636
+ ev.emit('contacts.upsert', [{
637
+ id: id,
638
+ name: action.contactAction.fullName,
639
+ lid: action.contactAction.lidJid || undefined,
640
+ jid: (0, WABinary_1.isJidUser)(id) ? id : undefined
641
+ }]);
642
+ }
643
+ else if (action === null || action === void 0 ? void 0 : action.pushNameSetting) {
644
+ const name = (_b = action === null || action === void 0 ? void 0 : action.pushNameSetting) === null || _b === void 0 ? void 0 : _b.name;
645
+ if (name && (me === null || me === void 0 ? void 0 : me.name) !== name) {
693
646
  ev.emit('creds.update', { me: { ...me, name } });
694
647
  }
695
648
  }
696
- else if (action?.pinAction) {
697
- ev.emit('chats.update', [
698
- {
649
+ else if (action === null || action === void 0 ? void 0 : action.pinAction) {
650
+ ev.emit('chats.update', [{
699
651
  id,
700
- pinned: action.pinAction?.pinned ? (0, generics_1.toNumber)(action.timestamp) : null,
652
+ pinned: ((_c = action.pinAction) === null || _c === void 0 ? void 0 : _c.pinned) ? (0, generics_1.toNumber)(action.timestamp) : null,
701
653
  conditional: getChatUpdateConditional(id, undefined)
702
- }
703
- ]);
654
+ }]);
704
655
  }
705
- else if (action?.unarchiveChatsSetting) {
656
+ else if (action === null || action === void 0 ? void 0 : action.unarchiveChatsSetting) {
706
657
  const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
707
658
  ev.emit('creds.update', { accountSettings: { unarchiveChats } });
708
- logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
659
+ logger === null || logger === void 0 ? void 0 : logger.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
709
660
  if (accountSettings) {
710
661
  accountSettings.unarchiveChats = unarchiveChats;
711
662
  }
712
663
  }
713
- else if (action?.starAction || type === 'star') {
714
- let starred = action?.starAction?.starred;
664
+ else if ((action === null || action === void 0 ? void 0 : action.starAction) || type === 'star') {
665
+ let starred = (_d = action === null || action === void 0 ? void 0 : action.starAction) === null || _d === void 0 ? void 0 : _d.starred;
715
666
  if (typeof starred !== 'boolean') {
716
667
  starred = syncAction.index[syncAction.index.length - 1] === '1';
717
668
  }
@@ -722,24 +673,26 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
722
673
  }
723
674
  ]);
724
675
  }
725
- else if (action?.deleteChatAction || type === 'deleteChat') {
676
+ else if ((action === null || action === void 0 ? void 0 : action.deleteChatAction) || type === 'deleteChat') {
726
677
  if (!isInitialSync) {
727
678
  ev.emit('chats.delete', [id]);
728
679
  }
729
680
  }
730
- else if (action?.labelEditAction) {
681
+ else if (action === null || action === void 0 ? void 0 : action.labelEditAction) {
731
682
  const { name, color, deleted, predefinedId } = action.labelEditAction;
732
683
  ev.emit('labels.edit', {
733
- id: id,
684
+ id,
734
685
  name: name,
735
686
  color: color,
736
687
  deleted: deleted,
737
688
  predefinedId: predefinedId ? String(predefinedId) : undefined
738
689
  });
739
690
  }
740
- else if (action?.labelAssociationAction) {
691
+ else if (action === null || action === void 0 ? void 0 : action.labelAssociationAction) {
741
692
  ev.emit('labels.association', {
742
- type: action.labelAssociationAction.labeled ? 'add' : 'remove',
693
+ type: action.labelAssociationAction.labeled
694
+ ? 'add'
695
+ : 'remove',
743
696
  association: type === LabelAssociation_1.LabelAssociationType.Chat
744
697
  ? {
745
698
  type: LabelAssociation_1.LabelAssociationType.Chat,
@@ -755,11 +708,11 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
755
708
  });
756
709
  }
757
710
  else {
758
- logger?.debug({ syncAction, id }, 'unprocessable update');
711
+ logger === null || logger === void 0 ? void 0 : logger.debug({ syncAction, id }, 'unprocessable update');
759
712
  }
760
713
  function getChatUpdateConditional(id, msgRange) {
761
714
  return isInitialSync
762
- ? data => {
715
+ ? (data) => {
763
716
  const chat = data.historySets.chats[id] || data.chatUpserts[id];
764
717
  if (chat) {
765
718
  return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
@@ -768,8 +721,8 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
768
721
  : undefined;
769
722
  }
770
723
  function isValidPatchBasedOnMessageRange(chat, msgRange) {
771
- const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
772
- const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
724
+ const lastMsgTimestamp = Number((msgRange === null || msgRange === void 0 ? void 0 : msgRange.lastMessageTimestamp) || (msgRange === null || msgRange === void 0 ? void 0 : msgRange.lastSystemMessageTimestamp) || 0);
725
+ const chatLastMsgTimestamp = Number((chat === null || chat === void 0 ? void 0 : chat.lastMessageRecvTimestamp) || 0);
773
726
  return lastMsgTimestamp >= chatLastMsgTimestamp;
774
727
  }
775
728
  };