jagproject 26.3.23 → 26.3.26

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