@realvare/based 2.7.61 → 2.7.70

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 (42) hide show
  1. package/README.MD +25 -114
  2. package/WAProto/WAProto.proto +1073 -244
  3. package/WAProto/index.d.ts +16282 -8183
  4. package/WAProto/index.js +76605 -50628
  5. package/engine-requirements.js +10 -10
  6. package/lib/Defaults/baileys-version.json +1 -1
  7. package/lib/Defaults/index.d.ts +1 -1
  8. package/lib/Defaults/index.js +5 -5
  9. package/lib/Socket/chats.js +53 -16
  10. package/lib/Socket/groups.js +53 -9
  11. package/lib/Socket/messages-recv.js +1298 -1237
  12. package/lib/Socket/messages-send.js +350 -456
  13. package/lib/Socket/socket.js +1 -1
  14. package/lib/Socket/usync.js +57 -4
  15. package/lib/Store/make-in-memory-store.js +28 -15
  16. package/lib/Types/Message.d.ts +316 -6
  17. package/lib/Types/Message.js +1 -1
  18. package/lib/Utils/cache-manager.d.ts +16 -0
  19. package/lib/Utils/cache-manager.js +20 -4
  20. package/lib/Utils/chat-utils.js +17 -13
  21. package/lib/Utils/decode-wa-message.js +1 -11
  22. package/lib/Utils/event-buffer.js +103 -2
  23. package/lib/Utils/generics.js +4 -5
  24. package/lib/Utils/index.d.ts +5 -0
  25. package/lib/Utils/index.js +3 -0
  26. package/lib/Utils/jid-validation.d.ts +2 -0
  27. package/lib/Utils/jid-validation.js +36 -5
  28. package/lib/Utils/link-preview.js +38 -28
  29. package/lib/Utils/messages-media.js +21 -52
  30. package/lib/Utils/messages.js +540 -23
  31. package/lib/Utils/performance-config.d.ts +2 -0
  32. package/lib/Utils/performance-config.js +16 -7
  33. package/lib/Utils/process-message.js +124 -12
  34. package/lib/Utils/rate-limiter.js +15 -20
  35. package/lib/WABinary/jid-utils.js +257 -5
  36. package/lib/WAUSync/Protocols/USyncContactProtocol.js +75 -5
  37. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -6
  38. package/lib/WAUSync/USyncQuery.js +64 -6
  39. package/lib/index.d.ts +1 -0
  40. package/lib/index.js +5 -2
  41. package/package.json +7 -13
  42. package/WAProto/index.ts.ts +0 -53473
@@ -1,10 +1,10 @@
1
- const major = parseInt(process.versions.node.split('.')[0], 10);
2
-
3
- if (major < 20) {
4
- console.error(
5
- `\n❌ This package requires Node.js 20+ to run reliably.\n` +
6
- ` You are using Node.js ${process.versions.node}.\n` +
7
- ` Please upgrade to Node.js 20+ to proceed.\n`
8
- );
9
- process.exit(1);
10
- }
1
+ const major = parseInt(process.versions.node.split('.')[0], 10);
2
+
3
+ if (major < 20) {
4
+ console.error(
5
+ `\n❌ This package requires Node.js 20+ to run reliably.\n` +
6
+ ` You are using Node.js ${process.versions.node}.\n` +
7
+ ` Please upgrade to Node.js 20+ to proceed.\n`
8
+ );
9
+ process.exit(1);
10
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": [2, 3000, 1030470917]
2
+ "version": [2, 3000, 1031424117]
3
3
  }
@@ -15,7 +15,7 @@ export declare const URL_REGEX: RegExp;
15
15
  export declare const WA_CERT_DETAILS: {
16
16
  SERIAL: number;
17
17
  };
18
- export declare const PROCESSABLE_HISTORY_TYPES: proto.Message.HistorySyncNotification.HistorySyncType[];
18
+ export declare const PROCESSABLE_HISTORY_TYPES: proto.Message.HistorySyncType[];
19
19
  export declare const DEFAULT_CONNECTION_CONFIG: SocketConfig;
20
20
  export declare const MEDIA_PATH_MAP: {
21
21
  [T in MediaType]?: string;
@@ -25,11 +25,11 @@ exports.WA_CERT_DETAILS = {
25
25
  SERIAL: 0,
26
26
  };
27
27
  exports.PROCESSABLE_HISTORY_TYPES = [
28
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.INITIAL_BOOTSTRAP,
29
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
30
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
31
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.FULL,
32
- WAProto_1.proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND,
28
+ WAProto_1.proto.Message.HistorySyncType.INITIAL_BOOTSTRAP,
29
+ WAProto_1.proto.Message.HistorySyncType.PUSH_NAME,
30
+ WAProto_1.proto.Message.HistorySyncType.RECENT,
31
+ WAProto_1.proto.Message.HistorySyncType.FULL,
32
+ WAProto_1.proto.Message.HistorySyncType.ON_DEMAND,
33
33
  ];
34
34
  exports.DEFAULT_CONNECTION_CONFIG = {
35
35
  version: baileys_version_json_1.version,
@@ -15,7 +15,9 @@ const process_message_1 = __importDefault(require("../Utils/process-message"));
15
15
  const WABinary_1 = require("../WABinary");
16
16
  const WAUSync_1 = require("../WAUSync");
17
17
  const usync_1 = require("./usync");
18
+ const retry_1 = require("../Utils/retry");
18
19
  const MAX_SYNC_ATTEMPTS = 2;
20
+ const APP_STATE_RESYNC_COOLDOWN_MS = 60000;
19
21
  const makeChatsSocket = (config) => {
20
22
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
23
  const sock = (0, usync_1.makeUSyncSocket)(config);
@@ -367,14 +369,23 @@ const makeChatsSocket = (config) => {
367
369
  }
368
370
  };
369
371
  };
372
+ const appStateResyncCooldown = new Map();
370
373
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
374
+ const now = Date.now();
375
+ const collectionsToSync = collections.filter(name => {
376
+ const until = appStateResyncCooldown.get(name) || 0;
377
+ return until <= now;
378
+ });
379
+ if (!collectionsToSync.length) {
380
+ return;
381
+ }
371
382
  // we use this to determine which events to fire
372
383
  // otherwise when we resync from scratch -- all notifications will fire
373
384
  const initialVersionMap = {};
374
385
  const globalMutationMap = {};
375
386
  await authState.keys.transaction(async () => {
376
387
  var _a;
377
- const collectionsToHandle = new Set(collections);
388
+ const collectionsToHandle = new Set(collectionsToSync);
378
389
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
379
390
  const attemptsMap = {};
380
391
  // keep executing till all collections are done
@@ -457,6 +468,9 @@ const makeChatsSocket = (config) => {
457
468
  || error.name === 'TypeError';
458
469
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
459
470
  await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
471
+ if (((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404) {
472
+ appStateResyncCooldown.set(name, Date.now() + APP_STATE_RESYNC_COOLDOWN_MS);
473
+ }
460
474
  // increment number of retries
461
475
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
462
476
  if (isIrrecoverableError) {
@@ -499,24 +513,40 @@ const makeChatsSocket = (config) => {
499
513
  const sendPresenceUpdate = async (type, toJid) => {
500
514
  toJid = resolveJid(toJid);
501
515
  const me = authState.creds.me;
516
+ const retryOptions = {
517
+ retries: 2,
518
+ baseMs: 1000,
519
+ maxMs: 5000,
520
+ jitter: true,
521
+ timeoutPerAttemptMs: 10000,
522
+ shouldRetry: (err) => {
523
+ if (err.message.includes('WebSocket is not open')) {
524
+ return false;
525
+ }
526
+ var _a;
527
+ const status = ((_a = err.output) === null || _a === void 0 ? void 0 : _a.statusCode) || (err === null || err === void 0 ? void 0 : err.statusCode);
528
+ return !status || (status >= 500 || status === 408 || status === 429);
529
+ },
530
+ onRetry: (err, n) => logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt: n }, 'retrying presence update')
531
+ };
502
532
  if (type === 'available' || type === 'unavailable') {
503
533
  if (!me.name) {
504
534
  logger.warn('no name present, ignoring presence update request...');
505
535
  return;
506
536
  }
507
537
  ev.emit('connection.update', { isOnline: type === 'available' });
508
- await sendNode({
538
+ await (0, retry_1.retryWithBackoff)(() => sendNode({
509
539
  tag: 'presence',
510
540
  attrs: {
511
541
  name: me.name.replace(/@/g, ''),
512
542
  type
513
543
  }
514
- });
544
+ }), retryOptions);
515
545
  }
516
546
  else {
517
547
  const { server } = (0, WABinary_1.jidDecode)(toJid);
518
548
  const isLid = server === 'lid';
519
- await sendNode({
549
+ await (0, retry_1.retryWithBackoff)(() => sendNode({
520
550
  tag: 'chatstate',
521
551
  attrs: {
522
552
  from: isLid ? me.lid : me.id,
@@ -528,7 +558,7 @@ const makeChatsSocket = (config) => {
528
558
  attrs: type === 'recording' ? { media: 'audio' } : {}
529
559
  }
530
560
  ]
531
- });
561
+ }), retryOptions);
532
562
  }
533
563
  };
534
564
  /**
@@ -754,22 +784,29 @@ const makeChatsSocket = (config) => {
754
784
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
755
785
  var _a, _b, _c;
756
786
  try {
757
- const r = msg?.key?.remoteJid;
758
- const p = msg?.key?.participant;
759
- if (r) {
760
- const rd = (0, WABinary_1.jidDecode)(r);
787
+ const r0 = msg?.key?.remoteJid;
788
+ const p0 = msg?.key?.participant;
789
+
790
+ if (r0) {
791
+ const rd = (0, WABinary_1.jidDecode)(r0);
761
792
  if (rd?.user) {
762
- const lid = (0, WABinary_1.jidEncode)(rd.user, 'lid');
763
- msg.key.remoteLid = lid;
764
- msg.key.remoteJidNormalized = (0, WABinary_1.jidNormalizedUser)(r);
793
+ // preserve LID form (original if provided, otherwise derived)
794
+ msg.key.remoteLid = (0, WABinary_1.isLid)(r0) ? r0 : (0, WABinary_1.jidEncode)(rd.user, 'lid');
765
795
  }
796
+ // always expose a standard jid to consumers
797
+ msg.key.remoteJid = (0, WABinary_1.jidNormalizedUser)((0, WABinary_1.lidToJid)(r0));
798
+ msg.key.remoteJidNormalized = msg.key.remoteJid;
766
799
  }
767
- if (p) {
768
- const pd = (0, WABinary_1.jidDecode)(p);
800
+
801
+ if (p0) {
802
+ const pd = (0, WABinary_1.jidDecode)(p0);
769
803
  if (pd?.user) {
770
- const lidP = (0, WABinary_1.jidEncode)(pd.user, 'lid');
771
- msg.key.participantLid = lidP;
804
+ msg.key.participantLid = (0, WABinary_1.isLid)(p0) ? p0 : (0, WABinary_1.jidEncode)(pd.user, 'lid');
772
805
  }
806
+ msg.key.participant = (0, WABinary_1.jidNormalizedUser)((0, WABinary_1.lidToJid)(p0));
807
+ }
808
+ if (msg === null || msg === void 0 ? void 0 : msg.participant) {
809
+ msg.participant = (0, WABinary_1.jidNormalizedUser)((0, WABinary_1.lidToJid)(msg.participant));
773
810
  }
774
811
  } catch {}
775
812
  ev.emit('messages.upsert', { messages: [msg], type });
@@ -6,6 +6,8 @@ const Types_1 = require("../Types");
6
6
  const Utils_1 = require("../Utils");
7
7
  const WABinary_1 = require("../WABinary");
8
8
  const chats_1 = require("./chats");
9
+ const { getPerformanceConfig } = require('../Utils/performance-config');
10
+ const { CacheManager } = require('../Utils/cache-manager');
9
11
  const makeGroupsSocket = (config) => {
10
12
  const sock = (0, chats_1.makeChatsSocket)(config);
11
13
  const { authState, ev, query, upsertMessage } = sock;
@@ -25,16 +27,41 @@ const makeGroupsSocket = (config) => {
25
27
  content
26
28
  }));
27
29
  const groupMetadata = async (jid) => {
28
- const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
29
- const metadata = (0, exports.extractGroupMetadata)(result);
30
- if (config.lidCache) {
31
- for (const p of metadata.participants) {
32
- if ((0, WABinary_1.isLid)(p.id) && !(0, WABinary_1.isLid)(p.jid)) {
33
- config.lidCache.set(p.id, p.jid);
30
+ const config = getPerformanceConfig();
31
+
32
+ // Check cache first
33
+ const cached = CacheManager.get('groupMetadataCache', jid);
34
+ if (cached) {
35
+ config.logger?.trace({ jid }, 'using cached group metadata');
36
+ return cached;
37
+ }
38
+
39
+ // Fetch from server with rate limiting and retry logic
40
+ let retryCount = 0;
41
+ const maxRetries = 3;
42
+ const baseDelay = 1000; // 1 second
43
+
44
+ while (retryCount <= maxRetries) {
45
+ try {
46
+ const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
47
+ const metadata = (0, exports.extractGroupMetadata)(result);
48
+
49
+ // Cache the result
50
+ CacheManager.set('groupMetadataCache', jid, metadata, config.cache.groupMetadataCache.ttl);
51
+
52
+ return metadata;
53
+ } catch (error) {
54
+ if (error.message === 'rate-overlimit' && retryCount < maxRetries) {
55
+ const delay = baseDelay * Math.pow(2, retryCount); // Exponential backoff
56
+ config.logger?.warn({ jid, retryCount, delay }, 'Rate limit hit, retrying group metadata fetch');
57
+ await new Promise(resolve => setTimeout(resolve, delay));
58
+ retryCount++;
59
+ } else {
60
+ // Re-throw non-rate-limit errors or if max retries exceeded
61
+ throw error;
34
62
  }
35
63
  }
36
64
  }
37
- return metadata;
38
65
  };
39
66
  const groupFetchAllParticipating = async () => {
40
67
  const result = await query({
@@ -79,6 +106,23 @@ const makeGroupsSocket = (config) => {
79
106
  await groupFetchAllParticipating();
80
107
  await sock.cleanDirtyBits('groups');
81
108
  });
109
+
110
+ // Cache invalidation on group events
111
+ ev.on('groups.update', async (groups) => {
112
+ for (const group of groups) {
113
+ CacheManager.del('groupMetadataCache', group.id);
114
+ }
115
+ });
116
+
117
+ ev.on('group-participants.update', async (update) => {
118
+ CacheManager.del('groupMetadataCache', update.id);
119
+ });
120
+
121
+ ev.on('groups.upsert', async (groups) => {
122
+ for (const group of groups) {
123
+ CacheManager.del('groupMetadataCache', group.id);
124
+ }
125
+ });
82
126
  return {
83
127
  ...sock,
84
128
  groupQuery,
@@ -339,7 +383,7 @@ const extractGroupMetadata = (result) => {
339
383
  participants: (0, WABinary_1.getBinaryNodeChildren)(group, 'participant').map(({ attrs }) => {
340
384
  return {
341
385
  id: attrs.jid,
342
- jid: attrs.phone_number || attrs.jid,
386
+ jid: attrs.phone_number || (0, WABinary_1.lidToJid)(attrs.jid),
343
387
  lid: attrs.lid || ((0, WABinary_1.isLid)(attrs.jid) ? attrs.jid : undefined),
344
388
  admin: (attrs.type || null),
345
389
  };
@@ -348,4 +392,4 @@ const extractGroupMetadata = (result) => {
348
392
  };
349
393
  return metadata;
350
394
  };
351
- exports.extractGroupMetadata = extractGroupMetadata;
395
+ exports.extractGroupMetadata = extractGroupMetadata;