supunmd-bail 2.1.1 → 2.1.4

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