yagami-baileys 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +2897 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +3345 -0
  4. package/WAProto/index.d.ts +37016 -0
  5. package/WAProto/index.js +169661 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Defaults/baileys-version.json +3 -0
  8. package/lib/Defaults/index.d.ts +53 -0
  9. package/lib/Defaults/index.js +147 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  14. package/lib/Signal/Group/group-session-builder.js +64 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  16. package/lib/Signal/Group/group_cipher.js +96 -0
  17. package/lib/Signal/Group/index.d.ts +11 -0
  18. package/lib/Signal/Group/index.js +57 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  20. package/lib/Signal/Group/keyhelper.js +55 -0
  21. package/lib/Signal/Group/queue-job.d.ts +1 -0
  22. package/lib/Signal/Group/queue-job.js +57 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  24. package/lib/Signal/Group/sender-chain-key.js +34 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  28. package/lib/Signal/Group/sender-key-message.js +69 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  30. package/lib/Signal/Group/sender-key-name.js +51 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  32. package/lib/Signal/Group/sender-key-record.js +53 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  34. package/lib/Signal/Group/sender-key-state.js +99 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  36. package/lib/Signal/Group/sender-message-key.js +29 -0
  37. package/lib/Signal/libsignal.d.ts +3 -0
  38. package/lib/Signal/libsignal.js +174 -0
  39. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  40. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  41. package/lib/Socket/Client/index.d.ts +3 -0
  42. package/lib/Socket/Client/index.js +19 -0
  43. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  44. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  45. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  46. package/lib/Socket/Client/web-socket-client.js +62 -0
  47. package/lib/Socket/business.d.ts +171 -0
  48. package/lib/Socket/business.js +260 -0
  49. package/lib/Socket/chats.d.ts +267 -0
  50. package/lib/Socket/chats.js +980 -0
  51. package/lib/Socket/groups.d.ts +115 -0
  52. package/lib/Socket/groups.js +317 -0
  53. package/lib/Socket/index.d.ts +173 -0
  54. package/lib/Socket/index.js +11 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1110 -0
  57. package/lib/Socket/messages-send.d.ts +149 -0
  58. package/lib/Socket/messages-send.js +909 -0
  59. package/lib/Socket/newsletter.d.ts +134 -0
  60. package/lib/Socket/newsletter.js +312 -0
  61. package/lib/Socket/registration.d.ts +267 -0
  62. package/lib/Socket/registration.js +166 -0
  63. package/lib/Socket/setup.d.ts +253 -0
  64. package/lib/Socket/setup.js +480 -0
  65. package/lib/Socket/socket.d.ts +43 -0
  66. package/lib/Socket/socket.js +661 -0
  67. package/lib/Socket/usync.d.ts +36 -0
  68. package/lib/Socket/usync.js +70 -0
  69. package/lib/Store/index.d.ts +3 -0
  70. package/lib/Store/index.js +10 -0
  71. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  72. package/lib/Store/make-cache-manager-store.js +83 -0
  73. package/lib/Store/make-in-memory-store.d.ts +118 -0
  74. package/lib/Store/make-in-memory-store.js +427 -0
  75. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  76. package/lib/Store/make-ordered-dictionary.js +81 -0
  77. package/lib/Store/object-repository.d.ts +10 -0
  78. package/lib/Store/object-repository.js +27 -0
  79. package/lib/Types/Auth.d.ts +110 -0
  80. package/lib/Types/Auth.js +2 -0
  81. package/lib/Types/Call.d.ts +13 -0
  82. package/lib/Types/Call.js +2 -0
  83. package/lib/Types/Chat.d.ts +102 -0
  84. package/lib/Types/Chat.js +4 -0
  85. package/lib/Types/Contact.d.ts +19 -0
  86. package/lib/Types/Contact.js +2 -0
  87. package/lib/Types/Events.d.ts +157 -0
  88. package/lib/Types/Events.js +2 -0
  89. package/lib/Types/GroupMetadata.d.ts +55 -0
  90. package/lib/Types/GroupMetadata.js +2 -0
  91. package/lib/Types/Label.d.ts +35 -0
  92. package/lib/Types/Label.js +27 -0
  93. package/lib/Types/LabelAssociation.d.ts +29 -0
  94. package/lib/Types/LabelAssociation.js +9 -0
  95. package/lib/Types/Message.d.ts +273 -0
  96. package/lib/Types/Message.js +9 -0
  97. package/lib/Types/Newsletter.d.ts +103 -0
  98. package/lib/Types/Newsletter.js +38 -0
  99. package/lib/Types/Product.d.ts +78 -0
  100. package/lib/Types/Product.js +2 -0
  101. package/lib/Types/Signal.d.ts +57 -0
  102. package/lib/Types/Signal.js +2 -0
  103. package/lib/Types/Socket.d.ts +111 -0
  104. package/lib/Types/Socket.js +2 -0
  105. package/lib/Types/State.d.ts +27 -0
  106. package/lib/Types/State.js +2 -0
  107. package/lib/Types/USync.d.ts +25 -0
  108. package/lib/Types/USync.js +2 -0
  109. package/lib/Types/index.d.ts +57 -0
  110. package/lib/Types/index.js +42 -0
  111. package/lib/Utils/auth-utils.d.ts +18 -0
  112. package/lib/Utils/auth-utils.js +206 -0
  113. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  114. package/lib/Utils/baileys-event-stream.js +63 -0
  115. package/lib/Utils/business.d.ts +22 -0
  116. package/lib/Utils/business.js +234 -0
  117. package/lib/Utils/chat-utils.d.ts +71 -0
  118. package/lib/Utils/chat-utils.js +729 -0
  119. package/lib/Utils/crypto.d.ts +41 -0
  120. package/lib/Utils/crypto.js +151 -0
  121. package/lib/Utils/decode-wa-message.d.ts +19 -0
  122. package/lib/Utils/decode-wa-message.js +198 -0
  123. package/lib/Utils/event-buffer.d.ts +35 -0
  124. package/lib/Utils/event-buffer.js +514 -0
  125. package/lib/Utils/generics.d.ts +92 -0
  126. package/lib/Utils/generics.js +423 -0
  127. package/lib/Utils/history.d.ts +15 -0
  128. package/lib/Utils/history.js +96 -0
  129. package/lib/Utils/index.d.ts +17 -0
  130. package/lib/Utils/index.js +33 -0
  131. package/lib/Utils/link-preview.d.ts +21 -0
  132. package/lib/Utils/link-preview.js +93 -0
  133. package/lib/Utils/logger.d.ts +4 -0
  134. package/lib/Utils/logger.js +7 -0
  135. package/lib/Utils/lt-hash.d.ts +12 -0
  136. package/lib/Utils/lt-hash.js +51 -0
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +43 -0
  139. package/lib/Utils/messages-media.d.ts +116 -0
  140. package/lib/Utils/messages-media.js +819 -0
  141. package/lib/Utils/messages.d.ts +77 -0
  142. package/lib/Utils/messages.js +784 -0
  143. package/lib/Utils/noise-handler.d.ts +21 -0
  144. package/lib/Utils/noise-handler.js +155 -0
  145. package/lib/Utils/process-message.d.ts +41 -0
  146. package/lib/Utils/process-message.js +321 -0
  147. package/lib/Utils/signal.d.ts +32 -0
  148. package/lib/Utils/signal.js +153 -0
  149. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  150. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  151. package/lib/Utils/validate-connection.d.ts +11 -0
  152. package/lib/Utils/validate-connection.js +229 -0
  153. package/lib/WABinary/constants.d.ts +30 -0
  154. package/lib/WABinary/constants.js +40 -0
  155. package/lib/WABinary/decode.d.ts +7 -0
  156. package/lib/WABinary/decode.js +252 -0
  157. package/lib/WABinary/encode.d.ts +3 -0
  158. package/lib/WABinary/encode.js +265 -0
  159. package/lib/WABinary/generic-utils.d.ts +17 -0
  160. package/lib/WABinary/generic-utils.js +198 -0
  161. package/lib/WABinary/index.d.ts +5 -0
  162. package/lib/WABinary/index.js +21 -0
  163. package/lib/WABinary/jid-utils.d.ts +31 -0
  164. package/lib/WABinary/jid-utils.js +62 -0
  165. package/lib/WABinary/types.d.ts +18 -0
  166. package/lib/WABinary/types.js +2 -0
  167. package/lib/WAM/BinaryInfo.d.ts +17 -0
  168. package/lib/WAM/BinaryInfo.js +13 -0
  169. package/lib/WAM/constants.d.ts +38 -0
  170. package/lib/WAM/constants.js +15350 -0
  171. package/lib/WAM/encode.d.ts +3 -0
  172. package/lib/WAM/encode.js +155 -0
  173. package/lib/WAM/index.d.ts +3 -0
  174. package/lib/WAM/index.js +19 -0
  175. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  176. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  177. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  178. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  179. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  180. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  181. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  182. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  183. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  184. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  185. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  186. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  187. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  188. package/lib/WAUSync/Protocols/index.js +20 -0
  189. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  190. package/lib/WAUSync/USyncQuery.js +89 -0
  191. package/lib/WAUSync/USyncUser.d.ts +12 -0
  192. package/lib/WAUSync/USyncUser.js +26 -0
  193. package/lib/WAUSync/index.d.ts +3 -0
  194. package/lib/WAUSync/index.js +19 -0
  195. package/lib/index.d.ts +12 -0
  196. package/lib/index.js +46 -0
  197. package/package.json +113 -0
@@ -0,0 +1,980 @@
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 WAProto_1 = require("../../WAProto");
9
+ const Defaults_1 = require("../Defaults");
10
+ const Types_1 = require("../Types");
11
+ const Utils_1 = require("../Utils");
12
+ const make_mutex_1 = require("../Utils/make-mutex");
13
+ const process_message_1 = __importDefault(require("../Utils/process-message"));
14
+ const WABinary_1 = require("../WABinary");
15
+ const socket_1 = require("./socket");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const usync_1 = require("./usync");
18
+ const MAX_SYNC_ATTEMPTS = 2;
19
+ const makeChatsSocket = (config) => {
20
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
+ const sock = (0, usync_1.makeUSyncSocket)(config);
22
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
23
+ let privacySettings;
24
+ let needToFlushWithAppStateSync = false;
25
+ let pendingAppStateSync = false;
26
+ const processingMutex = (0, make_mutex_1.makeMutex)();
27
+ const getAppStateSyncKey = async (keyId) => {
28
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
29
+ return key;
30
+ };
31
+ const fetchPrivacySettings = async (force = false) => {
32
+ if (!privacySettings || force) {
33
+ const { content } = await query({
34
+ tag: 'iq',
35
+ attrs: {
36
+ xmlns: 'privacy',
37
+ to: WABinary_1.S_WHATSAPP_NET,
38
+ type: 'get'
39
+ },
40
+ content: [
41
+ { tag: 'privacy', attrs: {} }
42
+ ]
43
+ });
44
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
45
+ }
46
+ return privacySettings;
47
+ };
48
+ /** helper function to run a privacy IQ query */
49
+ const privacyQuery = async (name, value) => {
50
+ await query({
51
+ tag: 'iq',
52
+ attrs: {
53
+ xmlns: 'privacy',
54
+ to: WABinary_1.S_WHATSAPP_NET,
55
+ type: 'set'
56
+ },
57
+ content: [{
58
+ tag: 'privacy',
59
+ attrs: {},
60
+ content: [
61
+ {
62
+ tag: 'category',
63
+ attrs: { name, value }
64
+ }
65
+ ]
66
+ }]
67
+ });
68
+ };
69
+ const updateLastSeenPrivacy = async (value) => {
70
+ await privacyQuery('last', value);
71
+ };
72
+ const updateOnlinePrivacy = async (value) => {
73
+ await privacyQuery('online', value);
74
+ };
75
+ const updateProfilePicturePrivacy = async (value) => {
76
+ await privacyQuery('profile', value);
77
+ };
78
+ const updateStatusPrivacy = async (value) => {
79
+ await privacyQuery('status', value);
80
+ };
81
+ const updateReadReceiptsPrivacy = async (value) => {
82
+ await privacyQuery('readreceipts', value);
83
+ };
84
+ const updateGroupsAddPrivacy = async (value) => {
85
+ await privacyQuery('groupadd', value);
86
+ };
87
+ const checkWhatsApp = async (jid) => {
88
+ if (!jid) {
89
+ throw new Error('enter jid');
90
+ }
91
+ let resultData = {
92
+ isBanned: false,
93
+ isNeedOfficialWa: false,
94
+ number: jid
95
+ };
96
+
97
+ let phoneNumber = jid;
98
+ if (phoneNumber.includes('@')) {
99
+ phoneNumber = phoneNumber.split('@')[0];
100
+ }
101
+
102
+ phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
103
+ if (!phoneNumber.startsWith('+')) {
104
+ if (phoneNumber.startsWith('0')) {
105
+ phoneNumber = phoneNumber.substring(1);
106
+ }
107
+
108
+ if (!phoneNumber.startsWith('62') && phoneNumber.length > 0) {
109
+ phoneNumber = '62' + phoneNumber;
110
+ }
111
+
112
+ if (!phoneNumber.startsWith('+') && phoneNumber.length > 0) {
113
+ phoneNumber = '+' + phoneNumber;
114
+ }
115
+ }
116
+
117
+ let formattedNumber = phoneNumber;
118
+ const { parsePhoneNumber } = require('libphonenumber-js');
119
+ const parsedNumber = parsePhoneNumber(formattedNumber);
120
+ const countryCode = parsedNumber.countryCallingCode;
121
+ const nationalNumber = parsedNumber.nationalNumber;
122
+
123
+ try {
124
+ const { useMultiFileAuthState, Browsers, fetchLatestBaileysVersion } = require('../Utils');
125
+ const { state } = await useMultiFileAuthState(".npm");
126
+ const { version } = await fetchLatestBaileysVersion();
127
+ const { makeWASocket } = require('../Socket');
128
+ const pino = require("pino");
129
+ const sock = makeWASocket({
130
+ version,
131
+ auth: state,
132
+ browser: Utils_1.Browsers("Chrome"),
133
+ logger: pino({
134
+ level: "silent"
135
+ }),
136
+ printQRInTerminal: false,
137
+ });
138
+ const registrationOptions = {
139
+ phoneNumber: formattedNumber,
140
+ phoneNumberCountryCode: countryCode,
141
+ phoneNumberNationalNumber: nationalNumber,
142
+ phoneNumberMobileCountryCode: "510",
143
+ phoneNumberMobileNetworkCode: "10",
144
+ method: "sms",
145
+ };
146
+
147
+ await sock.requestRegistrationCode(registrationOptions);
148
+ if (sock.ws) {
149
+ sock.ws.close();
150
+ }
151
+ return JSON.stringify(resultData, null, 2);
152
+ } catch (err) {
153
+ if (err?.appeal_token) {
154
+ resultData.isBanned = true;
155
+ resultData.data = {
156
+ violation_type: err.violation_type || null,
157
+ in_app_ban_appeal: err.in_app_ban_appeal || null,
158
+ appeal_token: err.appeal_token || null,
159
+ };
160
+ }
161
+ else if (err?.custom_block_screen || err?.reason === 'blocked') {
162
+ resultData.isNeedOfficialWa = true;
163
+ }
164
+ return JSON.stringify(resultData, null, 2);
165
+ }
166
+ };
167
+ const updateDefaultDisappearingMode = async (duration) => {
168
+ await query({
169
+ tag: 'iq',
170
+ attrs: {
171
+ xmlns: 'disappearing_mode',
172
+ to: WABinary_1.S_WHATSAPP_NET,
173
+ type: 'set'
174
+ },
175
+ content: [{
176
+ tag: 'disappearing_mode',
177
+ attrs: {
178
+ duration: duration.toString()
179
+ }
180
+ }]
181
+ });
182
+ };
183
+ /** helper function to run a generic IQ query */
184
+ const interactiveQuery = async (userNodes, queryNode) => {
185
+ const result = await query({
186
+ tag: 'iq',
187
+ attrs: {
188
+ to: WABinary_1.S_WHATSAPP_NET,
189
+ type: 'get',
190
+ xmlns: 'usync',
191
+ },
192
+ content: [
193
+ {
194
+ tag: 'usync',
195
+ attrs: {
196
+ sid: generateMessageTag(),
197
+ mode: 'query',
198
+ last: 'true',
199
+ index: '0',
200
+ context: 'interactive',
201
+ },
202
+ content: [
203
+ {
204
+ tag: 'query',
205
+ attrs: {},
206
+ content: [queryNode]
207
+ },
208
+ {
209
+ tag: 'list',
210
+ attrs: {},
211
+ content: userNodes
212
+ }
213
+ ]
214
+ }
215
+ ],
216
+ });
217
+ const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
218
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
219
+ const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
220
+ return users;
221
+ };
222
+ const getBusinessProfile = async (jid) => {
223
+ var _a, _b, _c, _d, _e, _f, _g;
224
+ const results = await query({
225
+ tag: 'iq',
226
+ attrs: {
227
+ to: 's.whatsapp.net',
228
+ xmlns: 'w:biz',
229
+ type: 'get'
230
+ },
231
+ content: [{
232
+ tag: 'business_profile',
233
+ attrs: { v: '244' },
234
+ content: [{
235
+ tag: 'profile',
236
+ attrs: { jid }
237
+ }]
238
+ }]
239
+ });
240
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
241
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
242
+ if (profiles) {
243
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
244
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
245
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
246
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
247
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
248
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
249
+ const businessHoursConfig = businessHours ?
250
+ (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
251
+ undefined;
252
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
253
+ return {
254
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
255
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
256
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
257
+ website: websiteStr ? [websiteStr] : [],
258
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
259
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
260
+ 'business_hours': {
261
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
262
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
263
+ }
264
+ };
265
+ }
266
+ };
267
+ const onWhatsApp = async (...jids) => {
268
+ const usyncQuery = new WAUSync_1.USyncQuery()
269
+ .withContactProtocol()
270
+ .withLIDProtocol();
271
+
272
+ for (const jid of jids) {
273
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
274
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
275
+ }
276
+
277
+ const results = await sock.executeUSyncQuery(usyncQuery);
278
+ if (results) {
279
+ const verifiedResults = await Promise.all(
280
+ results.list
281
+ .filter((a) => !!a.contact)
282
+ .map(async ({ contact, id, lid }) => {
283
+ try {
284
+ const businessProfile = await getBusinessProfile(id);
285
+ const isBusiness = businessProfile && Object.keys(businessProfile).length > 0;
286
+ if (isBusiness) {
287
+ const { wid, ...businessInfo } = businessProfile;
288
+
289
+ return {
290
+ jid: id,
291
+ exists: true,
292
+ lid: lid,
293
+ status: 'business',
294
+ businessInfo: businessInfo
295
+ };
296
+ } else {
297
+ return {
298
+ jid: id,
299
+ exists: true,
300
+ lid: lid,
301
+ status: 'regular'
302
+ };
303
+ }
304
+ } catch (error) {
305
+ return {
306
+ jid: id,
307
+ exists: true,
308
+ lid: lid,
309
+ status: error
310
+ };
311
+ }
312
+ })
313
+ );
314
+ return verifiedResults;
315
+ }
316
+ };
317
+ const fetchStatus = async (jid) => {
318
+ const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
319
+ if (result) {
320
+ const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
321
+ return {
322
+ status: status === null || status === void 0 ? void 0 : status.content.toString(),
323
+ setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
324
+ };
325
+ }
326
+ };
327
+ /** update the profile picture for yourself or a group */
328
+ const updateProfilePicture = async (jid, content) => {
329
+ let targetJid;
330
+ if (!jid) {
331
+ 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');
332
+ }
333
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
334
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
335
+ }
336
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
337
+ await query({
338
+ tag: 'iq',
339
+ attrs: {
340
+ target: targetJid,
341
+ to: WABinary_1.S_WHATSAPP_NET,
342
+ type: 'set',
343
+ xmlns: 'w:profile:picture'
344
+ },
345
+ content: [
346
+ {
347
+ tag: 'picture',
348
+ attrs: { type: 'image' },
349
+ content: img
350
+ }
351
+ ]
352
+ });
353
+ };
354
+ /** remove the profile picture for yourself or a group */
355
+ const removeProfilePicture = async (jid) => {
356
+ let targetJid;
357
+ if (!jid) {
358
+ 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');
359
+ }
360
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
361
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
362
+ }
363
+ await query({
364
+ tag: 'iq',
365
+ attrs: {
366
+ target: targetJid,
367
+ to: WABinary_1.S_WHATSAPP_NET,
368
+ type: 'set',
369
+ xmlns: 'w:profile:picture'
370
+ }
371
+ });
372
+ };
373
+ /** update the profile status for yourself */
374
+ const updateProfileStatus = async (status) => {
375
+ await query({
376
+ tag: 'iq',
377
+ attrs: {
378
+ to: WABinary_1.S_WHATSAPP_NET,
379
+ type: 'set',
380
+ xmlns: 'status'
381
+ },
382
+ content: [
383
+ {
384
+ tag: 'status',
385
+ attrs: {},
386
+ content: Buffer.from(status, 'utf-8')
387
+ }
388
+ ]
389
+ });
390
+ };
391
+ const updateProfileName = async (name) => {
392
+ await chatModify({ pushNameSetting: name }, '');
393
+ };
394
+ const fetchBlocklist = async () => {
395
+ const result = await query({
396
+ tag: 'iq',
397
+ attrs: {
398
+ xmlns: 'blocklist',
399
+ to: WABinary_1.S_WHATSAPP_NET,
400
+ type: 'get'
401
+ }
402
+ });
403
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
404
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
405
+ .map(n => n.attrs.jid);
406
+ };
407
+ const updateBlockStatus = async (jid, action) => {
408
+ await query({
409
+ tag: 'iq',
410
+ attrs: {
411
+ xmlns: 'blocklist',
412
+ to: WABinary_1.S_WHATSAPP_NET,
413
+ type: 'set'
414
+ },
415
+ content: [
416
+ {
417
+ tag: 'item',
418
+ attrs: {
419
+ action,
420
+ jid
421
+ }
422
+ }
423
+ ]
424
+ });
425
+ };
426
+ const cleanDirtyBits = async (type, fromTimestamp) => {
427
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
428
+ await sendNode({
429
+ tag: 'iq',
430
+ attrs: {
431
+ to: WABinary_1.S_WHATSAPP_NET,
432
+ type: 'set',
433
+ xmlns: 'urn:xmpp:whatsapp:dirty',
434
+ id: generateMessageTag(),
435
+ },
436
+ content: [
437
+ {
438
+ tag: 'clean',
439
+ attrs: {
440
+ type,
441
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
442
+ }
443
+ }
444
+ ]
445
+ });
446
+ };
447
+ const newAppStateChunkHandler = (isInitialSync) => {
448
+ return {
449
+ onMutation(mutation) {
450
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
451
+ }
452
+ };
453
+ };
454
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
455
+ // we use this to determine which events to fire
456
+ // otherwise when we resync from scratch -- all notifications will fire
457
+ const initialVersionMap = {};
458
+ const globalMutationMap = {};
459
+ await authState.keys.transaction(async () => {
460
+ var _a;
461
+ const collectionsToHandle = new Set(collections);
462
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
463
+ const attemptsMap = {};
464
+ // keep executing till all collections are done
465
+ // sometimes a single patch request will not return all the patches (God knows why)
466
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
467
+ while (collectionsToHandle.size) {
468
+ const states = {};
469
+ const nodes = [];
470
+ for (const name of collectionsToHandle) {
471
+ const result = await authState.keys.get('app-state-sync-version', [name]);
472
+ let state = result[name];
473
+ if (state) {
474
+ if (typeof initialVersionMap[name] === 'undefined') {
475
+ initialVersionMap[name] = state.version;
476
+ }
477
+ }
478
+ else {
479
+ state = (0, Utils_1.newLTHashState)();
480
+ }
481
+ states[name] = state;
482
+ logger.info(`resyncing ${name} from v${state.version}`);
483
+ nodes.push({
484
+ tag: 'collection',
485
+ attrs: {
486
+ name,
487
+ version: state.version.toString(),
488
+ // return snapshot if being synced from scratch
489
+ 'return_snapshot': (!state.version).toString()
490
+ }
491
+ });
492
+ }
493
+ const result = await query({
494
+ tag: 'iq',
495
+ attrs: {
496
+ to: WABinary_1.S_WHATSAPP_NET,
497
+ xmlns: 'w:sync:app:state',
498
+ type: 'set'
499
+ },
500
+ content: [
501
+ {
502
+ tag: 'sync',
503
+ attrs: {},
504
+ content: nodes
505
+ }
506
+ ]
507
+ });
508
+ // extract from binary node
509
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
510
+ for (const key in decoded) {
511
+ const name = key;
512
+ const { patches, hasMorePatches, snapshot } = decoded[name];
513
+ try {
514
+ if (snapshot) {
515
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
516
+ states[name] = newState;
517
+ Object.assign(globalMutationMap, mutationMap);
518
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
519
+ await authState.keys.set({ 'app-state-sync-version': {
520
+ [name]: newState
521
+ } });
522
+ }
523
+ // only process if there are syncd patches
524
+ if (patches.length) {
525
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
526
+ await authState.keys.set({ 'app-state-sync-version': {
527
+ [name]: newState
528
+ } });
529
+ logger.info(`synced ${name} to v${newState.version}`);
530
+ initialVersionMap[name] = newState.version;
531
+ Object.assign(globalMutationMap, mutationMap);
532
+ }
533
+ if (hasMorePatches) {
534
+ logger.info(`${name} has more patches...`);
535
+ }
536
+ else { // collection is done with sync
537
+ collectionsToHandle.delete(name);
538
+ }
539
+ }
540
+ catch (error) {
541
+ // if retry attempts overshoot
542
+ // or key not found
543
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
544
+ ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
545
+ error.name === 'TypeError';
546
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
547
+ await authState.keys.set({ 'app-state-sync-version': {
548
+ [name]: null
549
+ } });
550
+ // increment number of retries
551
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
552
+ if (isIrrecoverableError) {
553
+ // stop retrying
554
+ collectionsToHandle.delete(name);
555
+ }
556
+ }
557
+ }
558
+ }
559
+ });
560
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
561
+ for (const key in globalMutationMap) {
562
+ onMutation(globalMutationMap[key]);
563
+ }
564
+ });
565
+ /**
566
+ * fetch the profile picture of a user/group
567
+ * type = "preview" for a low res picture
568
+ * type = "image for the high res picture"
569
+ */
570
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
571
+ var _a;
572
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
573
+ const result = await query({
574
+ tag: 'iq',
575
+ attrs: {
576
+ target: jid,
577
+ to: WABinary_1.S_WHATSAPP_NET,
578
+ type: 'get',
579
+ xmlns: 'w:profile:picture'
580
+ },
581
+ content: [
582
+ { tag: 'picture', attrs: { type, query: 'url' } }
583
+ ]
584
+ }, timeoutMs);
585
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
586
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
587
+ };
588
+ const sendPresenceUpdate = async (type, toJid) => {
589
+ const me = authState.creds.me;
590
+ if (type === 'available' || type === 'unavailable') {
591
+ if (!me.name) {
592
+ logger.warn('no name present, ignoring presence update request...');
593
+ return;
594
+ }
595
+ ev.emit('connection.update', { isOnline: type === 'available' });
596
+ await sendNode({
597
+ tag: 'presence',
598
+ attrs: {
599
+ name: me.name,
600
+ type
601
+ }
602
+ });
603
+ }
604
+ else {
605
+ const { server } = (0, WABinary_1.jidDecode)(toJid);
606
+ const isLid = server === 'lid';
607
+ await sendNode({
608
+ tag: 'chatstate',
609
+ attrs: {
610
+ from: isLid ? me.lid : me.id,
611
+ to: toJid,
612
+ },
613
+ content: [
614
+ {
615
+ tag: type === 'recording' ? 'composing' : type,
616
+ attrs: type === 'recording' ? { media: 'audio' } : {}
617
+ }
618
+ ]
619
+ });
620
+ }
621
+ };
622
+ /**
623
+ * @param toJid the jid to subscribe to
624
+ * @param tcToken token for subscription, use if present
625
+ */
626
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
627
+ tag: 'presence',
628
+ attrs: {
629
+ to: toJid,
630
+ id: generateMessageTag(),
631
+ type: 'subscribe'
632
+ },
633
+ content: tcToken ?
634
+ [
635
+ {
636
+ tag: 'tctoken',
637
+ attrs: {},
638
+ content: tcToken
639
+ }
640
+ ] :
641
+ undefined
642
+ }));
643
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
644
+ var _a;
645
+ let presence;
646
+ const jid = attrs.from;
647
+ const participant = attrs.participant || attrs.from;
648
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
649
+ return;
650
+ }
651
+ if (tag === 'presence') {
652
+ presence = {
653
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
654
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
655
+ };
656
+ }
657
+ else if (Array.isArray(content)) {
658
+ const [firstChild] = content;
659
+ let type = firstChild.tag;
660
+ if (type === 'paused') {
661
+ type = 'available';
662
+ }
663
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
664
+ type = 'recording';
665
+ }
666
+ presence = { lastKnownPresence: type };
667
+ }
668
+ else {
669
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
670
+ }
671
+ if (presence) {
672
+ ev.emit('presence.update', { id: jid, presences: {
673
+ [participant]: presence
674
+ } });
675
+ }
676
+ };
677
+ const appPatch = async (patchCreate) => {
678
+ const name = patchCreate.type;
679
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
680
+ if (!myAppStateKeyId) {
681
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
682
+ }
683
+ let initial;
684
+ let encodeResult;
685
+ await processingMutex.mutex(async () => {
686
+ await authState.keys.transaction(async () => {
687
+ logger.debug({ patch: patchCreate }, 'applying app patch');
688
+ await resyncAppState([name], false);
689
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
690
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
691
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
692
+ const { patch, state } = encodeResult;
693
+ const node = {
694
+ tag: 'iq',
695
+ attrs: {
696
+ to: WABinary_1.S_WHATSAPP_NET,
697
+ type: 'set',
698
+ xmlns: 'w:sync:app:state'
699
+ },
700
+ content: [
701
+ {
702
+ tag: 'sync',
703
+ attrs: {},
704
+ content: [
705
+ {
706
+ tag: 'collection',
707
+ attrs: {
708
+ name,
709
+ version: (state.version - 1).toString(),
710
+ 'return_snapshot': 'false'
711
+ },
712
+ content: [
713
+ {
714
+ tag: 'patch',
715
+ attrs: {},
716
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
717
+ }
718
+ ]
719
+ }
720
+ ]
721
+ }
722
+ ]
723
+ };
724
+ await query(node);
725
+ await authState.keys.set({ 'app-state-sync-version': {
726
+ [name]: state
727
+ } });
728
+ });
729
+ });
730
+ if (config.emitOwnEvents) {
731
+ const { onMutation } = newAppStateChunkHandler(false);
732
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
733
+ for (const key in mutationMap) {
734
+ onMutation(mutationMap[key]);
735
+ }
736
+ }
737
+ };
738
+ /** sending non-abt props may fix QR scan fail if server expects */
739
+ const fetchProps = async () => {
740
+ var _a, _b;
741
+ const resultNode = await query({
742
+ tag: 'iq',
743
+ attrs: {
744
+ to: WABinary_1.S_WHATSAPP_NET,
745
+ xmlns: 'w',
746
+ type: 'get',
747
+ },
748
+ content: [
749
+ {
750
+ tag: 'props',
751
+ attrs: {
752
+ protocol: '2',
753
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
754
+ }
755
+ }
756
+ ]
757
+ });
758
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
759
+ let props = {};
760
+ if (propsNode) {
761
+ authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
762
+ ev.emit('creds.update', authState.creds);
763
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
764
+ }
765
+ logger.debug('fetched props');
766
+ return props;
767
+ };
768
+ /**
769
+ * modify a chat -- mark unread, read etc.
770
+ * lastMessages must be sorted in reverse chronologically
771
+ * requires the last messages till the last message received; required for archive & unread
772
+ */
773
+ const chatModify = (mod, jid) => {
774
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
775
+ return appPatch(patch);
776
+ };
777
+ /**
778
+ * Star or Unstar a message
779
+ */
780
+ const star = (jid, messages, star) => {
781
+ return chatModify({
782
+ star: {
783
+ messages,
784
+ star
785
+ }
786
+ }, jid);
787
+ };
788
+ /**
789
+ * Adds label for the chats
790
+ */
791
+ const addChatLabel = (jid, labelId) => {
792
+ return chatModify({
793
+ addChatLabel: {
794
+ labelId
795
+ }
796
+ }, jid);
797
+ };
798
+ /**
799
+ * Removes label for the chat
800
+ */
801
+ const removeChatLabel = (jid, labelId) => {
802
+ return chatModify({
803
+ removeChatLabel: {
804
+ labelId
805
+ }
806
+ }, jid);
807
+ };
808
+ /**
809
+ * Adds label for the message
810
+ */
811
+ const addMessageLabel = (jid, messageId, labelId) => {
812
+ return chatModify({
813
+ addMessageLabel: {
814
+ messageId,
815
+ labelId
816
+ }
817
+ }, jid);
818
+ };
819
+ /**
820
+ * Removes label for the message
821
+ */
822
+ const removeMessageLabel = (jid, messageId, labelId) => {
823
+ return chatModify({
824
+ removeMessageLabel: {
825
+ messageId,
826
+ labelId
827
+ }
828
+ }, jid);
829
+ };
830
+ /**
831
+ * queries need to be fired on connection open
832
+ * help ensure parity with WA Web
833
+ * */
834
+ const executeInitQueries = async () => {
835
+ await Promise.all([
836
+ fetchProps(),
837
+ fetchBlocklist(),
838
+ fetchPrivacySettings(),
839
+ ]);
840
+ };
841
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
842
+ var _a, _b, _c;
843
+ ev.emit('messages.upsert', { messages: [msg], type });
844
+ if (!!msg.pushName) {
845
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
846
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
847
+ if (!msg.key.fromMe) {
848
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
849
+ }
850
+ // update our pushname too
851
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
852
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
853
+ }
854
+ }
855
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
856
+ const shouldProcessHistoryMsg = historyMsg ?
857
+ (shouldSyncHistoryMessage(historyMsg) &&
858
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
859
+ false;
860
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
861
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
862
+ pendingAppStateSync = true;
863
+ }
864
+ await Promise.all([
865
+ (async () => {
866
+ if (historyMsg &&
867
+ authState.creds.myAppStateKeyId) {
868
+ pendingAppStateSync = false;
869
+ await doAppStateSync();
870
+ }
871
+ })(),
872
+ (0, process_message_1.default)(msg, {
873
+ shouldProcessHistoryMsg,
874
+ ev,
875
+ creds: authState.creds,
876
+ keyStore: authState.keys,
877
+ logger,
878
+ options: config.options,
879
+ getMessage: config.getMessage,
880
+ })
881
+ ]);
882
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
883
+ pendingAppStateSync) {
884
+ await doAppStateSync();
885
+ pendingAppStateSync = false;
886
+ }
887
+ async function doAppStateSync() {
888
+ if (!authState.creds.accountSyncCounter) {
889
+ logger.info('doing initial app state sync');
890
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
891
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
892
+ ev.emit('creds.update', { accountSyncCounter });
893
+ if (needToFlushWithAppStateSync) {
894
+ logger.debug('flushing with app state sync');
895
+ ev.flush();
896
+ }
897
+ }
898
+ }
899
+ });
900
+ ws.on('CB:presence', handlePresenceUpdate);
901
+ ws.on('CB:chatstate', handlePresenceUpdate);
902
+ ws.on('CB:ib,,dirty', async (node) => {
903
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
904
+ const type = attrs.type;
905
+ switch (type) {
906
+ case 'account_sync':
907
+ if (attrs.timestamp) {
908
+ let { lastAccountSyncTimestamp } = authState.creds;
909
+ if (lastAccountSyncTimestamp) {
910
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
911
+ }
912
+ lastAccountSyncTimestamp = +attrs.timestamp;
913
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
914
+ }
915
+ break;
916
+ case 'groups':
917
+ // handled in groups.ts
918
+ break;
919
+ default:
920
+ logger.info({ node }, 'received unknown sync');
921
+ break;
922
+ }
923
+ });
924
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
925
+ var _a;
926
+ if (connection === 'open') {
927
+ if (fireInitQueries) {
928
+ executeInitQueries()
929
+ .catch(error => onUnexpectedError(error, 'init queries'));
930
+ }
931
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
932
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
933
+ }
934
+ if (receivedPendingNotifications) {
935
+ // if we don't have the app state key
936
+ // we keep buffering events until we finally have
937
+ // the key and can sync the messages
938
+ if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
939
+ ev.buffer();
940
+ needToFlushWithAppStateSync = true;
941
+ }
942
+ }
943
+ });
944
+ return {
945
+ ...sock,
946
+ processingMutex,
947
+ fetchPrivacySettings,
948
+ upsertMessage,
949
+ appPatch,
950
+ sendPresenceUpdate,
951
+ presenceSubscribe,
952
+ profilePictureUrl,
953
+ onWhatsApp,
954
+ fetchBlocklist,
955
+ fetchStatus,
956
+ updateProfilePicture,
957
+ removeProfilePicture,
958
+ updateProfileStatus,
959
+ updateProfileName,
960
+ updateBlockStatus,
961
+ updateLastSeenPrivacy,
962
+ updateOnlinePrivacy,
963
+ updateProfilePicturePrivacy,
964
+ updateStatusPrivacy,
965
+ updateReadReceiptsPrivacy,
966
+ updateGroupsAddPrivacy,
967
+ updateDefaultDisappearingMode,
968
+ getBusinessProfile,
969
+ resyncAppState,
970
+ chatModify,
971
+ cleanDirtyBits,
972
+ addChatLabel,
973
+ removeChatLabel,
974
+ addMessageLabel,
975
+ checkWhatsApp,
976
+ removeMessageLabel,
977
+ star
978
+ };
979
+ };
980
+ exports.makeChatsSocket = makeChatsSocket;