@vanzxy/baileys 1.4.0 → 1.4.2

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 (114) hide show
  1. package/cjs/WAProto/index.js +106053 -0
  2. package/cjs/lib/Defaults/index.js +168 -0
  3. package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
  4. package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
  5. package/cjs/lib/Signal/Group/group_cipher.js +86 -0
  6. package/cjs/lib/Signal/Group/index.js +58 -0
  7. package/cjs/lib/Signal/Group/keyhelper.js +56 -0
  8. package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
  9. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  10. package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
  11. package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
  12. package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
  13. package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
  14. package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
  15. package/cjs/lib/Signal/libsignal.js +467 -0
  16. package/cjs/lib/Signal/lid-mapping.js +281 -0
  17. package/cjs/lib/Socket/Client/index.js +19 -0
  18. package/cjs/lib/Socket/Client/types.js +15 -0
  19. package/cjs/lib/Socket/Client/websocket.js +61 -0
  20. package/cjs/lib/Socket/business.js +384 -0
  21. package/cjs/lib/Socket/chats.js +1257 -0
  22. package/cjs/lib/Socket/communities.js +442 -0
  23. package/cjs/lib/Socket/dugong.js +753 -0
  24. package/cjs/lib/Socket/groups.js +360 -0
  25. package/cjs/lib/Socket/index.js +19 -0
  26. package/cjs/lib/Socket/messages-recv.js +1790 -0
  27. package/cjs/lib/Socket/messages-send.js +1390 -0
  28. package/cjs/lib/Socket/mex.js +46 -0
  29. package/cjs/lib/Socket/newsletter.js +340 -0
  30. package/cjs/lib/Socket/socket.js +1007 -0
  31. package/cjs/lib/Store/index.js +20 -0
  32. package/cjs/lib/Store/make-in-memory-store.js +438 -0
  33. package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
  34. package/cjs/lib/Store/object-repository.js +28 -0
  35. package/cjs/lib/Types/Auth.js +3 -0
  36. package/cjs/lib/Types/Bussines.js +3 -0
  37. package/cjs/lib/Types/Call.js +3 -0
  38. package/cjs/lib/Types/Chat.js +11 -0
  39. package/cjs/lib/Types/Contact.js +3 -0
  40. package/cjs/lib/Types/Events.js +4 -0
  41. package/cjs/lib/Types/GroupMetadata.js +3 -0
  42. package/cjs/lib/Types/Label.js +26 -0
  43. package/cjs/lib/Types/LabelAssociation.js +8 -0
  44. package/cjs/lib/Types/Message.js +19 -0
  45. package/cjs/lib/Types/Mex.js +40 -0
  46. package/cjs/lib/Types/Product.js +3 -0
  47. package/cjs/lib/Types/RichType.js +24 -0
  48. package/cjs/lib/Types/Signal.js +4 -0
  49. package/cjs/lib/Types/Socket.js +4 -0
  50. package/cjs/lib/Types/State.js +54 -0
  51. package/cjs/lib/Types/USync.js +4 -0
  52. package/cjs/lib/Types/index.js +42 -0
  53. package/cjs/lib/Utils/MessageBuilder.js +2164 -0
  54. package/cjs/lib/Utils/auth-utils.js +312 -0
  55. package/cjs/lib/Utils/browser-utils.js +32 -0
  56. package/cjs/lib/Utils/business.js +245 -0
  57. package/cjs/lib/Utils/chat-utils.js +937 -0
  58. package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
  59. package/cjs/lib/Utils/crypto.js +196 -0
  60. package/cjs/lib/Utils/decode-wa-message.js +324 -0
  61. package/cjs/lib/Utils/event-buffer.js +643 -0
  62. package/cjs/lib/Utils/generics.js +429 -0
  63. package/cjs/lib/Utils/history.js +151 -0
  64. package/cjs/lib/Utils/identity-change-handler.js +56 -0
  65. package/cjs/lib/Utils/index.js +42 -0
  66. package/cjs/lib/Utils/link-preview.js +122 -0
  67. package/cjs/lib/Utils/logger.js +8 -0
  68. package/cjs/lib/Utils/lt-hash.js +62 -0
  69. package/cjs/lib/Utils/make-mutex.js +38 -0
  70. package/cjs/lib/Utils/message-retry-manager.js +267 -0
  71. package/cjs/lib/Utils/messages-media.js +933 -0
  72. package/cjs/lib/Utils/messages.js +2175 -0
  73. package/cjs/lib/Utils/noise-handler.js +205 -0
  74. package/cjs/lib/Utils/offline-node-processor.js +43 -0
  75. package/cjs/lib/Utils/pre-key-manager.js +113 -0
  76. package/cjs/lib/Utils/process-message.js +772 -0
  77. package/cjs/lib/Utils/reporting-utils.js +263 -0
  78. package/cjs/lib/Utils/rich-message-utils.js +439 -0
  79. package/cjs/lib/Utils/signal.js +214 -0
  80. package/cjs/lib/Utils/stanza-ack.js +41 -0
  81. package/cjs/lib/Utils/sync-action-utils.js +54 -0
  82. package/cjs/lib/Utils/tc-token-utils.js +174 -0
  83. package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
  84. package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
  85. package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
  86. package/cjs/lib/Utils/validate-connection.js +210 -0
  87. package/cjs/lib/WABinary/constants.js +1470 -0
  88. package/cjs/lib/WABinary/decode.js +301 -0
  89. package/cjs/lib/WABinary/encode.js +257 -0
  90. package/cjs/lib/WABinary/generic-utils.js +274 -0
  91. package/cjs/lib/WABinary/index.js +22 -0
  92. package/cjs/lib/WABinary/jid-utils.js +114 -0
  93. package/cjs/lib/WABinary/types.js +37 -0
  94. package/cjs/lib/WAM/BinaryInfo.js +14 -0
  95. package/cjs/lib/WAM/constants.js +22856 -0
  96. package/cjs/lib/WAM/encode.js +154 -0
  97. package/cjs/lib/WAM/index.js +20 -0
  98. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  99. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
  100. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  101. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
  103. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
  104. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
  105. package/cjs/lib/WAUSync/Protocols/index.js +24 -0
  106. package/cjs/lib/WAUSync/USyncQuery.js +126 -0
  107. package/cjs/lib/WAUSync/USyncUser.js +35 -0
  108. package/cjs/lib/WAUSync/index.js +20 -0
  109. package/cjs/lib/index.js +34 -0
  110. package/cjs/package.json +1 -0
  111. package/lib/Socket/messages-send.js +4 -3
  112. package/lib/Utils/messages.js +4 -1
  113. package/package.json +16 -5
  114. package/postinstall-banner.js +3 -2
@@ -0,0 +1,1257 @@
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 node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
+ const boom_1 = require("@hapi/boom");
9
+ const index_js_1 = require("../../WAProto/index.js");
10
+ const index_js_2 = require("../Defaults/index.js");
11
+ const index_js_3 = require("../Types/index.js");
12
+ const State_js_1 = require("../Types/State.js");
13
+ const index_js_4 = require("../Utils/index.js");
14
+ const make_mutex_js_1 = require("../Utils/make-mutex.js");
15
+ const process_message_js_1 = __importDefault(require("../Utils/process-message.js"));
16
+ const tc_token_utils_js_1 = require("../Utils/tc-token-utils.js");
17
+ const index_js_5 = require("../WABinary/index.js");
18
+ const index_js_6 = require("../WAUSync/index.js");
19
+ const socket_js_1 = require("./socket.js");
20
+ const makeChatsSocket = (config) => {
21
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
22
+ const sock = (0, socket_js_1.makeSocket)(config);
23
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
24
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
25
+ let privacySettings;
26
+ /** Server-assigned AB props for protocol behavior. */
27
+ const serverProps = {
28
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
29
+ privacyTokenOn1to1: true,
30
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
31
+ profilePicPrivacyToken: true,
32
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
33
+ lidTrustedTokenIssueToLid: false
34
+ };
35
+ let syncState = State_js_1.SyncState.Connecting;
36
+ /** this mutex ensures that messages are processed in order */
37
+ const messageMutex = (0, make_mutex_js_1.makeMutex)();
38
+ /** this mutex ensures that receipts are processed in order */
39
+ const receiptMutex = (0, make_mutex_js_1.makeMutex)();
40
+ /** this mutex ensures that app state patches are processed in order */
41
+ const appStatePatchMutex = (0, make_mutex_js_1.makeMutex)();
42
+ /** this mutex ensures that notifications are processed in order */
43
+ const notificationMutex = (0, make_mutex_js_1.makeMutex)();
44
+ // Timeout for AwaitingInitialSync state
45
+ let awaitingSyncTimeout;
46
+ // In-memory history sync completion tracking (resets on reconnection)
47
+ const historySyncStatus = {
48
+ initialBootstrapComplete: false,
49
+ recentSyncComplete: false
50
+ };
51
+ let historySyncPausedTimeout;
52
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
53
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
54
+ const blockedCollections = new Set();
55
+ const placeholderResendCache = config.placeholderResendCache ||
56
+ new node_cache_1.default({
57
+ stdTTL: index_js_2.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
58
+ useClones: false
59
+ });
60
+ /** helper function to fetch the given app state sync key */
61
+ const getAppStateSyncKey = async (keyId) => {
62
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
63
+ return key;
64
+ };
65
+ const fetchPrivacySettings = async (force = false) => {
66
+ if (!privacySettings || force) {
67
+ const { content } = await query({
68
+ tag: 'iq',
69
+ attrs: {
70
+ xmlns: 'privacy',
71
+ to: index_js_5.S_WHATSAPP_NET,
72
+ type: 'get'
73
+ },
74
+ content: [{ tag: 'privacy', attrs: {} }]
75
+ });
76
+ privacySettings = (0, index_js_5.reduceBinaryNodeToDictionary)(content?.[0], 'category');
77
+ }
78
+ return privacySettings;
79
+ };
80
+ /** helper function to run a privacy IQ query */
81
+ const privacyQuery = async (name, value) => {
82
+ await query({
83
+ tag: 'iq',
84
+ attrs: {
85
+ xmlns: 'privacy',
86
+ to: index_js_5.S_WHATSAPP_NET,
87
+ type: 'set'
88
+ },
89
+ content: [
90
+ {
91
+ tag: 'privacy',
92
+ attrs: {},
93
+ content: [
94
+ {
95
+ tag: 'category',
96
+ attrs: { name, value }
97
+ }
98
+ ]
99
+ }
100
+ ]
101
+ });
102
+ };
103
+ const updateMessagesPrivacy = async (value) => {
104
+ await privacyQuery('messages', value);
105
+ };
106
+ const updateCallPrivacy = async (value) => {
107
+ await privacyQuery('calladd', value);
108
+ };
109
+ const updateLastSeenPrivacy = async (value) => {
110
+ await privacyQuery('last', value);
111
+ };
112
+ const updateOnlinePrivacy = async (value) => {
113
+ await privacyQuery('online', value);
114
+ };
115
+ const updateProfilePicturePrivacy = async (value) => {
116
+ await privacyQuery('profile', value);
117
+ };
118
+ const updateStatusPrivacy = async (value) => {
119
+ await privacyQuery('status', value);
120
+ };
121
+ const updateReadReceiptsPrivacy = async (value) => {
122
+ await privacyQuery('readreceipts', value);
123
+ };
124
+ const updateGroupsAddPrivacy = async (value) => {
125
+ await privacyQuery('groupadd', value);
126
+ };
127
+ const updateDefaultDisappearingMode = async (duration) => {
128
+ await query({
129
+ tag: 'iq',
130
+ attrs: {
131
+ xmlns: 'disappearing_mode',
132
+ to: index_js_5.S_WHATSAPP_NET,
133
+ type: 'set'
134
+ },
135
+ content: [
136
+ {
137
+ tag: 'disappearing_mode',
138
+ attrs: {
139
+ duration: duration.toString()
140
+ }
141
+ }
142
+ ]
143
+ });
144
+ };
145
+ const getBotListV2 = async () => {
146
+ const resp = await query({
147
+ tag: 'iq',
148
+ attrs: {
149
+ xmlns: 'bot',
150
+ to: index_js_5.S_WHATSAPP_NET,
151
+ type: 'get'
152
+ },
153
+ content: [
154
+ {
155
+ tag: 'bot',
156
+ attrs: {
157
+ v: '2'
158
+ }
159
+ }
160
+ ]
161
+ });
162
+ const botNode = (0, index_js_5.getBinaryNodeChild)(resp, 'bot');
163
+ const botList = [];
164
+ for (const section of (0, index_js_5.getBinaryNodeChildren)(botNode, 'section')) {
165
+ if (section.attrs.type === 'all') {
166
+ for (const bot of (0, index_js_5.getBinaryNodeChildren)(section, 'bot')) {
167
+ botList.push({
168
+ jid: bot.attrs.jid,
169
+ personaId: bot.attrs['persona_id']
170
+ });
171
+ }
172
+ }
173
+ }
174
+ return botList;
175
+ };
176
+ const fetchStatus = async (...jids) => {
177
+ const usyncQuery = new index_js_6.USyncQuery().withStatusProtocol();
178
+ for (const jid of jids) {
179
+ usyncQuery.withUser(new index_js_6.USyncUser().withId(jid));
180
+ }
181
+ const result = await sock.executeUSyncQuery(usyncQuery);
182
+ if (result) {
183
+ return result.list;
184
+ }
185
+ };
186
+ const fetchDisappearingDuration = async (...jids) => {
187
+ const usyncQuery = new index_js_6.USyncQuery().withDisappearingModeProtocol();
188
+ for (const jid of jids) {
189
+ usyncQuery.withUser(new index_js_6.USyncUser().withId(jid));
190
+ }
191
+ const result = await sock.executeUSyncQuery(usyncQuery);
192
+ if (result) {
193
+ return result.list;
194
+ }
195
+ };
196
+ // Lia@Note 06-02-26 --- Quick helper only. This function exists solely for faster lookup with caching.
197
+ const findUserId = async (pnLid) => {
198
+ const normalizedJid = (0, index_js_5.jidNormalizedUser)(pnLid);
199
+ const userId = {
200
+ lid: undefined,
201
+ phoneNumber: undefined
202
+ };
203
+ if ((0, index_js_5.isPnUser)(normalizedJid) || (0, index_js_5.isHostedPnUser)(normalizedJid)) {
204
+ userId.phoneNumber = normalizedJid;
205
+ userId.lid = (0, index_js_5.jidNormalizedUser)((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid);
206
+ }
207
+ else if ((0, index_js_5.isLidUser)(normalizedJid) || (0, index_js_5.isHostedLidUser)(normalizedJid)) {
208
+ userId.lid = normalizedJid;
209
+ userId.phoneNumber = (0, index_js_5.jidNormalizedUser)((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn);
210
+ }
211
+ else {
212
+ throw new boom_1.Boom('Invalid id input to find user ids', { statusCode: 400 });
213
+ }
214
+ return userId;
215
+ };
216
+ /** update the profile picture for yourself or a group */
217
+ const updateProfilePicture = async (jid, content, dimensions) => {
218
+ let targetJid;
219
+ if (!jid) {
220
+ 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');
221
+ }
222
+ if ((0, index_js_5.jidNormalizedUser)(jid) !== (0, index_js_5.jidNormalizedUser)(authState.creds.me.id)) {
223
+ targetJid = (0, index_js_5.jidNormalizedUser)(jid); // in case it is someone other than us
224
+ }
225
+ else {
226
+ targetJid = undefined;
227
+ }
228
+ const { img } = await (0, index_js_4.generateProfilePicture)(content, dimensions);
229
+ await query({
230
+ tag: 'iq',
231
+ attrs: {
232
+ to: index_js_5.S_WHATSAPP_NET,
233
+ type: 'set',
234
+ xmlns: 'w:profile:picture',
235
+ ...(targetJid ? { target: targetJid } : {})
236
+ },
237
+ content: [
238
+ {
239
+ tag: 'picture',
240
+ attrs: { type: 'image' },
241
+ content: img
242
+ }
243
+ ]
244
+ });
245
+ };
246
+ /** remove the profile picture for yourself or a group */
247
+ const removeProfilePicture = async (jid) => {
248
+ let targetJid;
249
+ if (!jid) {
250
+ 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');
251
+ }
252
+ if ((0, index_js_5.jidNormalizedUser)(jid) !== (0, index_js_5.jidNormalizedUser)(authState.creds.me.id)) {
253
+ targetJid = (0, index_js_5.jidNormalizedUser)(jid); // in case it is someone other than us
254
+ }
255
+ else {
256
+ targetJid = undefined;
257
+ }
258
+ await query({
259
+ tag: 'iq',
260
+ attrs: {
261
+ to: index_js_5.S_WHATSAPP_NET,
262
+ type: 'set',
263
+ xmlns: 'w:profile:picture',
264
+ ...(targetJid ? { target: targetJid } : {})
265
+ }
266
+ });
267
+ };
268
+ /** update the profile status for yourself */
269
+ const updateProfileStatus = async (status) => {
270
+ await query({
271
+ tag: 'iq',
272
+ attrs: {
273
+ to: index_js_5.S_WHATSAPP_NET,
274
+ type: 'set',
275
+ xmlns: 'status'
276
+ },
277
+ content: [
278
+ {
279
+ tag: 'status',
280
+ attrs: {},
281
+ content: Buffer.from(status, 'utf-8')
282
+ }
283
+ ]
284
+ });
285
+ };
286
+ const updateProfileName = async (name) => {
287
+ await chatModify({ pushNameSetting: name }, '');
288
+ };
289
+ const fetchBlocklist = async () => {
290
+ const result = await query({
291
+ tag: 'iq',
292
+ attrs: {
293
+ xmlns: 'blocklist',
294
+ to: index_js_5.S_WHATSAPP_NET,
295
+ type: 'get'
296
+ }
297
+ });
298
+ const listNode = (0, index_js_5.getBinaryNodeChild)(result, 'list');
299
+ return (0, index_js_5.getBinaryNodeChildren)(listNode, 'item').map(n => n.attrs.jid);
300
+ };
301
+ const updateBlockStatus = async (jid, action) => {
302
+ const normalizedJid = (0, index_js_5.jidNormalizedUser)(jid);
303
+ let lid;
304
+ let pn_jid;
305
+ if ((0, index_js_5.isLidUser)(normalizedJid) || (0, index_js_5.isHostedLidUser)(normalizedJid)) {
306
+ lid = normalizedJid;
307
+ if (action === 'block') {
308
+ const pn = (await findUserId(normalizedJid)).phoneNumber;
309
+ if (!pn) {
310
+ throw new boom_1.Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
311
+ }
312
+ pn_jid = (0, index_js_5.jidNormalizedUser)(pn);
313
+ }
314
+ }
315
+ else if ((0, index_js_5.isPnUser)(normalizedJid) || (0, index_js_5.isHostedPnUser)(normalizedJid)) {
316
+ const mapped = (await findUserId(normalizedJid)).lid;
317
+ if (!mapped) {
318
+ throw new boom_1.Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
319
+ }
320
+ lid = mapped;
321
+ if (action === 'block') {
322
+ pn_jid = (0, index_js_5.jidNormalizedUser)(normalizedJid);
323
+ }
324
+ }
325
+ else {
326
+ throw new boom_1.Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
327
+ }
328
+ const itemAttrs = {
329
+ action,
330
+ jid: lid
331
+ };
332
+ if (action === 'block') {
333
+ if (!pn_jid) {
334
+ throw new boom_1.Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
335
+ }
336
+ itemAttrs.pn_jid = pn_jid;
337
+ }
338
+ await query({
339
+ tag: 'iq',
340
+ attrs: {
341
+ xmlns: 'blocklist',
342
+ to: index_js_5.S_WHATSAPP_NET,
343
+ type: 'set'
344
+ },
345
+ content: [
346
+ {
347
+ tag: 'item',
348
+ attrs: itemAttrs
349
+ }
350
+ ]
351
+ });
352
+ };
353
+ const getBusinessProfile = async (jid) => {
354
+ const results = await query({
355
+ tag: 'iq',
356
+ attrs: {
357
+ to: 's.whatsapp.net',
358
+ xmlns: 'w:biz',
359
+ type: 'get'
360
+ },
361
+ content: [
362
+ {
363
+ tag: 'business_profile',
364
+ attrs: { v: '244' },
365
+ content: [
366
+ {
367
+ tag: 'profile',
368
+ attrs: { jid }
369
+ }
370
+ ]
371
+ }
372
+ ]
373
+ });
374
+ const profileNode = (0, index_js_5.getBinaryNodeChild)(results, 'business_profile');
375
+ const profiles = (0, index_js_5.getBinaryNodeChild)(profileNode, 'profile');
376
+ if (profiles) {
377
+ const address = (0, index_js_5.getBinaryNodeChild)(profiles, 'address');
378
+ const description = (0, index_js_5.getBinaryNodeChild)(profiles, 'description');
379
+ const website = (0, index_js_5.getBinaryNodeChild)(profiles, 'website');
380
+ const email = (0, index_js_5.getBinaryNodeChild)(profiles, 'email');
381
+ const category = (0, index_js_5.getBinaryNodeChild)((0, index_js_5.getBinaryNodeChild)(profiles, 'categories'), 'category');
382
+ const businessHours = (0, index_js_5.getBinaryNodeChild)(profiles, 'business_hours');
383
+ const businessHoursConfig = businessHours
384
+ ? (0, index_js_5.getBinaryNodeChildren)(businessHours, 'business_hours_config')
385
+ : undefined;
386
+ const websiteStr = website?.content?.toString();
387
+ return {
388
+ wid: profiles.attrs?.jid,
389
+ address: address?.content?.toString(),
390
+ description: description?.content?.toString() || '',
391
+ website: websiteStr ? [websiteStr] : [],
392
+ email: email?.content?.toString(),
393
+ category: category?.content?.toString(),
394
+ business_hours: {
395
+ timezone: businessHours?.attrs?.timezone,
396
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
397
+ }
398
+ };
399
+ }
400
+ };
401
+ const cleanDirtyBits = async (type, fromTimestamp) => {
402
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
403
+ await sendNode({
404
+ tag: 'iq',
405
+ attrs: {
406
+ to: index_js_5.S_WHATSAPP_NET,
407
+ type: 'set',
408
+ xmlns: 'urn:xmpp:whatsapp:dirty',
409
+ id: generateMessageTag()
410
+ },
411
+ content: [
412
+ {
413
+ tag: 'clean',
414
+ attrs: {
415
+ type,
416
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
417
+ }
418
+ }
419
+ ]
420
+ });
421
+ };
422
+ const newAppStateChunkHandler = (isInitialSync) => {
423
+ return {
424
+ onMutation(mutation) {
425
+ (0, index_js_4.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
426
+ }
427
+ };
428
+ };
429
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
430
+ const appStateSyncKeyCache = new Map();
431
+ const getCachedAppStateSyncKey = async (keyId) => {
432
+ if (appStateSyncKeyCache.has(keyId)) {
433
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
434
+ }
435
+ const key = await getAppStateSyncKey(keyId);
436
+ appStateSyncKeyCache.set(keyId, key ?? null);
437
+ return key;
438
+ };
439
+ // we use this to determine which events to fire
440
+ // otherwise when we resync from scratch -- all notifications will fire
441
+ const initialVersionMap = {};
442
+ const globalMutationMap = {};
443
+ await authState.keys.transaction(async () => {
444
+ const collectionsToHandle = new Set(collections);
445
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
446
+ const attemptsMap = {};
447
+ // collections that failed and need a full snapshot on retry
448
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
449
+ const forceSnapshotCollections = new Set();
450
+ // keep executing till all collections are done
451
+ // sometimes a single patch request will not return all the patches (God knows why)
452
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
453
+ while (collectionsToHandle.size) {
454
+ const states = {};
455
+ const nodes = [];
456
+ for (const name of collectionsToHandle) {
457
+ const result = await authState.keys.get('app-state-sync-version', [name]);
458
+ let state = result[name];
459
+ if (state) {
460
+ state = (0, index_js_4.ensureLTHashStateVersion)(state);
461
+ if (typeof initialVersionMap[name] === 'undefined') {
462
+ initialVersionMap[name] = state.version;
463
+ }
464
+ }
465
+ else {
466
+ state = (0, index_js_4.newLTHashState)();
467
+ }
468
+ states[name] = state;
469
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
470
+ if (shouldForceSnapshot) {
471
+ forceSnapshotCollections.delete(name);
472
+ }
473
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
474
+ nodes.push({
475
+ tag: 'collection',
476
+ attrs: {
477
+ name,
478
+ version: state.version.toString(),
479
+ // return snapshot if syncing from scratch or forcing after a failed attempt
480
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
481
+ }
482
+ });
483
+ }
484
+ const result = await query({
485
+ tag: 'iq',
486
+ attrs: {
487
+ to: index_js_5.S_WHATSAPP_NET,
488
+ xmlns: 'w:sync:app:state',
489
+ type: 'set'
490
+ },
491
+ content: [
492
+ {
493
+ tag: 'sync',
494
+ attrs: {},
495
+ content: nodes
496
+ }
497
+ ]
498
+ });
499
+ // extract from binary node
500
+ const decoded = await (0, index_js_4.extractSyncdPatches)(result, config?.options);
501
+ for (const key in decoded) {
502
+ const name = key;
503
+ const { patches, hasMorePatches, snapshot } = decoded[name];
504
+ try {
505
+ if (snapshot) {
506
+ const { state: newState, mutationMap } = await (0, index_js_4.decodeSyncdSnapshot)(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
507
+ states[name] = newState;
508
+ Object.assign(globalMutationMap, mutationMap);
509
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
510
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
511
+ }
512
+ // only process if there are syncd patches
513
+ if (patches.length) {
514
+ const { state: newState, mutationMap } = await (0, index_js_4.decodePatches)(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
515
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
516
+ logger.info(`synced ${name} to v${newState.version}`);
517
+ initialVersionMap[name] = newState.version;
518
+ Object.assign(globalMutationMap, mutationMap);
519
+ }
520
+ if (hasMorePatches) {
521
+ logger.info(`${name} has more patches...`);
522
+ }
523
+ else {
524
+ // collection is done with sync
525
+ collectionsToHandle.delete(name);
526
+ }
527
+ }
528
+ catch (error) {
529
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
530
+ const logData = {
531
+ name,
532
+ attempt: attemptsMap[name],
533
+ version: states[name].version,
534
+ statusCode: error.output?.statusCode,
535
+ errorType: error.name,
536
+ error: error.stack
537
+ };
538
+ if ((0, index_js_4.isMissingKeyError)(error) && attemptsMap[name] >= index_js_4.MAX_SYNC_ATTEMPTS) {
539
+ // WA Web treats missing keys as "Blocked" — park the collection
540
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
541
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
542
+ blockedCollections.add(name);
543
+ collectionsToHandle.delete(name);
544
+ }
545
+ else if ((0, index_js_4.isMissingKeyError)(error)) {
546
+ // Retry with a snapshot which may use a different key.
547
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
548
+ forceSnapshotCollections.add(name);
549
+ }
550
+ else if ((0, index_js_4.isAppStateSyncIrrecoverable)(error, attemptsMap[name])) {
551
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
552
+ collectionsToHandle.delete(name);
553
+ }
554
+ else {
555
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
556
+ // force a full snapshot on retry to recover from
557
+ // corrupted local state (e.g. LTHash MAC mismatch)
558
+ forceSnapshotCollections.add(name);
559
+ }
560
+ }
561
+ }
562
+ }
563
+ }, authState?.creds?.me?.id || 'resync-app-state');
564
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
565
+ for (const key in globalMutationMap) {
566
+ onMutation(globalMutationMap[key]);
567
+ }
568
+ });
569
+ /**
570
+ * fetch the profile picture of a user/group
571
+ * type = "preview" for a low res picture
572
+ * type = "image for the high res picture"
573
+ */
574
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = false) => {
575
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
576
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
577
+ // and never for own profile pic (Chat model for self has no tcToken).
578
+ // Including tctoken for own JID causes the server to never respond.
579
+ const normalizedJid = (0, index_js_5.jidNormalizedUser)(jid);
580
+ const isUserJid = (0, index_js_5.isPnUser)(normalizedJid) || (0, index_js_5.isLidUser)(normalizedJid);
581
+ const me = authState.creds.me;
582
+ const isSelf = me && (normalizedJid === (0, index_js_5.jidNormalizedUser)(me.id) || (me.lid && normalizedJid === (0, index_js_5.jidNormalizedUser)(me.lid)));
583
+ let content = baseContent;
584
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
585
+ content = await (0, tc_token_utils_js_1.buildTcTokenFromJid)({
586
+ authState,
587
+ jid: normalizedJid,
588
+ baseContent,
589
+ getLIDForPN
590
+ });
591
+ }
592
+ jid = (0, index_js_5.jidNormalizedUser)(jid);
593
+ const result = await query({
594
+ tag: 'iq',
595
+ attrs: {
596
+ target: jid,
597
+ to: index_js_5.S_WHATSAPP_NET,
598
+ type: 'get',
599
+ xmlns: 'w:profile:picture'
600
+ },
601
+ content
602
+ }, timeoutMs);
603
+ const child = (0, index_js_5.getBinaryNodeChild)(result, 'picture');
604
+ return child?.attrs?.url;
605
+ };
606
+ const createCallLink = async (type, event, timeoutMs) => {
607
+ const result = await query({
608
+ tag: 'call',
609
+ attrs: {
610
+ id: generateMessageTag(),
611
+ to: '@call'
612
+ },
613
+ content: [
614
+ {
615
+ tag: 'link_create',
616
+ attrs: { media: type },
617
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
618
+ }
619
+ ]
620
+ }, timeoutMs);
621
+ const child = (0, index_js_5.getBinaryNodeChild)(result, 'link_create');
622
+ return child?.attrs?.token;
623
+ };
624
+ const sendPresenceUpdate = async (type, toJid) => {
625
+ const me = authState.creds.me;
626
+ const isAvailableType = type === 'available';
627
+ if (isAvailableType || type === 'unavailable') {
628
+ if (!me.name) {
629
+ logger.warn('no name present, ignoring presence update request...');
630
+ return;
631
+ }
632
+ ev.emit('connection.update', { isOnline: isAvailableType });
633
+ if (isAvailableType) {
634
+ void sendUnifiedSession();
635
+ }
636
+ await sendNode({
637
+ tag: 'presence',
638
+ attrs: {
639
+ name: me.name.replace(/@/g, ''),
640
+ type
641
+ }
642
+ });
643
+ }
644
+ else {
645
+ const { server } = (0, index_js_5.jidDecode)(toJid);
646
+ const isLid = server === 'lid';
647
+ await sendNode({
648
+ tag: 'chatstate',
649
+ attrs: {
650
+ from: isLid ? me.lid : me.id,
651
+ to: toJid
652
+ },
653
+ content: [
654
+ {
655
+ tag: type === 'recording' ? 'composing' : type,
656
+ attrs: type === 'recording' ? { media: 'audio' } : {}
657
+ }
658
+ ]
659
+ });
660
+ }
661
+ };
662
+ /**
663
+ * @param toJid the jid to subscribe to
664
+ * @param tcToken token for subscription, use if present
665
+ */
666
+ const presenceSubscribe = async (toJid) => {
667
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
668
+ const normalizedToJid = (0, index_js_5.jidNormalizedUser)(toJid);
669
+ const isUserJid = (0, index_js_5.isPnUser)(normalizedToJid) || (0, index_js_5.isLidUser)(normalizedToJid);
670
+ const tcTokenContent = isUserJid
671
+ ? await (0, tc_token_utils_js_1.buildTcTokenFromJid)({ authState, jid: normalizedToJid, getLIDForPN })
672
+ : undefined;
673
+ return sendNode({
674
+ tag: 'presence',
675
+ attrs: {
676
+ to: toJid,
677
+ id: generateMessageTag(),
678
+ type: 'subscribe'
679
+ },
680
+ content: tcTokenContent
681
+ });
682
+ };
683
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
684
+ let presence;
685
+ const jid = attrs.from;
686
+ const participant = attrs.participant || attrs.from;
687
+ if (shouldIgnoreJid(jid) && jid !== index_js_5.S_WHATSAPP_NET) {
688
+ return;
689
+ }
690
+ if (tag === 'presence') {
691
+ presence = {
692
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
693
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
694
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
695
+ };
696
+ }
697
+ else if (Array.isArray(content)) {
698
+ const [firstChild] = content;
699
+ let type = firstChild.tag;
700
+ if (type === 'paused') {
701
+ type = 'available';
702
+ }
703
+ if (firstChild.attrs?.media === 'audio') {
704
+ type = 'recording';
705
+ }
706
+ presence = { lastKnownPresence: type };
707
+ }
708
+ else {
709
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
710
+ }
711
+ if (presence) {
712
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
713
+ }
714
+ };
715
+ const appPatch = async (patchCreate) => {
716
+ const name = patchCreate.type;
717
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
718
+ if (!myAppStateKeyId) {
719
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
720
+ }
721
+ let initial;
722
+ let encodeResult;
723
+ await appStatePatchMutex.mutex(async () => {
724
+ await authState.keys.transaction(async () => {
725
+ logger.debug({ patch: patchCreate }, 'applying app patch');
726
+ await resyncAppState([name], false);
727
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
728
+ initial = currentSyncVersion ? (0, index_js_4.ensureLTHashStateVersion)(currentSyncVersion) : (0, index_js_4.newLTHashState)();
729
+ encodeResult = await (0, index_js_4.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
730
+ const { patch, state } = encodeResult;
731
+ const node = {
732
+ tag: 'iq',
733
+ attrs: {
734
+ to: index_js_5.S_WHATSAPP_NET,
735
+ type: 'set',
736
+ xmlns: 'w:sync:app:state'
737
+ },
738
+ content: [
739
+ {
740
+ tag: 'sync',
741
+ attrs: {},
742
+ content: [
743
+ {
744
+ tag: 'collection',
745
+ attrs: {
746
+ name,
747
+ version: (state.version - 1).toString(),
748
+ return_snapshot: 'false'
749
+ },
750
+ content: [
751
+ {
752
+ tag: 'patch',
753
+ attrs: {},
754
+ content: index_js_1.proto.SyncdPatch.encode(patch).finish()
755
+ }
756
+ ]
757
+ }
758
+ ]
759
+ }
760
+ ]
761
+ };
762
+ await query(node);
763
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
764
+ }, authState?.creds?.me?.id || 'app-patch');
765
+ });
766
+ if (config.emitOwnEvents) {
767
+ const { onMutation } = newAppStateChunkHandler(false);
768
+ const { mutationMap } = await (0, index_js_4.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
769
+ for (const key in mutationMap) {
770
+ onMutation(mutationMap[key]);
771
+ }
772
+ }
773
+ };
774
+ /** fetch AB props */
775
+ const fetchProps = async () => {
776
+ const resultNode = await query({
777
+ tag: 'iq',
778
+ attrs: {
779
+ to: index_js_5.S_WHATSAPP_NET,
780
+ xmlns: 'abt',
781
+ type: 'get'
782
+ },
783
+ content: [
784
+ {
785
+ tag: 'props',
786
+ attrs: {
787
+ protocol: '1',
788
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
789
+ }
790
+ }
791
+ ]
792
+ });
793
+ const propsNode = (0, index_js_5.getBinaryNodeChild)(resultNode, 'props');
794
+ let props = {};
795
+ if (propsNode) {
796
+ if (propsNode.attrs?.hash) {
797
+ // on some clients, the hash is returning as undefined
798
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
799
+ ev.emit('creds.update', authState.creds);
800
+ }
801
+ props = (0, index_js_5.reduceBinaryNodeToDictionary)(propsNode, 'prop');
802
+ }
803
+ // Extract protocol-relevant AB props (only the ones we need)
804
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
805
+ if (privacyTokenProp !== undefined) {
806
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
807
+ }
808
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
809
+ if (profilePicProp !== undefined) {
810
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
811
+ }
812
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
813
+ if (lidIssueProp !== undefined) {
814
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
815
+ }
816
+ logger.debug({ serverProps }, 'fetched props');
817
+ return props;
818
+ };
819
+ /**
820
+ * modify a chat -- mark unread, read etc.
821
+ * lastMessages must be sorted in reverse chronologically
822
+ * requires the last messages till the last message received; required for archive & unread
823
+ */
824
+ const chatModify = (mod, jid) => {
825
+ const patch = (0, index_js_4.chatModificationToAppPatch)(mod, jid);
826
+ return appPatch(patch);
827
+ };
828
+ /**
829
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
830
+ */
831
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
832
+ return chatModify({
833
+ disableLinkPreviews: { isPreviewsDisabled }
834
+ }, '');
835
+ };
836
+ /**
837
+ * Star or Unstar a message
838
+ */
839
+ const star = (jid, messages, star) => {
840
+ return chatModify({
841
+ star: {
842
+ messages,
843
+ star
844
+ }
845
+ }, jid);
846
+ };
847
+ /**
848
+ * Add or Edit Contact
849
+ */
850
+ const addOrEditContact = (jid, contact) => {
851
+ return chatModify({
852
+ contact
853
+ }, jid);
854
+ };
855
+ /**
856
+ * Remove Contact
857
+ */
858
+ const removeContact = (jid) => {
859
+ return chatModify({
860
+ contact: null
861
+ }, jid);
862
+ };
863
+ /**
864
+ * Adds label
865
+ */
866
+ const addLabel = (jid, labels) => {
867
+ return chatModify({
868
+ addLabel: {
869
+ ...labels
870
+ }
871
+ }, jid);
872
+ };
873
+ /**
874
+ * Adds label for the chats
875
+ */
876
+ const addChatLabel = (jid, labelId) => {
877
+ return chatModify({
878
+ addChatLabel: {
879
+ labelId
880
+ }
881
+ }, jid);
882
+ };
883
+ /**
884
+ * Removes label for the chat
885
+ */
886
+ const removeChatLabel = (jid, labelId) => {
887
+ return chatModify({
888
+ removeChatLabel: {
889
+ labelId
890
+ }
891
+ }, jid);
892
+ };
893
+ /**
894
+ * Adds label for the message
895
+ */
896
+ const addMessageLabel = (jid, messageId, labelId) => {
897
+ return chatModify({
898
+ addMessageLabel: {
899
+ messageId,
900
+ labelId
901
+ }
902
+ }, jid);
903
+ };
904
+ /**
905
+ * Removes label for the message
906
+ */
907
+ const removeMessageLabel = (jid, messageId, labelId) => {
908
+ return chatModify({
909
+ removeMessageLabel: {
910
+ messageId,
911
+ labelId
912
+ }
913
+ }, jid);
914
+ };
915
+ /**
916
+ * Add or Edit Quick Reply
917
+ */
918
+ const addOrEditQuickReply = (quickReply) => {
919
+ return chatModify({
920
+ quickReply
921
+ }, '');
922
+ };
923
+ /**
924
+ * Remove Quick Reply
925
+ */
926
+ const removeQuickReply = (timestamp) => {
927
+ return chatModify({
928
+ quickReply: { timestamp, deleted: true }
929
+ }, '');
930
+ };
931
+ /**
932
+ * queries need to be fired on connection open
933
+ * help ensure parity with WA Web
934
+ * */
935
+ const executeInitQueries = async () => {
936
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
937
+ };
938
+ // Vanzxy@Changes --- Detect WhatsApp system/security notification messages
939
+ // (e.g. "Messages are end-to-end encrypted", "This business now uses a secure
940
+ // service from Meta") so consumers can filter them out without affecting any
941
+ // existing message types or behavior. This ONLY adds a flag, nothing is dropped.
942
+ const isWASystemNotification = (msg) => {
943
+ const content = msg?.message;
944
+ if (!content)
945
+ return false;
946
+ // E2E / business-encryption notices arrive as protocolMessage with these types
947
+ const protoType = content.protocolMessage?.type;
948
+ if (protoType === index_js_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION ||
949
+ protoType === index_js_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE ||
950
+ protoType === index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE ||
951
+ protoType === index_js_1.proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC) {
952
+ return true;
953
+ }
954
+ // Generic stub-type system notices (no real content, just a stub event)
955
+ if (msg.messageStubType && !content.conversation && !content.extendedTextMessage) {
956
+ const stub = msg.messageStubType;
957
+ const SYSTEM_STUB_TYPES = new Set([
958
+ index_js_3.WAMessageStubType.E2E_DEVICE_CHANGED,
959
+ index_js_3.WAMessageStubType.E2E_ENCRYPTED,
960
+ index_js_3.WAMessageStubType.E2E_IDENTITY_CHANGED,
961
+ index_js_3.WAMessageStubType.CIPHERTEXT,
962
+ index_js_3.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP,
963
+ index_js_3.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
964
+ ]);
965
+ if (SYSTEM_STUB_TYPES.has(stub))
966
+ return true;
967
+ }
968
+ return false;
969
+ };
970
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
971
+ // Vanzxy@Changes --- Annotate msg with isSystemNotification flag (additive only)
972
+ if (isWASystemNotification(msg)) {
973
+ msg.isSystemNotification = true;
974
+ }
975
+ ev.emit('messages.upsert', { messages: [msg], type });
976
+ if (!!msg.pushName) {
977
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
978
+ jid = (0, index_js_5.jidNormalizedUser)(jid);
979
+ if (!msg.key.fromMe) {
980
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
981
+ }
982
+ // update our pushname too
983
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
984
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
985
+ }
986
+ }
987
+ const historyMsg = (0, index_js_4.getHistoryMsg)(msg.message);
988
+ const shouldProcessHistoryMsg = historyMsg
989
+ ? shouldSyncHistoryMessage(historyMsg) &&
990
+ index_js_2.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
991
+ : false;
992
+ if (historyMsg && shouldProcessHistoryMsg) {
993
+ const syncType = historyMsg.syncType;
994
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
995
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
996
+ !historySyncStatus.initialBootstrapComplete) {
997
+ historySyncStatus.initialBootstrapComplete = true;
998
+ ev.emit('messaging-history.status', {
999
+ syncType,
1000
+ status: 'complete',
1001
+ explicit: true
1002
+ });
1003
+ }
1004
+ // RECENT with progress === 100 — explicit completion
1005
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT &&
1006
+ historyMsg.progress === 100 &&
1007
+ !historySyncStatus.recentSyncComplete) {
1008
+ historySyncStatus.recentSyncComplete = true;
1009
+ clearTimeout(historySyncPausedTimeout);
1010
+ historySyncPausedTimeout = undefined;
1011
+ ev.emit('messaging-history.status', {
1012
+ syncType,
1013
+ status: 'complete',
1014
+ explicit: true
1015
+ });
1016
+ }
1017
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
1018
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
1019
+ clearTimeout(historySyncPausedTimeout);
1020
+ historySyncPausedTimeout = setTimeout(() => {
1021
+ if (!historySyncStatus.recentSyncComplete) {
1022
+ historySyncStatus.recentSyncComplete = true;
1023
+ ev.emit('messaging-history.status', {
1024
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT,
1025
+ status: 'paused',
1026
+ explicit: false
1027
+ });
1028
+ }
1029
+ historySyncPausedTimeout = undefined;
1030
+ }, index_js_2.HISTORY_SYNC_PAUSED_TIMEOUT_MS);
1031
+ }
1032
+ }
1033
+ // State machine: decide on sync and flush
1034
+ if (historyMsg && syncState === State_js_1.SyncState.AwaitingInitialSync) {
1035
+ if (awaitingSyncTimeout) {
1036
+ clearTimeout(awaitingSyncTimeout);
1037
+ awaitingSyncTimeout = undefined;
1038
+ }
1039
+ if (shouldProcessHistoryMsg) {
1040
+ syncState = State_js_1.SyncState.Syncing;
1041
+ logger.info('Transitioned to Syncing state');
1042
+ // Let doAppStateSync handle the final flush after it's done
1043
+ }
1044
+ else {
1045
+ syncState = State_js_1.SyncState.Online;
1046
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
1047
+ ev.flush();
1048
+ }
1049
+ }
1050
+ const doAppStateSync = async () => {
1051
+ if (syncState === State_js_1.SyncState.Syncing) {
1052
+ // All collections will be synced, so clear any blocked ones
1053
+ blockedCollections.clear();
1054
+ logger.info('Doing app state sync');
1055
+ await resyncAppState(index_js_3.ALL_WA_PATCH_NAMES, true);
1056
+ // Sync is complete, go online and flush everything
1057
+ syncState = State_js_1.SyncState.Online;
1058
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
1059
+ ev.flush();
1060
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1061
+ ev.emit('creds.update', { accountSyncCounter });
1062
+ }
1063
+ };
1064
+ await Promise.all([
1065
+ (async () => {
1066
+ if (shouldProcessHistoryMsg) {
1067
+ await doAppStateSync();
1068
+ }
1069
+ })(),
1070
+ (0, process_message_js_1.default)(msg, {
1071
+ signalRepository,
1072
+ shouldProcessHistoryMsg,
1073
+ placeholderResendCache,
1074
+ ev,
1075
+ creds: authState.creds,
1076
+ keyStore: authState.keys,
1077
+ logger,
1078
+ options: config.options,
1079
+ getMessage
1080
+ })
1081
+ ]);
1082
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
1083
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === State_js_1.SyncState.Syncing) {
1084
+ logger.info('App state sync key arrived, triggering app state sync');
1085
+ await doAppStateSync();
1086
+ }
1087
+ });
1088
+ ws.on('CB:presence', handlePresenceUpdate);
1089
+ ws.on('CB:chatstate', handlePresenceUpdate);
1090
+ ws.on('CB:ib,,dirty', async (node) => {
1091
+ const { attrs } = (0, index_js_5.getBinaryNodeChild)(node, 'dirty');
1092
+ const type = attrs.type;
1093
+ switch (type) {
1094
+ case 'account_sync':
1095
+ if (attrs.timestamp) {
1096
+ let { lastAccountSyncTimestamp } = authState.creds;
1097
+ if (lastAccountSyncTimestamp) {
1098
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
1099
+ }
1100
+ lastAccountSyncTimestamp = +attrs.timestamp;
1101
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
1102
+ }
1103
+ break;
1104
+ case 'groups':
1105
+ // handled in groups.ts
1106
+ break;
1107
+ default:
1108
+ logger.info({ node }, 'received unknown sync');
1109
+ break;
1110
+ }
1111
+ });
1112
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1113
+ if (connection === 'close') {
1114
+ blockedCollections.clear();
1115
+ clearTimeout(historySyncPausedTimeout);
1116
+ historySyncPausedTimeout = undefined;
1117
+ }
1118
+ if (connection === 'open') {
1119
+ if (fireInitQueries) {
1120
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
1121
+ }
1122
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1123
+ }
1124
+ if (!receivedPendingNotifications || syncState !== State_js_1.SyncState.Connecting) {
1125
+ return;
1126
+ }
1127
+ historySyncStatus.initialBootstrapComplete = false;
1128
+ historySyncStatus.recentSyncComplete = false;
1129
+ clearTimeout(historySyncPausedTimeout);
1130
+ historySyncPausedTimeout = undefined;
1131
+ syncState = State_js_1.SyncState.AwaitingInitialSync;
1132
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1133
+ ev.buffer();
1134
+ const willSyncHistory = shouldSyncHistoryMessage(index_js_1.proto.Message.HistorySyncNotification.create({
1135
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT
1136
+ }));
1137
+ if (!willSyncHistory) {
1138
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1139
+ syncState = State_js_1.SyncState.Online;
1140
+ setTimeout(() => ev.flush(), 0);
1141
+ return;
1142
+ }
1143
+ // On reconnection (accountSyncCounter > 0), the server does not push
1144
+ // history sync notifications — the device already has its data.
1145
+ // Skip the 20s wait and go online immediately.
1146
+ if (authState.creds.accountSyncCounter > 0) {
1147
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1148
+ syncState = State_js_1.SyncState.Online;
1149
+ setTimeout(() => ev.flush(), 0);
1150
+ return;
1151
+ }
1152
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1153
+ if (awaitingSyncTimeout) {
1154
+ clearTimeout(awaitingSyncTimeout);
1155
+ }
1156
+ awaitingSyncTimeout = setTimeout(() => {
1157
+ if (syncState === State_js_1.SyncState.AwaitingInitialSync) {
1158
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1159
+ syncState = State_js_1.SyncState.Online;
1160
+ ev.flush();
1161
+ // Increment so subsequent reconnections skip the 20s wait.
1162
+ // Late-arriving history is still processed via processMessage
1163
+ // regardless of the state machine phase.
1164
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1165
+ ev.emit('creds.update', { accountSyncCounter });
1166
+ }
1167
+ }, 20000);
1168
+ });
1169
+ // When an app state sync key arrives (myAppStateKeyId is set) and there are
1170
+ // collections blocked on a missing key, trigger a re-sync for just those collections.
1171
+ // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1172
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
1173
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
1174
+ return;
1175
+ }
1176
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
1177
+ if (syncState === State_js_1.SyncState.Syncing) {
1178
+ blockedCollections.clear();
1179
+ return;
1180
+ }
1181
+ const collections = [...blockedCollections];
1182
+ blockedCollections.clear();
1183
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1184
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1185
+ });
1186
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1187
+ try {
1188
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1189
+ }
1190
+ catch (error) {
1191
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1192
+ }
1193
+ });
1194
+ registerSocketEndHandler(() => {
1195
+ if (awaitingSyncTimeout) {
1196
+ clearTimeout(awaitingSyncTimeout);
1197
+ awaitingSyncTimeout = undefined;
1198
+ }
1199
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1200
+ placeholderResendCache.close();
1201
+ }
1202
+ syncState = State_js_1.SyncState.Connecting;
1203
+ privacySettings = undefined;
1204
+ });
1205
+ return {
1206
+ ...sock,
1207
+ findUserId,
1208
+ serverProps,
1209
+ createCallLink,
1210
+ getBotListV2,
1211
+ messageMutex,
1212
+ receiptMutex,
1213
+ appStatePatchMutex,
1214
+ notificationMutex,
1215
+ fetchPrivacySettings,
1216
+ upsertMessage,
1217
+ appPatch,
1218
+ sendPresenceUpdate,
1219
+ presenceSubscribe,
1220
+ profilePictureUrl,
1221
+ fetchBlocklist,
1222
+ fetchStatus,
1223
+ fetchDisappearingDuration,
1224
+ updateProfilePicture,
1225
+ removeProfilePicture,
1226
+ updateProfileStatus,
1227
+ updateProfileName,
1228
+ updateBlockStatus,
1229
+ updateDisableLinkPreviewsPrivacy,
1230
+ updateCallPrivacy,
1231
+ updateMessagesPrivacy,
1232
+ updateLastSeenPrivacy,
1233
+ updateOnlinePrivacy,
1234
+ updateProfilePicturePrivacy,
1235
+ updateStatusPrivacy,
1236
+ updateReadReceiptsPrivacy,
1237
+ updateGroupsAddPrivacy,
1238
+ updateDefaultDisappearingMode,
1239
+ getBusinessProfile,
1240
+ resyncAppState,
1241
+ chatModify,
1242
+ cleanDirtyBits,
1243
+ addOrEditContact,
1244
+ removeContact,
1245
+ placeholderResendCache,
1246
+ addLabel,
1247
+ addChatLabel,
1248
+ removeChatLabel,
1249
+ addMessageLabel,
1250
+ removeMessageLabel,
1251
+ star,
1252
+ addOrEditQuickReply,
1253
+ removeQuickReply
1254
+ };
1255
+ };
1256
+ exports.makeChatsSocket = makeChatsSocket;
1257
+ //# sourceMappingURL=chats.js.map