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