@dappaoffc/baileys-mod 4.0.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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/WAProto.proto +5311 -0
  3. package/WAProto/index.js +94091 -0
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/KeyDB/BinarySearch.js +20 -0
  6. package/lib/KeyDB/KeyedDB.js +167 -0
  7. package/lib/KeyDB/index.js +4 -0
  8. package/lib/Signal/Group/ciphertext-message.js +13 -0
  9. package/lib/Signal/Group/group-session-builder.js +32 -0
  10. package/lib/Signal/Group/group_cipher.js +84 -0
  11. package/lib/Signal/Group/index.js +13 -0
  12. package/lib/Signal/Group/keyhelper.js +20 -0
  13. package/lib/Signal/Group/sender-chain-key.js +28 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  15. package/lib/Signal/Group/sender-key-message.js +68 -0
  16. package/lib/Signal/Group/sender-key-name.js +52 -0
  17. package/lib/Signal/Group/sender-key-record.js +43 -0
  18. package/lib/Signal/Group/sender-key-state.js +86 -0
  19. package/lib/Signal/Group/sender-message-key.js +28 -0
  20. package/lib/Signal/libsignal.js +324 -0
  21. package/lib/Signal/lid-mapping.js +155 -0
  22. package/lib/Socket/Client/index.js +4 -0
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +52 -0
  25. package/lib/Socket/business.js +377 -0
  26. package/lib/Socket/chats.js +881 -0
  27. package/lib/Socket/communities.js +413 -0
  28. package/lib/Socket/groups.js +312 -0
  29. package/lib/Socket/index.js +16 -0
  30. package/lib/Socket/messages-recv.js +1163 -0
  31. package/lib/Socket/messages-send.js +1061 -0
  32. package/lib/Socket/mex.js +45 -0
  33. package/lib/Socket/newsletter.js +244 -0
  34. package/lib/Socket/socket.js +781 -0
  35. package/lib/Store/index.js +6 -0
  36. package/lib/Store/make-cache-manager-store.js +75 -0
  37. package/lib/Store/make-in-memory-store.js +290 -0
  38. package/lib/Store/make-ordered-dictionary.js +79 -0
  39. package/lib/Store/object-repository.js +25 -0
  40. package/lib/Types/Auth.js +3 -0
  41. package/lib/Types/Bussines.js +3 -0
  42. package/lib/Types/Call.js +3 -0
  43. package/lib/Types/Chat.js +9 -0
  44. package/lib/Types/Contact.js +3 -0
  45. package/lib/Types/Events.js +3 -0
  46. package/lib/Types/GroupMetadata.js +3 -0
  47. package/lib/Types/Label.js +25 -0
  48. package/lib/Types/LabelAssociation.js +7 -0
  49. package/lib/Types/Message.js +12 -0
  50. package/lib/Types/Newsletter.js +33 -0
  51. package/lib/Types/Newsletter.js.bak +33 -0
  52. package/lib/Types/Product.js +3 -0
  53. package/lib/Types/Signal.js +3 -0
  54. package/lib/Types/Socket.js +4 -0
  55. package/lib/Types/State.js +11 -0
  56. package/lib/Types/USync.js +3 -0
  57. package/lib/Types/index.js +28 -0
  58. package/lib/Utils/auth-utils.js +219 -0
  59. package/lib/Utils/baileys-event-stream.js +44 -0
  60. package/lib/Utils/browser-utils.js +25 -0
  61. package/lib/Utils/business.js +233 -0
  62. package/lib/Utils/chat-utils.js +752 -0
  63. package/lib/Utils/crypto.js +130 -0
  64. package/lib/Utils/decode-wa-message.js +267 -0
  65. package/lib/Utils/event-buffer.js +528 -0
  66. package/lib/Utils/generics.js +355 -0
  67. package/lib/Utils/history.js +87 -0
  68. package/lib/Utils/index.js +21 -0
  69. package/lib/Utils/link-preview.js +81 -0
  70. package/lib/Utils/logger.js +5 -0
  71. package/lib/Utils/lt-hash.js +45 -0
  72. package/lib/Utils/make-mutex.js +36 -0
  73. package/lib/Utils/message-retry-manager.js +113 -0
  74. package/lib/Utils/messages-media.js +601 -0
  75. package/lib/Utils/messages.js +907 -0
  76. package/lib/Utils/noise-handler.js +144 -0
  77. package/lib/Utils/pre-key-manager.js +85 -0
  78. package/lib/Utils/process-message.js +341 -0
  79. package/lib/Utils/signal.js +161 -0
  80. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  81. package/lib/Utils/validate-connection.js +200 -0
  82. package/lib/WABinary/constants.js +1303 -0
  83. package/lib/WABinary/decode.js +240 -0
  84. package/lib/WABinary/encode.js +218 -0
  85. package/lib/WABinary/generic-utils.js +189 -0
  86. package/lib/WABinary/index.js +7 -0
  87. package/lib/WABinary/jid-utils.js +93 -0
  88. package/lib/WABinary/types.js +3 -0
  89. package/lib/WAM/BinaryInfo.js +11 -0
  90. package/lib/WAM/constants.js +22853 -0
  91. package/lib/WAM/encode.js +154 -0
  92. package/lib/WAM/index.js +5 -0
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  99. package/lib/WAUSync/Protocols/index.js +6 -0
  100. package/lib/WAUSync/USyncQuery.js +90 -0
  101. package/lib/WAUSync/USyncUser.js +24 -0
  102. package/lib/WAUSync/index.js +5 -0
  103. package/lib/index.js +23 -0
  104. package/package.json +103 -0
@@ -0,0 +1,1061 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import {
5
+ DEFAULT_CACHE_TTLS,
6
+ WA_DEFAULT_EPHEMERAL
7
+ } from '../Defaults/index.js';
8
+ import {
9
+ aggregateMessageKeysNotFromMe,
10
+ assertMediaContent,
11
+ bindWaitForEvent,
12
+ decryptMediaRetryData,
13
+ encodeNewsletterMessage,
14
+ encodeSignedDeviceIdentity,
15
+ encodeWAMessage,
16
+ encryptMediaRetryRequest,
17
+ extractDeviceJids,
18
+ generateMessageIDV2,
19
+ generateParticipantHashV2,
20
+ generateWAMessage,
21
+ getStatusCodeForMediaRetry,
22
+ getUrlFromDirectPath,
23
+ getWAUploadToServer,
24
+ MessageRetryManager,
25
+ normalizeMessageContent,
26
+ parseAndInjectE2ESessions,
27
+ unixTimestampSeconds
28
+ } from '../Utils/index.js';
29
+ import {
30
+ areJidsSameUser,
31
+ getBinaryNodeChild,
32
+ getBinaryNodeChildren,
33
+ getAdditionalNode,
34
+ getBinaryNodeFilter,
35
+ isHostedLidUser,
36
+ isHostedPnUser,
37
+ isJidGroup,
38
+ isLidUser,
39
+ isPnUser,
40
+ jidDecode,
41
+ jidEncode,
42
+ isJidNewsletter,
43
+ jidNormalizedUser,
44
+ S_WHATSAPP_NET
45
+ } from '../WABinary/index.js';
46
+ import { getUrlInfo } from '../Utils/link-preview.js';
47
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
48
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
49
+ import { makeNewsletterSocket } from './newsletter.js';
50
+ export const makeMessagesSocket = (config) => {
51
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
52
+ const sock = makeNewsletterSocket(config);
53
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
54
+ const userDevicesCache = config.userDevicesCache ||
55
+ new NodeCache({
56
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
57
+ useClones: false
58
+ });
59
+ const peerSessionsCache = new NodeCache({
60
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
61
+ useClones: false
62
+ });
63
+ // Initialize message retry manager if enabled
64
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
65
+ // Prevent race conditions in Signal session encryption by user
66
+ const encryptionMutex = makeKeyedMutex();
67
+ let mediaConn;
68
+ const refreshMediaConn = async (forceGet = false) => {
69
+ const media = await mediaConn;
70
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
71
+ mediaConn = (async () => {
72
+ const result = await query({
73
+ tag: 'iq',
74
+ attrs: {
75
+ type: 'set',
76
+ xmlns: 'w:m',
77
+ to: S_WHATSAPP_NET
78
+ },
79
+ content: [{ tag: 'media_conn', attrs: {} }]
80
+ });
81
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
82
+ // TODO: explore full length of data that whatsapp provides
83
+ const node = {
84
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
85
+ hostname: attrs.hostname,
86
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
87
+ })),
88
+ auth: mediaConnNode.attrs.auth,
89
+ ttl: +mediaConnNode.attrs.ttl,
90
+ fetchDate: new Date()
91
+ };
92
+ logger.debug('fetched media conn');
93
+ return node;
94
+ })();
95
+ }
96
+ return mediaConn;
97
+ };
98
+ /**
99
+ * generic send receipt function
100
+ * used for receipts of phone call, read, delivery etc.
101
+ * */
102
+ const sendReceipt = async (jid, participant, messageIds, type) => {
103
+ if (!messageIds || messageIds.length === 0) {
104
+ throw new Boom('missing ids in receipt');
105
+ }
106
+ const node = {
107
+ tag: 'receipt',
108
+ attrs: {
109
+ id: messageIds[0]
110
+ }
111
+ };
112
+ const isReadReceipt = type === 'read' || type === 'read-self';
113
+ if (isReadReceipt) {
114
+ node.attrs.t = unixTimestampSeconds().toString();
115
+ }
116
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
117
+ node.attrs.recipient = jid;
118
+ node.attrs.to = participant;
119
+ }
120
+ else {
121
+ node.attrs.to = jid;
122
+ if (participant) {
123
+ node.attrs.participant = participant;
124
+ }
125
+ }
126
+ if (type) {
127
+ node.attrs.type = type;
128
+ }
129
+ const remainingMessageIds = messageIds.slice(1);
130
+ if (remainingMessageIds.length) {
131
+ node.content = [
132
+ {
133
+ tag: 'list',
134
+ attrs: {},
135
+ content: remainingMessageIds.map(id => ({
136
+ tag: 'item',
137
+ attrs: { id }
138
+ }))
139
+ }
140
+ ];
141
+ }
142
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
143
+ await sendNode(node);
144
+ };
145
+ /** Correctly bulk send receipts to multiple chats, participants */
146
+ const sendReceipts = async (keys, type) => {
147
+ const recps = aggregateMessageKeysNotFromMe(keys);
148
+ for (const { jid, participant, messageIds } of recps) {
149
+ await sendReceipt(jid, participant, messageIds, type);
150
+ }
151
+ };
152
+ /** Bulk read messages. Keys can be from different chats & participants */
153
+ const readMessages = async (keys) => {
154
+ const privacySettings = await fetchPrivacySettings();
155
+ // based on privacy settings, we have to change the read type
156
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
157
+ await sendReceipts(keys, readType);
158
+ };
159
+ /** Fetch all the devices we've to send a message to */
160
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
161
+ const deviceResults = [];
162
+ if (!useCache) {
163
+ logger.debug('not using cache for devices');
164
+ }
165
+ const toFetch = [];
166
+ const jidsWithUser = jids
167
+ .map(jid => {
168
+ const decoded = jidDecode(jid);
169
+ const user = decoded?.user;
170
+ const device = decoded?.device;
171
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
172
+ if (isExplicitDevice && user) {
173
+ deviceResults.push({
174
+ user,
175
+ device,
176
+ jid
177
+ });
178
+ return null;
179
+ }
180
+ jid = jidNormalizedUser(jid);
181
+ return { jid, user };
182
+ })
183
+ .filter(jid => jid !== null);
184
+ let mgetDevices;
185
+ if (useCache && userDevicesCache.mget) {
186
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
187
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
188
+ }
189
+ for (const { jid, user } of jidsWithUser) {
190
+ if (useCache) {
191
+ const devices = mgetDevices?.[user] ||
192
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
193
+ if (devices) {
194
+ const devicesWithJid = devices.map(d => ({
195
+ ...d,
196
+ jid: jidEncode(d.user, d.server, d.device)
197
+ }));
198
+ deviceResults.push(...devicesWithJid);
199
+ logger.trace({ user }, 'using cache for devices');
200
+ }
201
+ else {
202
+ toFetch.push(jid);
203
+ }
204
+ }
205
+ else {
206
+ toFetch.push(jid);
207
+ }
208
+ }
209
+ if (!toFetch.length) {
210
+ return deviceResults;
211
+ }
212
+ const requestedLidUsers = new Set();
213
+ for (const jid of toFetch) {
214
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
215
+ const user = jidDecode(jid)?.user;
216
+ if (user)
217
+ requestedLidUsers.add(user);
218
+ }
219
+ }
220
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
221
+ for (const jid of toFetch) {
222
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
223
+ }
224
+ const result = await sock.executeUSyncQuery(query);
225
+ if (result) {
226
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
227
+ const lidResults = result.list.filter(a => !!a.lid);
228
+ if (lidResults.length > 0) {
229
+ logger.trace('Storing LID maps from device call');
230
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
231
+ }
232
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
233
+ const deviceMap = {};
234
+ for (const item of extracted) {
235
+ deviceMap[item.user] = deviceMap[item.user] || [];
236
+ deviceMap[item.user]?.push(item);
237
+ }
238
+ // Process each user's devices as a group for bulk LID migration
239
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
240
+ const isLidUser = requestedLidUsers.has(user);
241
+ // Process all devices for this user
242
+ for (const item of userDevices) {
243
+ const finalJid = isLidUser
244
+ ? jidEncode(user, item.server, item.device)
245
+ : jidEncode(item.user, item.server, item.device);
246
+ deviceResults.push({
247
+ ...item,
248
+ jid: finalJid
249
+ });
250
+ logger.debug({
251
+ user: item.user,
252
+ device: item.device,
253
+ finalJid,
254
+ usedLid: isLidUser
255
+ }, 'Processed device with LID priority');
256
+ }
257
+ }
258
+ if (userDevicesCache.mset) {
259
+ // if the cache supports mset, we can set all devices in one go
260
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
261
+ }
262
+ else {
263
+ for (const key in deviceMap) {
264
+ if (deviceMap[key])
265
+ await userDevicesCache.set(key, deviceMap[key]);
266
+ }
267
+ }
268
+ const userDeviceUpdates = {};
269
+ for (const [userId, devices] of Object.entries(deviceMap)) {
270
+ if (devices && devices.length > 0) {
271
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
272
+ }
273
+ }
274
+ if (Object.keys(userDeviceUpdates).length > 0) {
275
+ try {
276
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
277
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
278
+ }
279
+ catch (error) {
280
+ logger.warn({ error }, 'failed to store user device lists');
281
+ }
282
+ }
283
+ }
284
+ return deviceResults;
285
+ };
286
+ const assertSessions = async (jids) => {
287
+ let didFetchNewSession = false;
288
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
289
+ const jidsRequiringFetch = [];
290
+ logger.debug({ jids }, 'assertSessions call with jids');
291
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
292
+ for (const jid of uniqueJids) {
293
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
294
+ const cachedSession = peerSessionsCache.get(signalId);
295
+ if (cachedSession !== undefined) {
296
+ if (cachedSession) {
297
+ continue; // Session exists in cache
298
+ }
299
+ }
300
+ else {
301
+ const sessionValidation = await signalRepository.validateSession(jid);
302
+ const hasSession = sessionValidation.exists;
303
+ peerSessionsCache.set(signalId, hasSession);
304
+ if (hasSession) {
305
+ continue;
306
+ }
307
+ }
308
+ jidsRequiringFetch.push(jid);
309
+ }
310
+ if (jidsRequiringFetch.length) {
311
+ // LID if mapped, otherwise original
312
+ const wireJids = [
313
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
314
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
315
+ ];
316
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
317
+ const result = await query({
318
+ tag: 'iq',
319
+ attrs: {
320
+ xmlns: 'encrypt',
321
+ type: 'get',
322
+ to: S_WHATSAPP_NET
323
+ },
324
+ content: [
325
+ {
326
+ tag: 'key',
327
+ attrs: {},
328
+ content: wireJids.map(jid => ({
329
+ tag: 'user',
330
+ attrs: { jid }
331
+ }))
332
+ }
333
+ ]
334
+ });
335
+ await parseAndInjectE2ESessions(result, signalRepository);
336
+ didFetchNewSession = true;
337
+ // Cache fetched sessions using wire JIDs
338
+ for (const wireJid of wireJids) {
339
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
340
+ peerSessionsCache.set(signalId, true);
341
+ }
342
+ }
343
+ return didFetchNewSession;
344
+ };
345
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
346
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
347
+ if (!authState.creds.me?.id) {
348
+ throw new Boom('Not authenticated');
349
+ }
350
+ const protocolMessage = {
351
+ protocolMessage: {
352
+ peerDataOperationRequestMessage: pdoMessage,
353
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
354
+ }
355
+ };
356
+ const meJid = jidNormalizedUser(authState.creds.me.id);
357
+ const msgId = await relayMessage(meJid, protocolMessage, {
358
+ additionalAttributes: {
359
+ category: 'peer',
360
+ push_priority: 'high_force'
361
+ },
362
+ additionalNodes: [
363
+ {
364
+ tag: 'meta',
365
+ attrs: { appdata: 'default' }
366
+ }
367
+ ]
368
+ });
369
+ return msgId;
370
+ };
371
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
372
+ if (!recipientJids.length) {
373
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
374
+ }
375
+ const patched = await patchMessageBeforeSending(message, recipientJids);
376
+ const patchedMessages = Array.isArray(patched)
377
+ ? patched
378
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
379
+ let shouldIncludeDeviceIdentity = false;
380
+ const meId = authState.creds.me.id;
381
+ const meLid = authState.creds.me?.lid;
382
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
383
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
384
+ if (!jid)
385
+ return null;
386
+ let msgToEncrypt = patchedMessage;
387
+ if (dsmMessage) {
388
+ const { user: targetUser } = jidDecode(jid);
389
+ const { user: ownPnUser } = jidDecode(meId);
390
+ const ownLidUser = meLidUser;
391
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
392
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
393
+ if (isOwnUser && !isExactSenderDevice) {
394
+ msgToEncrypt = dsmMessage;
395
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
396
+ }
397
+ }
398
+ const bytes = encodeWAMessage(msgToEncrypt);
399
+ const mutexKey = jid;
400
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
401
+ const { type, ciphertext } = await signalRepository.encryptMessage({
402
+ jid,
403
+ data: bytes
404
+ });
405
+ if (type === 'pkmsg') {
406
+ shouldIncludeDeviceIdentity = true;
407
+ }
408
+ return {
409
+ tag: 'to',
410
+ attrs: { jid },
411
+ content: [
412
+ {
413
+ tag: 'enc',
414
+ attrs: {
415
+ v: '2',
416
+ type,
417
+ ...(extraAttrs || {})
418
+ },
419
+ content: ciphertext
420
+ }
421
+ ]
422
+ };
423
+ });
424
+ return node;
425
+ });
426
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
427
+ return { nodes, shouldIncludeDeviceIdentity };
428
+ };
429
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
430
+ // let shouldIncludeDeviceIdentity = false;
431
+ let didPushAdditional = false
432
+ const meId = authState.creds.me.id;
433
+ const meLid = authState.creds.me?.lid;
434
+ const isRetryResend = Boolean(participant?.jid);
435
+ let shouldIncludeDeviceIdentity = isRetryResend;
436
+ const statusJid = 'status@broadcast';
437
+ const { user, server } = jidDecode(jid);
438
+ const isGroup = server === 'g.us';
439
+ const isStatus = jid === statusJid;
440
+ const isLid = server === 'lid';
441
+ const isNewsletter = server === 'newsletter';
442
+ const isPrivate = server === 's.whatsapp.net'
443
+ const finalJid = jid;
444
+ msgId = msgId || generateMessageIDV2(meId);
445
+ useUserDevicesCache = useUserDevicesCache !== false;
446
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
447
+ const participants = [];
448
+ const destinationJid = !isStatus ? finalJid : statusJid;
449
+ const binaryNodeContent = [];
450
+ const devices = [];
451
+ const meMsg = {
452
+ deviceSentMessage: {
453
+ destinationJid,
454
+ message
455
+ },
456
+ messageContextInfo: message.messageContextInfo
457
+ };
458
+ const extraAttrs = {};
459
+ const messages = normalizeMessageContent(message)
460
+ const buttonType = getButtonType(messages);
461
+ if (participant) {
462
+ if (!isGroup && !isStatus) {
463
+ additionalAttributes = {
464
+ ...additionalAttributes,
465
+ device_fanout: 'false'
466
+ };
467
+ }
468
+ const { user, device } = jidDecode(participant.jid);
469
+ devices.push({
470
+ user,
471
+ device,
472
+ jid: participant.jid
473
+ });
474
+ }
475
+ await authState.keys.transaction(async () => {
476
+ const mediaType = getMediaType(message);
477
+ if (mediaType) {
478
+ extraAttrs['mediatype'] = mediaType;
479
+ }
480
+
481
+ if (messages.pinInChatMessage || messages.keepInChatMessage || message.reactionMessage || message.protocolMessage?.editedMessage) {
482
+ extraAttrs['decrypt-fail'] = 'hide'
483
+ }
484
+
485
+ if (messages.interactiveResponseMessage?.nativeFlowResponseMessage) {
486
+ extraAttrs['native_flow_name'] = messages.interactiveResponseMessage?.nativeFlowResponseMessage.name
487
+ }
488
+
489
+ if (isGroup || isStatus) {
490
+ const [groupData, senderKeyMap] = await Promise.all([
491
+ (async () => {
492
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
493
+ if (groupData && Array.isArray(groupData?.participants)) {
494
+ logger.trace({
495
+ jid,
496
+ participants: groupData.participants.length
497
+ }, 'using cached group metadata');
498
+ }
499
+ else if (!isStatus) {
500
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
501
+ }
502
+ return groupData;
503
+ })(),
504
+ (async () => {
505
+ if (!participant && !isStatus) {
506
+ // what if sender memory is less accurate than the cached metadata
507
+ // on participant change in group, we should do sender memory manipulation
508
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
509
+ return result[jid] || {};
510
+ }
511
+ return {};
512
+ })()
513
+ ]);
514
+ if (!participant) {
515
+ const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
516
+ if (isStatus && statusJidList) {
517
+ participantsList.push(...statusJidList);
518
+ }
519
+ // if (!isStatus) {
520
+ // additionalAttributes = {
521
+ // ...additionalAttributes,
522
+ // addressing_mode: groupData?.addressingMode || 'pn'
523
+ // };
524
+ // }
525
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
526
+ devices.push(...additionalDevices);
527
+ }
528
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
529
+ additionalAttributes = {
530
+ ...additionalAttributes,
531
+ expiration: groupData.ephemeralDuration.toString()
532
+ };
533
+ }
534
+ const patched = await patchMessageBeforeSending(message);
535
+ if (Array.isArray(patched)) {
536
+ throw new Boom('Per-jid patching is not supported in groups');
537
+ }
538
+ const bytes = encodeWAMessage(patched);
539
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
540
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
541
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
542
+ group: destinationJid,
543
+ data: bytes,
544
+ meId: groupSenderIdentity
545
+ });
546
+ const senderKeyRecipients = [];
547
+ for (const device of devices) {
548
+ const deviceJid = device.jid;
549
+ const hasKey = !!senderKeyMap[deviceJid];
550
+ if ((!hasKey || !!participant) &&
551
+ !isHostedLidUser(deviceJid) &&
552
+ !isHostedPnUser(deviceJid) &&
553
+ device.device !== 99) {
554
+ //todo: revamp all this logic
555
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
556
+ senderKeyRecipients.push(deviceJid);
557
+ senderKeyMap[deviceJid] = true;
558
+ }
559
+ }
560
+ if (senderKeyRecipients.length) {
561
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
562
+ const senderKeyMsg = {
563
+ senderKeyDistributionMessage: {
564
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
565
+ groupId: destinationJid
566
+ }
567
+ };
568
+ const senderKeySessionTargets = senderKeyRecipients;
569
+ await assertSessions(senderKeySessionTargets);
570
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
571
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
572
+ participants.push(...result.nodes);
573
+ }
574
+ if (isRetryResend) {
575
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
576
+ data: bytes,
577
+ jid: participant?.jid
578
+ });
579
+ binaryNodeContent.push({
580
+ tag: 'enc',
581
+ attrs: {
582
+ v: '2',
583
+ type,
584
+ count: participant.count.toString()
585
+ },
586
+ content: encryptedContent
587
+ });
588
+ }
589
+ else {
590
+ binaryNodeContent.push({
591
+ tag: 'enc',
592
+ attrs: {
593
+ v: '2',
594
+ type: 'skmsg',
595
+ ...extraAttrs
596
+ },
597
+ content: ciphertext
598
+ });
599
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
600
+ }
601
+ }
602
+ else {
603
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
604
+ // TODO: investigate if this is true
605
+ let ownId = meId;
606
+ if (isLid && meLid) {
607
+ ownId = meLid;
608
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
609
+ }
610
+ else {
611
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
612
+ }
613
+ const { user: ownUser } = jidDecode(ownId);
614
+ if (!participant) {
615
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
616
+ devices.push({
617
+ user,
618
+ device: 0,
619
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
620
+ });
621
+ if (user !== ownUser) {
622
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
623
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
624
+ devices.push({
625
+ user: ownUserForAddressing,
626
+ device: 0,
627
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
628
+ });
629
+ }
630
+ if (additionalAttributes?.['category'] !== 'peer') {
631
+ // Clear placeholders and enumerate actual devices
632
+ devices.length = 0;
633
+ // Use conversation-appropriate sender identity
634
+ const senderIdentity = isLid && meLid
635
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
636
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
637
+ // Enumerate devices for sender and target with consistent addressing
638
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
639
+ devices.push(...sessionDevices);
640
+ logger.debug({
641
+ deviceCount: devices.length,
642
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
643
+ }, 'Device enumeration complete with unified addressing');
644
+ }
645
+ }
646
+ const allRecipients = [];
647
+ const meRecipients = [];
648
+ const otherRecipients = [];
649
+ const { user: mePnUser } = jidDecode(meId);
650
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
651
+ for (const { user, jid } of devices) {
652
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
653
+ if (isExactSenderDevice) {
654
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
655
+ continue;
656
+ }
657
+ // Check if this is our device (could match either PN or LID user)
658
+ const isMe = user === mePnUser || user === meLidUser;
659
+ if (isMe) {
660
+ meRecipients.push(jid);
661
+ }
662
+ else {
663
+ otherRecipients.push(jid);
664
+ }
665
+ allRecipients.push(jid);
666
+ }
667
+ await assertSessions(allRecipients);
668
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
669
+ // For own devices: use DSM if available (1:1 chats only)
670
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
671
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
672
+ ]);
673
+ participants.push(...meNodes);
674
+ participants.push(...otherNodes);
675
+ /* if (meRecipients.length > 0 || otherRecipients.length > 0) {
676
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
677
+ }*/
678
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
679
+ }
680
+ if (participants.length) {
681
+ if (additionalAttributes?.['category'] === 'peer') {
682
+ const peerNode = participants[0]?.content?.[0];
683
+ if (peerNode) {
684
+ binaryNodeContent.push(peerNode); // push only enc
685
+ }
686
+ }
687
+ else {
688
+ binaryNodeContent.push({
689
+ tag: 'participants',
690
+ attrs: {},
691
+ content: participants
692
+ });
693
+ }
694
+ }
695
+ const stanza = {
696
+ tag: 'message',
697
+ attrs: {
698
+ id: msgId,
699
+ to: destinationJid,
700
+ type: getTypeMessage(messages),
701
+ ...(additionalAttributes || {})
702
+ },
703
+ content: binaryNodeContent
704
+ };
705
+ // if the participant to send to is explicitly specified (generally retry recp)
706
+ // ensure the message is only sent to that person
707
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
708
+ if (participant) {
709
+ if (isJidGroup(destinationJid)) {
710
+ stanza.attrs.to = destinationJid;
711
+ stanza.attrs.participant = participant.jid;
712
+ }
713
+ else if (areJidsSameUser(participant.jid, meId)) {
714
+ stanza.attrs.to = participant.jid;
715
+ stanza.attrs.recipient = destinationJid;
716
+ }
717
+ else {
718
+ stanza.attrs.to = participant.jid;
719
+ }
720
+ }
721
+ else {
722
+ stanza.attrs.to = destinationJid;
723
+ }
724
+ if (shouldIncludeDeviceIdentity) {
725
+ ;
726
+ stanza.content.push({
727
+ tag: 'device-identity',
728
+ attrs: {},
729
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
730
+ });
731
+ logger.debug({ jid }, 'adding device identity');
732
+ }
733
+ if (AI && isPrivate) {
734
+ const botNode = {
735
+ tag: 'bot',
736
+ attrs: {
737
+ biz_bot: '1'
738
+ }
739
+ }
740
+
741
+ const filteredBizBot = getBinaryNodeFilter(additionalNodes ? additionalNodes : [])
742
+
743
+ if (filteredBizBot) {
744
+ stanza.content.push(...additionalNodes)
745
+ didPushAdditional = true
746
+ }
747
+
748
+ else {
749
+ stanza.content.push(botNode)
750
+ }
751
+ }
752
+
753
+ if(!isNewsletter && buttonType && !isStatus) {
754
+ const content = getAdditionalNode(buttonType)
755
+ const filteredNode = getBinaryNodeFilter(additionalNodes)
756
+
757
+ if (filteredNode) {
758
+ didPushAdditional = true
759
+ stanza.content.push(...additionalNodes)
760
+ }
761
+ else {
762
+ stanza.content.push(...content)
763
+ }
764
+ logger.debug({ jid }, 'adding business node')
765
+ }
766
+
767
+ if (!didPushAdditional && additionalNodes && additionalNodes.length > 0) {
768
+ stanza.content.push(...additionalNodes);
769
+ }
770
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
771
+ await sendNode(stanza);
772
+ // Add message to retry cache if enabled
773
+ if (messageRetryManager && !participant) {
774
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
775
+ }
776
+ }, meId);
777
+ return msgId;
778
+ };
779
+ const getTypeMessage = (msg) => {
780
+ const message = normalizeMessageContent(msg)
781
+ if (message.reactionMessage) {
782
+ return 'reaction'
783
+ }
784
+ else if (getMediaType(message)) {
785
+ return 'media'
786
+ }
787
+ else {
788
+ return 'text'
789
+ }
790
+ }
791
+ const getMediaType = (message) => {
792
+ if (message.imageMessage) {
793
+ return 'image'
794
+ }
795
+ else if (message.videoMessage) {
796
+ return message.videoMessage.gifPlayback ? 'gif' : 'video'
797
+ }
798
+ else if (message.audioMessage) {
799
+ return message.audioMessage.ptt ? 'ptt' : 'audio'
800
+ }
801
+ else if (message.contactMessage) {
802
+ return 'vcard'
803
+ }
804
+ else if (message.documentMessage) {
805
+ return 'document'
806
+ }
807
+ else if (message.contactsArrayMessage) {
808
+ return 'contact_array'
809
+ }
810
+ else if (message.liveLocationMessage) {
811
+ return 'livelocation'
812
+ }
813
+ else if (message.stickerMessage) {
814
+ return 'sticker'
815
+ }
816
+ else if (message.listMessage) {
817
+ return 'list'
818
+ }
819
+ else if (message.listResponseMessage) {
820
+ return 'list_response'
821
+ }
822
+ else if (message.buttonsResponseMessage) {
823
+ return 'buttons_response'
824
+ }
825
+ else if (message.orderMessage) {
826
+ return 'order'
827
+ }
828
+ else if (message.productMessage) {
829
+ return 'product'
830
+ }
831
+ else if (message.interactiveResponseMessage) {
832
+ return 'native_flow_response'
833
+ }
834
+ else if (message.groupInviteMessage) {
835
+ return 'url'
836
+ }
837
+ else if (/https:\/\/wa\.me\/p\/\d+\/\d+/.test(message.extendedTextMessage?.text)) {
838
+ return 'productlink'
839
+ }
840
+ }
841
+ const getButtonType = (message) => {
842
+ if (message.listMessage) {
843
+ return 'list'
844
+ }
845
+ else if (message.buttonsMessage) {
846
+ return 'buttons'
847
+ }
848
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
849
+ return 'review_and_pay'
850
+ }
851
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
852
+ return 'review_order'
853
+ }
854
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
855
+ return 'payment_info'
856
+ }
857
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
858
+ return 'payment_status'
859
+ }
860
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
861
+ return 'payment_method'
862
+ }
863
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
864
+ return 'interactive'
865
+ }
866
+ else if (message.interactiveMessage?.nativeFlowMessage) {
867
+ return 'native_flow'
868
+ }
869
+ }
870
+ const getPrivacyTokens = async (jids) => {
871
+ const t = unixTimestampSeconds().toString();
872
+ const result = await query({
873
+ tag: 'iq',
874
+ attrs: {
875
+ to: S_WHATSAPP_NET,
876
+ type: 'set',
877
+ xmlns: 'privacy'
878
+ },
879
+ content: [
880
+ {
881
+ tag: 'tokens',
882
+ attrs: {},
883
+ content: jids.map(jid => ({
884
+ tag: 'token',
885
+ attrs: {
886
+ jid: jidNormalizedUser(jid),
887
+ t,
888
+ type: 'trusted_contact'
889
+ }
890
+ }))
891
+ }
892
+ ]
893
+ });
894
+ return result;
895
+ };
896
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
897
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
898
+ return {
899
+ ...sock,
900
+ getPrivacyTokens,
901
+ assertSessions,
902
+ relayMessage,
903
+ sendReceipt,
904
+ sendReceipts,
905
+ readMessages,
906
+ refreshMediaConn,
907
+ waUploadToServer,
908
+ fetchPrivacySettings,
909
+ sendPeerDataOperationMessage,
910
+ createParticipantNodes,
911
+ getUSyncDevices,
912
+ messageRetryManager,
913
+ updateMediaMessage: async (message) => {
914
+ const content = assertMediaContent(message.message);
915
+ const mediaKey = content.mediaKey;
916
+ const meId = authState.creds.me.id;
917
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
918
+ let error = undefined;
919
+ await Promise.all([
920
+ sendNode(node),
921
+ waitForMsgMediaUpdate(async (update) => {
922
+ const result = update.find(c => c.key.id === message.key.id);
923
+ if (result) {
924
+ if (result.error) {
925
+ error = result.error;
926
+ }
927
+ else {
928
+ try {
929
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
930
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
931
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
932
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
933
+ data: media,
934
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
935
+ });
936
+ }
937
+ content.directPath = media.directPath;
938
+ content.url = getUrlFromDirectPath(content.directPath);
939
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
940
+ }
941
+ catch (err) {
942
+ error = err;
943
+ }
944
+ }
945
+ return true;
946
+ }
947
+ })
948
+ ]);
949
+ if (error) {
950
+ throw error;
951
+ }
952
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
953
+ return message;
954
+ },
955
+ sendMessage: async (jid, content, options = {}) => {
956
+ const userJid = authState.creds.me.id;
957
+ if (typeof content === 'object' &&
958
+ 'disappearingMessagesInChat' in content &&
959
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
960
+ isJidGroup(jid)) {
961
+ const { disappearingMessagesInChat } = content;
962
+ const value = typeof disappearingMessagesInChat === 'boolean'
963
+ ? disappearingMessagesInChat
964
+ ? WA_DEFAULT_EPHEMERAL
965
+ : 0
966
+ : disappearingMessagesInChat;
967
+ await groupToggleEphemeral(jid, value);
968
+ }
969
+ else {
970
+ const fullMsg = await generateWAMessage(jid, content, {
971
+ logger,
972
+ userJid,
973
+ getUrlInfo: text => getUrlInfo(text, {
974
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
975
+ fetchOpts: {
976
+ timeout: 3000,
977
+ ...(httpRequestOptions || {})
978
+ },
979
+ logger,
980
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
981
+ }),
982
+ //TODO: CACHE
983
+ getProfilePicUrl: sock.profilePictureUrl,
984
+ getCallLink: sock.createCallLink,
985
+ upload: async (readStream, opts) => {
986
+ const up = await waUploadToServer(readStream, {
987
+ ...opts,
988
+ newsletter: isJidNewsletter(jid)
989
+ });
990
+ return up;
991
+ },
992
+ mediaCache: config.mediaCache,
993
+ options: config.options,
994
+ messageId: generateMessageIDV2(sock.user?.id),
995
+ ...options
996
+ });
997
+ const isAiMsg = 'ai' in content && !!content.ai;
998
+ const isEventMsg = 'event' in content && !!content.event;
999
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1000
+ const isEditMsg = 'edit' in content && !!content.edit;
1001
+ const isPinMsg = 'pin' in content && !!content.pin;
1002
+ const isPollMessage = 'poll' in content && !!content.poll;
1003
+ const additionalAttributes = {};
1004
+ const additionalNodes = [];
1005
+ // required for delete
1006
+ if (isDeleteMsg) {
1007
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1008
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1009
+ additionalAttributes.edit = '8';
1010
+ }
1011
+ else {
1012
+ additionalAttributes.edit = '7';
1013
+ }
1014
+ }
1015
+ else if (isEditMsg) {
1016
+ additionalAttributes.edit = '1';
1017
+ }
1018
+ else if (isAiMsg) {
1019
+ additionalNodes.push({
1020
+ attrs: {
1021
+ biz_bot: '1'
1022
+ }, tag: "bot"
1023
+ });
1024
+ }
1025
+ else if (isPinMsg) {
1026
+ additionalAttributes.edit = '2';
1027
+ }
1028
+ else if (isPollMessage) {
1029
+ additionalNodes.push({
1030
+ tag: 'meta',
1031
+ attrs: {
1032
+ polltype: 'creation'
1033
+ }
1034
+ });
1035
+ }
1036
+ else if (isEventMsg) {
1037
+ additionalNodes.push({
1038
+ tag: 'meta',
1039
+ attrs: {
1040
+ event_type: 'creation'
1041
+ }
1042
+ });
1043
+ }
1044
+ await relayMessage(jid, fullMsg.message, {
1045
+ messageId: fullMsg.key.id,
1046
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1047
+ additionalAttributes,
1048
+ statusJidList: options.statusJidList,
1049
+ additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes
1050
+ });
1051
+ if (config.emitOwnEvents) {
1052
+ process.nextTick(() => {
1053
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1054
+ });
1055
+ }
1056
+ return fullMsg;
1057
+ }
1058
+ }
1059
+ };
1060
+ };
1061
+ //# sourceMappingURL=messages-send.js.map