@baileys-md/baileys 10.1.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1303 -2
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/fix-imports.js +29 -0
  6. package/WAProto/index.js +13516 -4182
  7. package/lib/Defaults/baileys-version.js +1 -0
  8. package/lib/Defaults/index.js +51 -72
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.js +30 -0
  11. package/lib/Signal/Group/group_cipher.js +94 -0
  12. package/lib/Signal/Group/index.js +12 -0
  13. package/lib/Signal/Group/keyhelper.js +19 -0
  14. package/lib/Signal/Group/queue-job.js +54 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  17. package/lib/Signal/Group/sender-key-message.js +67 -0
  18. package/lib/Signal/Group/sender-key-name.js +48 -0
  19. package/lib/Signal/Group/sender-key-record.js +50 -0
  20. package/lib/Signal/Group/sender-key-state.js +96 -0
  21. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +4 -16
  22. package/lib/Signal/libsignal.js +41 -61
  23. package/lib/Socket/Client/index.js +3 -19
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +50 -0
  26. package/lib/Socket/business.js +37 -42
  27. package/lib/Socket/chats.js +194 -187
  28. package/lib/Socket/communities.js +351 -0
  29. package/lib/Socket/groups.js +87 -90
  30. package/lib/Socket/index.js +7 -8
  31. package/lib/Socket/messages-recv.js +360 -335
  32. package/lib/Socket/messages-send.js +156 -279
  33. package/lib/Socket/mex.js +42 -0
  34. package/lib/Socket/newsletter.js +144 -213
  35. package/lib/Socket/socket.js +128 -161
  36. package/lib/Socket/usync.js +19 -26
  37. package/lib/Types/Auth.js +2 -2
  38. package/lib/Types/Call.js +2 -2
  39. package/lib/Types/Chat.js +8 -4
  40. package/lib/Types/Contact.js +2 -2
  41. package/lib/Types/Events.js +2 -2
  42. package/lib/Types/GroupMetadata.js +2 -2
  43. package/lib/Types/Label.js +3 -5
  44. package/lib/Types/LabelAssociation.js +3 -5
  45. package/lib/Types/Message.js +7 -7
  46. package/lib/Types/Newsletter.js +30 -17
  47. package/lib/Types/Product.js +2 -2
  48. package/lib/Types/Signal.js +2 -2
  49. package/lib/Types/Socket.js +3 -2
  50. package/lib/Types/State.js +2 -2
  51. package/lib/Types/USync.js +2 -2
  52. package/lib/Types/index.js +15 -31
  53. package/lib/Utils/auth-utils.js +31 -47
  54. package/lib/Utils/baileys-event-stream.js +15 -22
  55. package/lib/Utils/business.js +66 -69
  56. package/lib/Utils/chat-utils.js +200 -195
  57. package/lib/Utils/crypto.js +70 -85
  58. package/lib/Utils/decode-wa-message.js +47 -51
  59. package/lib/Utils/event-buffer.js +36 -46
  60. package/lib/Utils/generics.js +116 -188
  61. package/lib/Utils/history.js +37 -46
  62. package/lib/Utils/index.js +19 -33
  63. package/lib/Utils/link-preview.js +14 -55
  64. package/lib/Utils/logger.js +3 -7
  65. package/lib/Utils/lt-hash.js +23 -26
  66. package/lib/{Store → Utils}/make-in-memory-store.js +19 -27
  67. package/lib/Utils/make-mutex.js +7 -10
  68. package/lib/{Store → Utils}/make-ordered-dictionary.js +1 -3
  69. package/lib/Utils/messages-media.js +236 -368
  70. package/lib/Utils/messages.js +278 -510
  71. package/lib/Utils/noise-handler.js +22 -31
  72. package/lib/{Store → Utils}/object-repository.js +1 -4
  73. package/lib/Utils/process-message.js +144 -148
  74. package/lib/Utils/signal.js +71 -64
  75. package/lib/Utils/use-multi-file-auth-state.js +112 -84
  76. package/lib/Utils/validate-connection.js +72 -115
  77. package/lib/WABinary/constants.js +1281 -20
  78. package/lib/WABinary/decode.js +15 -52
  79. package/lib/WABinary/encode.js +14 -48
  80. package/lib/WABinary/generic-utils.js +31 -39
  81. package/lib/WABinary/index.js +6 -21
  82. package/lib/WABinary/jid-utils.js +23 -40
  83. package/lib/WABinary/types.js +2 -2
  84. package/lib/WAM/BinaryInfo.js +2 -5
  85. package/lib/WAM/constants.js +2257 -2366
  86. package/lib/WAM/encode.js +17 -21
  87. package/lib/WAM/index.js +4 -19
  88. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  89. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  90. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  91. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  92. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  93. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +3 -6
  94. package/lib/WAUSync/Protocols/index.js +5 -20
  95. package/lib/WAUSync/USyncQuery.js +34 -32
  96. package/lib/WAUSync/USyncUser.js +2 -5
  97. package/lib/WAUSync/index.js +4 -19
  98. package/lib/index.js +11 -33
  99. package/package.json +25 -54
  100. package/WASignalGroup/GroupProtocol.js +0 -1697
  101. package/WASignalGroup/ciphertext_message.js +0 -16
  102. package/WASignalGroup/group_cipher.js +0 -120
  103. package/WASignalGroup/group_session_builder.js +0 -46
  104. package/WASignalGroup/index.js +0 -5
  105. package/WASignalGroup/keyhelper.js +0 -21
  106. package/WASignalGroup/protobufs.js +0 -3
  107. package/WASignalGroup/queue_job.js +0 -69
  108. package/WASignalGroup/sender_chain_key.js +0 -50
  109. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  110. package/WASignalGroup/sender_key_message.js +0 -92
  111. package/WASignalGroup/sender_key_name.js +0 -70
  112. package/WASignalGroup/sender_key_record.js +0 -56
  113. package/WASignalGroup/sender_key_state.js +0 -129
  114. package/lib/Defaults/baileys-version.json +0 -3
  115. package/lib/Defaults/phonenumber-mcc.json +0 -223
  116. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  117. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  118. package/lib/Socket/Client/web-socket-client.js +0 -62
  119. package/lib/Socket/registration.js +0 -166
  120. package/lib/Store/index.js +0 -8
  121. package/lib/Store/make-cache-manager-store.js +0 -83
  122. package/lib/Store/make-mongo-store.js +0 -567
@@ -1,35 +1,30 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeChatsSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const WAProto_1 = require("../../WAProto");
10
- const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
12
- const Utils_1 = require("../Utils");
13
- const jimp_1 = require('jimp');
14
- const make_mutex_1 = require("../Utils/make-mutex");
15
- const process_message_1 = __importDefault(require("../Utils/process-message"));
16
- const WABinary_1 = require("../WABinary");
17
- const WAUSync_1 = require("../WAUSync");
18
- const usync_1 = require("./usync");
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
7
+ import { makeMutex } from '../Utils/make-mutex.js';
8
+ import processMessage from '../Utils/process-message.js';
9
+ import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
10
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
11
+ import { makeUSyncSocket } from './usync.js';
12
+ import * as WABinary_1 from "../WABinary/index.js"
19
13
  const MAX_SYNC_ATTEMPTS = 2;
20
- const makeChatsSocket = (config) => {
21
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
22
- const sock = (0, usync_1.makeUSyncSocket)(config);
23
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
14
+ export const makeChatsSocket = (config) => {
15
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage } = config;
16
+ const sock = makeUSyncSocket(config);
17
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError } = sock;
24
18
  let privacySettings;
25
19
  let needToFlushWithAppStateSync = false;
26
20
  let pendingAppStateSync = false;
27
21
  /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
28
- const processingMutex = (0, make_mutex_1.makeMutex)();
29
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
30
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
31
- useClones: false
32
- });
22
+ const processingMutex = makeMutex();
23
+ const placeholderResendCache = config.placeholderResendCache ||
24
+ new NodeCache({
25
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
26
+ useClones: false
27
+ });
33
28
  if (!config.placeholderResendCache) {
34
29
  config.placeholderResendCache = placeholderResendCache;
35
30
  }
@@ -44,14 +39,12 @@ const makeChatsSocket = (config) => {
44
39
  tag: 'iq',
45
40
  attrs: {
46
41
  xmlns: 'privacy',
47
- to: WABinary_1.S_WHATSAPP_NET,
42
+ to: S_WHATSAPP_NET,
48
43
  type: 'get'
49
44
  },
50
- content: [
51
- { tag: 'privacy', attrs: {} }
52
- ]
45
+ content: [{ tag: 'privacy', attrs: {} }]
53
46
  });
54
- privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
47
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
55
48
  }
56
49
  return privacySettings;
57
50
  };
@@ -61,10 +54,11 @@ const makeChatsSocket = (config) => {
61
54
  tag: 'iq',
62
55
  attrs: {
63
56
  xmlns: 'privacy',
64
- to: WABinary_1.S_WHATSAPP_NET,
57
+ to: S_WHATSAPP_NET,
65
58
  type: 'set'
66
59
  },
67
- content: [{
60
+ content: [
61
+ {
68
62
  tag: 'privacy',
69
63
  attrs: {},
70
64
  content: [
@@ -73,7 +67,8 @@ const makeChatsSocket = (config) => {
73
67
  attrs: { name, value }
74
68
  }
75
69
  ]
76
- }]
70
+ }
71
+ ]
77
72
  });
78
73
  };
79
74
  const updateMessagesPrivacy = async (value) => {
@@ -105,15 +100,17 @@ const makeChatsSocket = (config) => {
105
100
  tag: 'iq',
106
101
  attrs: {
107
102
  xmlns: 'disappearing_mode',
108
- to: WABinary_1.S_WHATSAPP_NET,
103
+ to: S_WHATSAPP_NET,
109
104
  type: 'set'
110
105
  },
111
- content: [{
106
+ content: [
107
+ {
112
108
  tag: 'disappearing_mode',
113
109
  attrs: {
114
110
  duration: duration.toString()
115
111
  }
116
- }]
112
+ }
113
+ ]
117
114
  });
118
115
  };
119
116
  const getBotListV2 = async () => {
@@ -121,21 +118,23 @@ const makeChatsSocket = (config) => {
121
118
  tag: 'iq',
122
119
  attrs: {
123
120
  xmlns: 'bot',
124
- to: WABinary_1.S_WHATSAPP_NET,
121
+ to: S_WHATSAPP_NET,
125
122
  type: 'get'
126
123
  },
127
- content: [{
124
+ content: [
125
+ {
128
126
  tag: 'bot',
129
127
  attrs: {
130
128
  v: '2'
131
129
  }
132
- }]
130
+ }
131
+ ]
133
132
  });
134
- const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
133
+ const botNode = getBinaryNodeChild(resp, 'bot');
135
134
  const botList = [];
136
- for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
135
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
137
136
  if (section.attrs.type === 'all') {
138
- for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
137
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
139
138
  botList.push({
140
139
  jid: bot.attrs.jid,
141
140
  personaId: bot.attrs['persona_id']
@@ -146,23 +145,20 @@ const makeChatsSocket = (config) => {
146
145
  return botList;
147
146
  };
148
147
  const onWhatsApp = async (...jids) => {
149
- const usyncQuery = new WAUSync_1.USyncQuery()
150
- .withContactProtocol()
151
- .withLIDProtocol();
148
+ const usyncQuery = new USyncQuery().withContactProtocol().withLIDProtocol();
152
149
  for (const jid of jids) {
153
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
154
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
150
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
151
+ usyncQuery.withUser(new USyncUser().withPhone(phone));
155
152
  }
156
153
  const results = await sock.executeUSyncQuery(usyncQuery);
157
154
  if (results) {
158
- return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
155
+ return results.list.filter(a => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
159
156
  }
160
157
  };
161
158
  const fetchStatus = async (...jids) => {
162
- const usyncQuery = new WAUSync_1.USyncQuery()
163
- .withStatusProtocol();
159
+ const usyncQuery = new USyncQuery().withStatusProtocol();
164
160
  for (const jid of jids) {
165
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
161
+ usyncQuery.withUser(new USyncUser().withId(jid));
166
162
  }
167
163
  const result = await sock.executeUSyncQuery(usyncQuery);
168
164
  if (result) {
@@ -170,10 +166,9 @@ const makeChatsSocket = (config) => {
170
166
  }
171
167
  };
172
168
  const fetchDisappearingDuration = async (...jids) => {
173
- const usyncQuery = new WAUSync_1.USyncQuery()
174
- .withDisappearingModeProtocol();
169
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
175
170
  for (const jid of jids) {
176
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
171
+ usyncQuery.withUser(new USyncUser().withId(jid));
177
172
  }
178
173
  const result = await sock.executeUSyncQuery(usyncQuery);
179
174
  if (result) {
@@ -182,24 +177,14 @@ const makeChatsSocket = (config) => {
182
177
  };
183
178
  /** update the profile picture for yourself or a group */
184
179
  const updateProfilePicture = async (jid, content) => {
185
- let targetJid;
186
- const generate_1 = async (media) => {
187
- const jimp = await jimp_1.read(media);
188
- const min = await jimp.getWidth();
189
- const max = await jimp.getHeight();
190
- const cropped = await jimp.crop(0, 0, min, max);
191
- return {
192
- img: await cropped.scaleToFit(720, 720).getBufferAsync(jimp_1.MIME_JPEG),
193
- preview: await cropped.normalize().getBufferAsync(jimp_1.MIME_JPEG)
194
- }
195
- }
180
+ let targetJid;
196
181
  if (!jid) {
197
182
  throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
198
183
  }
199
184
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
200
185
  targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
201
186
  }
202
- const { img } = await generate_1(content);
187
+ const { img } = await generateProfilePicture(content);
203
188
  await query({
204
189
  tag: 'iq',
205
190
  attrs: {
@@ -221,18 +206,21 @@ const makeChatsSocket = (config) => {
221
206
  const removeProfilePicture = async (jid) => {
222
207
  let targetJid;
223
208
  if (!jid) {
224
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
209
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
225
210
  }
226
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
227
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
211
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
212
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
213
+ }
214
+ else {
215
+ targetJid = undefined;
228
216
  }
229
217
  await query({
230
218
  tag: 'iq',
231
219
  attrs: {
232
- target: targetJid,
233
- to: WABinary_1.S_WHATSAPP_NET,
220
+ to: S_WHATSAPP_NET,
234
221
  type: 'set',
235
- xmlns: 'w:profile:picture'
222
+ xmlns: 'w:profile:picture',
223
+ ...(targetJid ? { target: targetJid } : {})
236
224
  }
237
225
  });
238
226
  };
@@ -241,7 +229,7 @@ const makeChatsSocket = (config) => {
241
229
  await query({
242
230
  tag: 'iq',
243
231
  attrs: {
244
- to: WABinary_1.S_WHATSAPP_NET,
232
+ to: S_WHATSAPP_NET,
245
233
  type: 'set',
246
234
  xmlns: 'status'
247
235
  },
@@ -262,20 +250,19 @@ const makeChatsSocket = (config) => {
262
250
  tag: 'iq',
263
251
  attrs: {
264
252
  xmlns: 'blocklist',
265
- to: WABinary_1.S_WHATSAPP_NET,
253
+ to: S_WHATSAPP_NET,
266
254
  type: 'get'
267
255
  }
268
256
  });
269
- const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
270
- return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
271
- .map(n => n.attrs.jid);
257
+ const listNode = getBinaryNodeChild(result, 'list');
258
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
272
259
  };
273
260
  const updateBlockStatus = async (jid, action) => {
274
261
  await query({
275
262
  tag: 'iq',
276
263
  attrs: {
277
264
  xmlns: 'blocklist',
278
- to: WABinary_1.S_WHATSAPP_NET,
265
+ to: S_WHATSAPP_NET,
279
266
  type: 'set'
280
267
  },
281
268
  content: [
@@ -290,7 +277,6 @@ const makeChatsSocket = (config) => {
290
277
  });
291
278
  };
292
279
  const getBusinessProfile = async (jid) => {
293
- var _a, _b, _c, _d, _e, _f, _g;
294
280
  const results = await query({
295
281
  tag: 'iq',
296
282
  attrs: {
@@ -298,38 +284,42 @@ const makeChatsSocket = (config) => {
298
284
  xmlns: 'w:biz',
299
285
  type: 'get'
300
286
  },
301
- content: [{
287
+ content: [
288
+ {
302
289
  tag: 'business_profile',
303
290
  attrs: { v: '244' },
304
- content: [{
291
+ content: [
292
+ {
305
293
  tag: 'profile',
306
294
  attrs: { jid }
307
- }]
308
- }]
295
+ }
296
+ ]
297
+ }
298
+ ]
309
299
  });
310
- const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
311
- const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
300
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
301
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
312
302
  if (profiles) {
313
- const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
314
- const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
315
- const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
316
- const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
317
- const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
318
- const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
303
+ const address = getBinaryNodeChild(profiles, 'address');
304
+ const description = getBinaryNodeChild(profiles, 'description');
305
+ const website = getBinaryNodeChild(profiles, 'website');
306
+ const email = getBinaryNodeChild(profiles, 'email');
307
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
308
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
319
309
  const businessHoursConfig = businessHours
320
- ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
310
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
321
311
  : undefined;
322
- const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
312
+ const websiteStr = website?.content?.toString();
323
313
  return {
324
- wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
325
- address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
326
- description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
314
+ wid: profiles.attrs?.jid,
315
+ address: address?.content?.toString(),
316
+ description: description?.content?.toString() || '',
327
317
  website: websiteStr ? [websiteStr] : [],
328
- email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
329
- category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
330
- 'business_hours': {
331
- timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
332
- 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
318
+ email: email?.content?.toString(),
319
+ category: category?.content?.toString(),
320
+ business_hours: {
321
+ timezone: businessHours?.attrs?.timezone,
322
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
333
323
  }
334
324
  };
335
325
  }
@@ -339,17 +329,17 @@ const makeChatsSocket = (config) => {
339
329
  await sendNode({
340
330
  tag: 'iq',
341
331
  attrs: {
342
- to: WABinary_1.S_WHATSAPP_NET,
332
+ to: S_WHATSAPP_NET,
343
333
  type: 'set',
344
334
  xmlns: 'urn:xmpp:whatsapp:dirty',
345
- id: generateMessageTag(),
335
+ id: generateMessageTag()
346
336
  },
347
337
  content: [
348
338
  {
349
339
  tag: 'clean',
350
340
  attrs: {
351
341
  type,
352
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
342
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
353
343
  }
354
344
  }
355
345
  ]
@@ -358,7 +348,7 @@ const makeChatsSocket = (config) => {
358
348
  const newAppStateChunkHandler = (isInitialSync) => {
359
349
  return {
360
350
  onMutation(mutation) {
361
- (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
351
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
362
352
  }
363
353
  };
364
354
  };
@@ -368,7 +358,6 @@ const makeChatsSocket = (config) => {
368
358
  const initialVersionMap = {};
369
359
  const globalMutationMap = {};
370
360
  await authState.keys.transaction(async () => {
371
- var _a;
372
361
  const collectionsToHandle = new Set(collections);
373
362
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
374
363
  const attemptsMap = {};
@@ -387,7 +376,7 @@ const makeChatsSocket = (config) => {
387
376
  }
388
377
  }
389
378
  else {
390
- state = (0, Utils_1.newLTHashState)();
379
+ state = newLTHashState();
391
380
  }
392
381
  states[name] = state;
393
382
  logger.info(`resyncing ${name} from v${state.version}`);
@@ -397,14 +386,14 @@ const makeChatsSocket = (config) => {
397
386
  name,
398
387
  version: state.version.toString(),
399
388
  // return snapshot if being synced from scratch
400
- 'return_snapshot': (!state.version).toString()
389
+ return_snapshot: (!state.version).toString()
401
390
  }
402
391
  });
403
392
  }
404
393
  const result = await query({
405
394
  tag: 'iq',
406
395
  attrs: {
407
- to: WABinary_1.S_WHATSAPP_NET,
396
+ to: S_WHATSAPP_NET,
408
397
  xmlns: 'w:sync:app:state',
409
398
  type: 'set'
410
399
  },
@@ -417,13 +406,13 @@ const makeChatsSocket = (config) => {
417
406
  ]
418
407
  });
419
408
  // extract from binary node
420
- const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
409
+ const decoded = await extractSyncdPatches(result, config?.options);
421
410
  for (const key in decoded) {
422
411
  const name = key;
423
412
  const { patches, hasMorePatches, snapshot } = decoded[name];
424
413
  try {
425
414
  if (snapshot) {
426
- const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
415
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
427
416
  states[name] = newState;
428
417
  Object.assign(globalMutationMap, mutationMap);
429
418
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
@@ -431,7 +420,7 @@ const makeChatsSocket = (config) => {
431
420
  }
432
421
  // only process if there are syncd patches
433
422
  if (patches.length) {
434
- const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
423
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
435
424
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
436
425
  logger.info(`synced ${name} to v${newState.version}`);
437
426
  initialVersionMap[name] = newState.version;
@@ -440,16 +429,17 @@ const makeChatsSocket = (config) => {
440
429
  if (hasMorePatches) {
441
430
  logger.info(`${name} has more patches...`);
442
431
  }
443
- else { // collection is done with sync
432
+ else {
433
+ // collection is done with sync
444
434
  collectionsToHandle.delete(name);
445
435
  }
446
436
  }
447
437
  catch (error) {
448
438
  // if retry attempts overshoot
449
439
  // or key not found
450
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
451
- || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
452
- || error.name === 'TypeError';
440
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
441
+ error.output?.statusCode === 404 ||
442
+ error.name === 'TypeError';
453
443
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
454
444
  await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
455
445
  // increment number of retries
@@ -473,22 +463,19 @@ const makeChatsSocket = (config) => {
473
463
  * type = "image for the high res picture"
474
464
  */
475
465
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
476
- var _a;
477
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
466
+ jid = jidNormalizedUser(jid);
478
467
  const result = await query({
479
468
  tag: 'iq',
480
469
  attrs: {
481
470
  target: jid,
482
- to: WABinary_1.S_WHATSAPP_NET,
471
+ to: S_WHATSAPP_NET,
483
472
  type: 'get',
484
473
  xmlns: 'w:profile:picture'
485
474
  },
486
- content: [
487
- { tag: 'picture', attrs: { type, query: 'url' } }
488
- ]
475
+ content: [{ tag: 'picture', attrs: { type, query: 'url' } }]
489
476
  }, timeoutMs);
490
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
491
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
477
+ const child = getBinaryNodeChild(result, 'picture');
478
+ return child?.attrs?.url;
492
479
  };
493
480
  const sendPresenceUpdate = async (type, toJid) => {
494
481
  const me = authState.creds.me;
@@ -501,17 +488,19 @@ const makeChatsSocket = (config) => {
501
488
  await sendNode({
502
489
  tag: 'presence',
503
490
  attrs: {
504
- name: me.name,
491
+ name: me.name.replace(/@/g, ''),
505
492
  type
506
493
  }
507
494
  });
508
495
  }
509
496
  else {
497
+ const { server } = jidDecode(toJid);
498
+ const isLid = server === 'lid';
510
499
  await sendNode({
511
500
  tag: 'chatstate',
512
501
  attrs: {
513
- from: me.id,
514
- to: toJid,
502
+ from: isLid ? me.lid : me.id,
503
+ to: toJid
515
504
  },
516
505
  content: [
517
506
  {
@@ -526,7 +515,7 @@ const makeChatsSocket = (config) => {
526
515
  * @param toJid the jid to subscribe to
527
516
  * @param tcToken token for subscription, use if present
528
517
  */
529
- const presenceSubscribe = (toJid, tcToken) => (sendNode({
518
+ const presenceSubscribe = (toJid, tcToken) => sendNode({
530
519
  tag: 'presence',
531
520
  attrs: {
532
521
  to: toJid,
@@ -542,13 +531,12 @@ const makeChatsSocket = (config) => {
542
531
  }
543
532
  ]
544
533
  : undefined
545
- }));
534
+ });
546
535
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
547
- var _a;
548
536
  let presence;
549
537
  const jid = attrs.from;
550
538
  const participant = attrs.participant || attrs.from;
551
- if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
539
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
552
540
  return;
553
541
  }
554
542
  if (tag === 'presence') {
@@ -563,7 +551,7 @@ const makeChatsSocket = (config) => {
563
551
  if (type === 'paused') {
564
552
  type = 'available';
565
553
  }
566
- if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
554
+ if (firstChild.attrs?.media === 'audio') {
567
555
  type = 'recording';
568
556
  }
569
557
  presence = { lastKnownPresence: type };
@@ -579,7 +567,7 @@ const makeChatsSocket = (config) => {
579
567
  const name = patchCreate.type;
580
568
  const myAppStateKeyId = authState.creds.myAppStateKeyId;
581
569
  if (!myAppStateKeyId) {
582
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
570
+ throw new Boom('App state key not present!', { statusCode: 400 });
583
571
  }
584
572
  let initial;
585
573
  let encodeResult;
@@ -588,13 +576,13 @@ const makeChatsSocket = (config) => {
588
576
  logger.debug({ patch: patchCreate }, 'applying app patch');
589
577
  await resyncAppState([name], false);
590
578
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
591
- initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
592
- encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
579
+ initial = currentSyncVersion || newLTHashState();
580
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
593
581
  const { patch, state } = encodeResult;
594
582
  const node = {
595
583
  tag: 'iq',
596
584
  attrs: {
597
- to: WABinary_1.S_WHATSAPP_NET,
585
+ to: S_WHATSAPP_NET,
598
586
  type: 'set',
599
587
  xmlns: 'w:sync:app:state'
600
588
  },
@@ -608,13 +596,13 @@ const makeChatsSocket = (config) => {
608
596
  attrs: {
609
597
  name,
610
598
  version: (state.version - 1).toString(),
611
- 'return_snapshot': 'false'
599
+ return_snapshot: 'false'
612
600
  },
613
601
  content: [
614
602
  {
615
603
  tag: 'patch',
616
604
  attrs: {},
617
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
605
+ content: proto.SyncdPatch.encode(patch).finish()
618
606
  }
619
607
  ]
620
608
  }
@@ -628,7 +616,7 @@ const makeChatsSocket = (config) => {
628
616
  });
629
617
  if (config.emitOwnEvents) {
630
618
  const { onMutation } = newAppStateChunkHandler(false);
631
- const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
619
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
632
620
  for (const key in mutationMap) {
633
621
  onMutation(mutationMap[key]);
634
622
  }
@@ -636,29 +624,32 @@ const makeChatsSocket = (config) => {
636
624
  };
637
625
  /** sending non-abt props may fix QR scan fail if server expects */
638
626
  const fetchProps = async () => {
639
- var _a, _b, _c;
640
627
  const resultNode = await query({
641
628
  tag: 'iq',
642
629
  attrs: {
643
- to: WABinary_1.S_WHATSAPP_NET,
630
+ to: S_WHATSAPP_NET,
644
631
  xmlns: 'w',
645
- type: 'get',
632
+ type: 'get'
646
633
  },
647
634
  content: [
648
- { tag: 'props', attrs: {
635
+ {
636
+ tag: 'props',
637
+ attrs: {
649
638
  protocol: '2',
650
- hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
651
- } }
639
+ hash: authState?.creds?.lastPropHash || ''
640
+ }
641
+ }
652
642
  ]
653
643
  });
654
- const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
644
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
655
645
  let props = {};
656
646
  if (propsNode) {
657
- if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
658
- authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
647
+ if (propsNode.attrs?.hash) {
648
+ // on some clients, the hash is returning as undefined
649
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
659
650
  ev.emit('creds.update', authState.creds);
660
651
  }
661
- props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
652
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
662
653
  }
663
654
  logger.debug('fetched props');
664
655
  return props;
@@ -667,9 +658,9 @@ const makeChatsSocket = (config) => {
667
658
  * modify a chat -- mark unread, read etc.
668
659
  * lastMessages must be sorted in reverse chronologically
669
660
  * requires the last messages till the last message received; required for archive & unread
670
- */
661
+ */
671
662
  const chatModify = (mod, jid) => {
672
- const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
663
+ const patch = chatModificationToAppPatch(mod, jid);
673
664
  return appPatch(patch);
674
665
  };
675
666
  /**
@@ -683,6 +674,32 @@ const makeChatsSocket = (config) => {
683
674
  }
684
675
  }, jid);
685
676
  };
677
+ /**
678
+ * Add or Edit Contact
679
+ */
680
+ const addOrEditContact = (jid, contact) => {
681
+ return chatModify({
682
+ contact
683
+ }, jid);
684
+ };
685
+ /**
686
+ * Remove Contact
687
+ */
688
+ const removeContact = (jid) => {
689
+ return chatModify({
690
+ contact: null
691
+ }, jid);
692
+ };
693
+ /**
694
+ * Adds label
695
+ */
696
+ const addLabel = (jid, labels) => {
697
+ return chatModify({
698
+ addLabel: {
699
+ ...labels
700
+ }
701
+ }, jid);
702
+ };
686
703
  /**
687
704
  * Adds label for the chats
688
705
  */
@@ -730,30 +747,24 @@ const makeChatsSocket = (config) => {
730
747
  * help ensure parity with WA Web
731
748
  * */
732
749
  const executeInitQueries = async () => {
733
- await Promise.all([
734
- fetchProps(),
735
- fetchBlocklist(),
736
- fetchPrivacySettings(),
737
- ]);
750
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
738
751
  };
739
752
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
740
- var _a, _b, _c;
741
753
  ev.emit('messages.upsert', { messages: [msg], type });
742
754
  if (!!msg.pushName) {
743
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
744
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
755
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
756
+ jid = jidNormalizedUser(jid);
745
757
  if (!msg.key.fromMe) {
746
758
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
747
759
  }
748
760
  // update our pushname too
749
- if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
761
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
750
762
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
751
763
  }
752
764
  }
753
- const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
765
+ const historyMsg = getHistoryMsg(msg.message);
754
766
  const shouldProcessHistoryMsg = historyMsg
755
- ? (shouldSyncHistoryMessage(historyMsg)
756
- && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
767
+ ? shouldSyncHistoryMessage(historyMsg) && PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
757
768
  : false;
758
769
  if (historyMsg && !authState.creds.myAppStateKeyId) {
759
770
  logger.warn('skipping app state sync, as myAppStateKeyId is not set');
@@ -761,32 +772,29 @@ const makeChatsSocket = (config) => {
761
772
  }
762
773
  await Promise.all([
763
774
  (async () => {
764
- if (historyMsg
765
- && authState.creds.myAppStateKeyId) {
775
+ if (historyMsg && authState.creds.myAppStateKeyId) {
766
776
  pendingAppStateSync = false;
767
777
  await doAppStateSync();
768
778
  }
769
779
  })(),
770
- (0, process_message_1.default)(msg, {
780
+ processMessage(msg, {
771
781
  shouldProcessHistoryMsg,
772
782
  placeholderResendCache,
773
783
  ev,
774
784
  creds: authState.creds,
775
785
  keyStore: authState.keys,
776
786
  logger,
777
- options: config.options,
778
- getMessage: config.getMessage,
787
+ options: config.options
779
788
  })
780
789
  ]);
781
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
782
- && pendingAppStateSync) {
790
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && pendingAppStateSync) {
783
791
  await doAppStateSync();
784
792
  pendingAppStateSync = false;
785
793
  }
786
794
  async function doAppStateSync() {
787
795
  if (!authState.creds.accountSyncCounter) {
788
796
  logger.info('doing initial app state sync');
789
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
797
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
790
798
  const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
791
799
  ev.emit('creds.update', { accountSyncCounter });
792
800
  if (needToFlushWithAppStateSync) {
@@ -799,7 +807,7 @@ const makeChatsSocket = (config) => {
799
807
  ws.on('CB:presence', handlePresenceUpdate);
800
808
  ws.on('CB:chatstate', handlePresenceUpdate);
801
809
  ws.on('CB:ib,,dirty', async (node) => {
802
- const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
810
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
803
811
  const type = attrs.type;
804
812
  switch (type) {
805
813
  case 'account_sync':
@@ -821,23 +829,19 @@ const makeChatsSocket = (config) => {
821
829
  }
822
830
  });
823
831
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
824
- var _a;
825
832
  if (connection === 'open') {
826
833
  if (fireInitQueries) {
827
- executeInitQueries()
828
- .catch(error => onUnexpectedError(error, 'init queries'));
834
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
829
835
  }
830
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
831
- .catch(error => onUnexpectedError(error, 'presence update requests'));
836
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
832
837
  }
833
- if (receivedPendingNotifications) {
834
- // if we don't have the app state key
838
+ if (receivedPendingNotifications && // if we don't have the app state key
835
839
  // we keep buffering events until we finally have
836
840
  // the key and can sync the messages
837
- if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
838
- ev.buffer();
839
- needToFlushWithAppStateSync = true;
840
- }
841
+ // todo scrutinize
842
+ !authState.creds?.myAppStateKeyId) {
843
+ ev.buffer();
844
+ needToFlushWithAppStateSync = true;
841
845
  }
842
846
  });
843
847
  return {
@@ -852,8 +856,8 @@ const makeChatsSocket = (config) => {
852
856
  profilePictureUrl,
853
857
  onWhatsApp,
854
858
  fetchBlocklist,
855
- fetchDisappearingDuration,
856
859
  fetchStatus,
860
+ fetchDisappearingDuration,
857
861
  updateProfilePicture,
858
862
  removeProfilePicture,
859
863
  updateProfileStatus,
@@ -872,6 +876,9 @@ const makeChatsSocket = (config) => {
872
876
  resyncAppState,
873
877
  chatModify,
874
878
  cleanDirtyBits,
879
+ addOrEditContact,
880
+ removeContact,
881
+ addLabel,
875
882
  addChatLabel,
876
883
  removeChatLabel,
877
884
  addMessageLabel,
@@ -879,4 +886,4 @@ const makeChatsSocket = (config) => {
879
886
  star
880
887
  };
881
888
  };
882
- exports.makeChatsSocket = makeChatsSocket;
889
+ //# sourceMappingURL=chats.js.map