alipclutch-baileys 8.3.0 → 8.4.1

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 (120) hide show
  1. package/LICENSE +3 -1
  2. package/README.md +10 -9
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.d.ts +55057 -0
  6. package/WAProto/index.js +56887 -17535
  7. package/WAProto/index.ts.ts +53473 -0
  8. package/lib/Defaults/baileys-version.json +2 -2
  9. package/lib/Defaults/index.d.ts +16 -7
  10. package/lib/Defaults/index.js +90 -119
  11. package/lib/Socket/Client/index.d.ts +2 -3
  12. package/lib/Socket/Client/index.js +2 -3
  13. package/lib/Socket/Client/types.d.ts +0 -1
  14. package/lib/Socket/Client/types.js +0 -1
  15. package/lib/Socket/Client/websocket.d.ts +0 -1
  16. package/lib/Socket/Client/websocket.js +0 -1
  17. package/lib/Socket/business.d.ts +59 -58
  18. package/lib/Socket/chats.d.ts +45 -230
  19. package/lib/Socket/chats.js +139 -238
  20. package/lib/Socket/groups.d.ts +41 -32
  21. package/lib/Socket/groups.js +38 -23
  22. package/lib/Socket/index.d.ts +63 -64
  23. package/lib/Socket/index.js +2 -3
  24. package/lib/Socket/messages-recv.js +9 -65
  25. package/lib/Socket/messages-send.d.ts +49 -47
  26. package/lib/Socket/messages-send.js +584 -395
  27. package/lib/Socket/newsletter.d.ts +39 -37
  28. package/lib/Socket/newsletter.js +88 -123
  29. package/lib/Socket/setup.js +433 -0
  30. package/lib/Socket/{dugong.d.ts → setup.ts} +17 -52
  31. package/lib/Socket/socket.d.ts +10 -10
  32. package/lib/Socket/socket.js +62 -38
  33. package/lib/Socket/usync.d.ts +3 -4
  34. package/lib/Socket/usync.js +0 -1
  35. package/lib/Store/index.d.ts +1 -2
  36. package/lib/Store/index.js +1 -3
  37. package/lib/Store/make-in-memory-store.d.ts +24 -24
  38. package/lib/Store/make-in-memory-store.js +26 -14
  39. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  40. package/lib/Store/make-ordered-dictionary.js +2 -2
  41. package/lib/Types/Auth.d.ts +0 -7
  42. package/lib/Types/Call.d.ts +1 -1
  43. package/lib/Types/Chat.d.ts +14 -7
  44. package/lib/Types/Contact.d.ts +5 -1
  45. package/lib/Types/Events.d.ts +44 -2
  46. package/lib/Types/GroupMetadata.d.ts +11 -2
  47. package/lib/Types/Label.js +1 -1
  48. package/lib/Types/LabelAssociation.js +1 -1
  49. package/lib/Types/Message.d.ts +148 -21
  50. package/lib/Types/Message.js +0 -2
  51. package/lib/Types/Newsletter.d.ts +73 -97
  52. package/lib/Types/Newsletter.js +18 -38
  53. package/lib/Types/Socket.d.ts +17 -9
  54. package/lib/Types/index.d.ts +8 -1
  55. package/lib/Types/index.js +2 -2
  56. package/lib/Utils/auth-utils.d.ts +3 -3
  57. package/lib/Utils/auth-utils.js +6 -13
  58. package/lib/Utils/business.js +2 -2
  59. package/lib/Utils/chat-utils.d.ts +15 -16
  60. package/lib/Utils/chat-utils.js +36 -35
  61. package/lib/Utils/crypto.d.ts +15 -16
  62. package/lib/Utils/crypto.js +71 -29
  63. package/lib/Utils/decode-wa-message.d.ts +22 -6
  64. package/lib/Utils/decode-wa-message.js +65 -56
  65. package/lib/Utils/event-buffer.d.ts +2 -2
  66. package/lib/Utils/event-buffer.js +11 -7
  67. package/lib/Utils/generics.d.ts +17 -20
  68. package/lib/Utils/generics.js +95 -75
  69. package/lib/Utils/history.d.ts +4 -0
  70. package/lib/Utils/history.js +4 -6
  71. package/lib/Utils/link-preview.d.ts +2 -2
  72. package/lib/Utils/link-preview.js +34 -1
  73. package/lib/Utils/logger.d.ts +10 -3
  74. package/lib/Utils/lt-hash.d.ts +2 -2
  75. package/lib/Utils/lt-hash.js +6 -6
  76. package/lib/Utils/make-mutex.d.ts +2 -2
  77. package/lib/Utils/messages-media.d.ts +28 -24
  78. package/lib/Utils/messages-media.js +272 -111
  79. package/lib/Utils/messages.d.ts +13 -10
  80. package/lib/Utils/messages.js +323 -50
  81. package/lib/Utils/noise-handler.d.ts +10 -12
  82. package/lib/Utils/noise-handler.js +18 -23
  83. package/lib/Utils/process-message.d.ts +5 -4
  84. package/lib/Utils/process-message.js +108 -25
  85. package/lib/Utils/signal.d.ts +2 -1
  86. package/lib/Utils/signal.js +26 -26
  87. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -1
  88. package/lib/Utils/use-multi-file-auth-state.js +51 -6
  89. package/lib/Utils/validate-connection.d.ts +3 -4
  90. package/lib/Utils/validate-connection.js +90 -66
  91. package/lib/WABinary/constants.d.ts +24 -27
  92. package/lib/WABinary/constants.js +1276 -13
  93. package/lib/WABinary/decode.d.ts +3 -4
  94. package/lib/WABinary/decode.js +26 -13
  95. package/lib/WABinary/encode.d.ts +1 -2
  96. package/lib/WABinary/encode.js +137 -152
  97. package/lib/WABinary/generic-utils.d.ts +1 -4
  98. package/lib/WABinary/generic-utils.js +37 -125
  99. package/lib/WABinary/jid-utils.d.ts +11 -5
  100. package/lib/WABinary/jid-utils.js +28 -5
  101. package/lib/WABinary/jid-utils.js.bak +83 -0
  102. package/lib/WAM/BinaryInfo.d.ts +2 -11
  103. package/lib/WAM/encode.d.ts +1 -2
  104. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  105. package/lib/index.d.ts +0 -1
  106. package/lib/index.js +27 -15
  107. package/package.json +18 -31
  108. package/engine-requirements.js +0 -10
  109. package/lib/Defaults/phonenumber-mcc.json +0 -223
  110. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  111. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  112. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  113. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  114. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  115. package/lib/Socket/Client/web-socket-client.js +0 -62
  116. package/lib/Socket/dugong.js +0 -483
  117. package/lib/Socket/registration.d.ts +0 -267
  118. package/lib/Socket/registration.js +0 -166
  119. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  120. package/lib/Store/make-cache-manager-store.js +0 -83
@@ -1,42 +1,49 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.decodeMessageNode = void 0;
3
+ exports.decryptMessageNode = exports.NACK_REASONS = exports.MISSING_KEYS_ERROR_TEXT = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
4
+ exports.decodeMessageNode = decodeMessageNode;
4
5
  const boom_1 = require("@hapi/boom");
5
6
  const WAProto_1 = require("../../WAProto");
6
7
  const WABinary_1 = require("../WABinary");
7
8
  const generics_1 = require("./generics");
8
- const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
9
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
10
+ exports.MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
11
+ exports.NACK_REASONS = {
12
+ ParsingError: 487,
13
+ UnrecognizedStanza: 488,
14
+ UnrecognizedStanzaClass: 489,
15
+ UnrecognizedStanzaType: 490,
16
+ InvalidProtobuf: 491,
17
+ InvalidHostedCompanionStanza: 493,
18
+ MissingMessageSecret: 495,
19
+ SignalErrorOldCounter: 496,
20
+ MessageDeletedOnPeer: 499,
21
+ UnhandledError: 500,
22
+ UnsupportedAdminRevoke: 550,
23
+ UnsupportedLIDGroup: 551,
24
+ DBOperationFailed: 552
25
+ };
9
26
  /**
10
27
  * Decode the received node as a message.
11
28
  * @note this will only parse the message, not decrypt it
12
29
  */
13
30
  function decodeMessageNode(stanza, meId, meLid) {
14
- var _a, _b;
31
+ var _a, _b, _c, _d, _e, _f, _g;
15
32
  let msgType;
16
33
  let chatId;
17
34
  let author;
18
35
  const msgId = stanza.attrs.id;
19
36
  const from = stanza.attrs.from;
37
+ const senderPn = (_a = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _a === void 0 ? void 0 : _a.sender_pn;
38
+ const senderLid = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.sender_lid;
20
39
  const participant = stanza.attrs.participant;
40
+ const participantLid = (_c = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _c === void 0 ? void 0 : _c.participant_lid;
21
41
  const recipient = stanza.attrs.recipient;
22
42
  const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
23
43
  const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
24
- if ((0, WABinary_1.isJidUser)(from)) {
25
- if (recipient) {
26
- if (!isMe(from)) {
27
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
28
- }
29
- chatId = recipient;
30
- }
31
- else {
32
- chatId = from;
33
- }
34
- msgType = 'chat';
35
- author = from;
36
- }
37
- else if ((0, WABinary_1.isLidUser)(from)) {
38
- if (recipient) {
39
- if (!isMeLid(from)) {
44
+ if ((0, WABinary_1.isJidUser)(from) || (0, WABinary_1.isLidUser)(from)) {
45
+ if (recipient && !(0, WABinary_1.isJidMetaAi)(recipient)) {
46
+ if (!isMe(from) && !isMeLid(from)) {
40
47
  throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
41
48
  }
42
49
  chatId = recipient;
@@ -55,6 +62,11 @@ function decodeMessageNode(stanza, meId, meLid) {
55
62
  author = participant;
56
63
  chatId = from;
57
64
  }
65
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
66
+ msgType = 'newsletter';
67
+ author = from;
68
+ chatId = from;
69
+ }
58
70
  else if ((0, WABinary_1.isJidBroadcast)(from)) {
59
71
  if (!participant) {
60
72
  throw new boom_1.Boom('No participant in group message');
@@ -69,21 +81,20 @@ function decodeMessageNode(stanza, meId, meLid) {
69
81
  chatId = from;
70
82
  author = participant;
71
83
  }
72
- else if ((0, WABinary_1.isJidNewsLetter)(from)) {
73
- msgType = 'newsletter';
74
- author = from;
75
- chatId = from;
76
- }
77
84
  else {
78
85
  throw new boom_1.Boom('Unknown message type', { data: stanza });
79
86
  }
80
- const fromMe = (0, WABinary_1.isJidNewsLetter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
81
- const pushname = stanza.attrs.notify;
87
+ const fromMe = (0, WABinary_1.isJidNewsletter)(from) ? !!((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.is_sender) || false : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
88
+ const pushname = (_e = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _e === void 0 ? void 0 : _e.notify;
82
89
  const key = {
83
90
  remoteJid: chatId,
84
91
  fromMe,
85
92
  id: msgId,
86
- participant
93
+ senderPn,
94
+ senderLid,
95
+ participant,
96
+ participantLid,
97
+ 'server_id': (_f = stanza.attrs) === null || _f === void 0 ? void 0 : _f.server_id
87
98
  };
88
99
  const fullMessage = {
89
100
  key,
@@ -92,7 +103,7 @@ function decodeMessageNode(stanza, meId, meLid) {
92
103
  broadcast: (0, WABinary_1.isJidBroadcast)(from)
93
104
  };
94
105
  if (msgType === 'newsletter') {
95
- fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
106
+ fullMessage.newsletterServerId = +((_g = stanza.attrs) === null || _g === void 0 ? void 0 : _g.server_id);
96
107
  }
97
108
  if (key.fromMe) {
98
109
  fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
@@ -103,7 +114,6 @@ function decodeMessageNode(stanza, meId, meLid) {
103
114
  sender: msgType === 'chat' ? author : chatId
104
115
  };
105
116
  }
106
- exports.decodeMessageNode = decodeMessageNode;
107
117
  const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
108
118
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
109
119
  return {
@@ -113,34 +123,17 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
113
123
  async decrypt() {
114
124
  var _a;
115
125
  let decryptables = 0;
116
- async function processSenderKeyDistribution(msg) {
117
- if (msg.senderKeyDistributionMessage) {
118
- try {
119
- await repository.processSenderKeyDistributionMessage({
120
- authorJid: author,
121
- item: msg.senderKeyDistributionMessage
122
- });
123
- }
124
- catch (err) {
125
- logger.error({ key: fullMessage.key, err }, 'failed to process senderKeyDistribution');
126
- }
127
- }
128
- }
129
- if ((0, WABinary_1.isJidNewsLetter)(fullMessage.key.remoteJid)) {
130
- const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
131
- const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
132
- await processSenderKeyDistribution(msg);
133
- fullMessage.message = msg;
134
- decryptables += 1;
135
- }
136
- else if (Array.isArray(stanza.content)) {
126
+ if (Array.isArray(stanza.content)) {
137
127
  for (const { tag, attrs, content } of stanza.content) {
138
128
  if (tag === 'verified_name' && content instanceof Uint8Array) {
139
129
  const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
140
130
  const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
141
131
  fullMessage.verifiedBizName = details.verifiedName;
142
132
  }
143
- if (tag !== 'enc') {
133
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
134
+ fullMessage.key.isViewOnce = true;
135
+ }
136
+ if (tag !== 'enc' && tag !== 'plaintext') {
144
137
  continue;
145
138
  }
146
139
  if (!(content instanceof Uint8Array)) {
@@ -149,7 +142,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
149
142
  decryptables += 1;
150
143
  let msgBuffer;
151
144
  try {
152
- const e2eType = attrs.type;
145
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
153
146
  switch (e2eType) {
154
147
  case 'skmsg':
155
148
  msgBuffer = await repository.decryptGroupMessage({
@@ -167,12 +160,28 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
167
160
  ciphertext: content
168
161
  });
169
162
  break;
163
+ case 'plaintext':
164
+ msgBuffer = content;
165
+ break;
166
+ case undefined:
167
+ msgBuffer = content;
168
+ break;
170
169
  default:
171
170
  throw new Error(`Unknown e2e type: ${e2eType}`);
172
171
  }
173
- let msg = WAProto_1.proto.Message.decode((0, generics_1.unpadRandomMax16)(msgBuffer));
174
- msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
175
- await processSenderKeyDistribution(msg);
172
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
173
+ msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
174
+ if (msg.senderKeyDistributionMessage) {
175
+ try {
176
+ await repository.processSenderKeyDistributionMessage({
177
+ authorJid: author,
178
+ item: msg.senderKeyDistributionMessage
179
+ });
180
+ }
181
+ catch (err) {
182
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
183
+ }
184
+ }
176
185
  if (fullMessage.message) {
177
186
  Object.assign(fullMessage.message, msg);
178
187
  }
@@ -190,7 +199,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
190
199
  // if nothing was found to decrypt
191
200
  if (!decryptables) {
192
201
  fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
193
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
202
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
194
203
  }
195
204
  }
196
205
  };
@@ -1,5 +1,5 @@
1
- import { Logger } from 'pino';
2
1
  import { BaileysEventEmitter, BaileysEventMap } from '../Types';
2
+ import { ILogger } from './logger';
3
3
  /**
4
4
  * A map that contains a list of all events that have been triggered
5
5
  *
@@ -31,5 +31,5 @@ type BaileysBufferableEventEmitter = BaileysEventEmitter & {
31
31
  * making the data processing more efficient.
32
32
  * @param ev the baileys event emitter
33
33
  */
34
- export declare const makeEventBuffer: (logger: Logger) => BaileysBufferableEventEmitter;
34
+ export declare const makeEventBuffer: (logger: ILogger) => BaileysBufferableEventEmitter;
35
35
  export {};
@@ -176,6 +176,9 @@ function append(data, historyCache, event, eventData, logger) {
176
176
  }
177
177
  }
178
178
  data.historySets.empty = false;
179
+ data.historySets.syncType = eventData.syncType;
180
+ data.historySets.progress = eventData.progress;
181
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
179
182
  data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
180
183
  break;
181
184
  case 'chats.upsert':
@@ -442,7 +445,10 @@ function consolidateEvents(data) {
442
445
  chats: Object.values(data.historySets.chats),
443
446
  messages: Object.values(data.historySets.messages),
444
447
  contacts: Object.values(data.historySets.contacts),
445
- isLatest: data.historySets.isLatest
448
+ syncType: data.historySets.syncType,
449
+ progress: data.historySets.progress,
450
+ isLatest: data.historySets.isLatest,
451
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
446
452
  };
447
453
  }
448
454
  const chatUpsertList = Object.values(data.chatUpserts);
@@ -496,12 +502,10 @@ function consolidateEvents(data) {
496
502
  return map;
497
503
  }
498
504
  function concatChats(a, b) {
499
- if (b.unreadCount === null) {
500
- // neutralize unread counter
501
- if (a.unreadCount < 0) {
502
- a.unreadCount = undefined;
503
- b.unreadCount = undefined;
504
- }
505
+ if (b.unreadCount === null && // neutralize unread counter
506
+ a.unreadCount < 0) {
507
+ a.unreadCount = undefined;
508
+ b.unreadCount = undefined;
505
509
  }
506
510
  if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
507
511
  b = { ...b };
@@ -1,24 +1,21 @@
1
- /// <reference types="node" />
2
1
  import { AxiosRequestConfig } from 'axios';
3
- import { Logger } from 'pino';
2
+ import { ILogger } from './logger';
4
3
  import { proto } from '../../WAProto';
5
- import { BaileysEventEmitter, BaileysEventMap, WACallUpdateType, WAVersion } from '../Types';
4
+ import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, WACallUpdateType, WAVersion } from '../Types';
6
5
  import { BinaryNode } from '../WABinary';
7
- export declare const Browsers: {
8
- ubuntu: (browser: any) => [string, string, string];
9
- macOS: (browser: any) => [string, string, string];
10
- baileys: (browser: any) => [string, string, string];
11
- windows: (browser: any) => [string, string, string];
12
- /** The appropriate browser based on your OS & release */
13
- appropriate: (browser: any) => [string, string, string];
14
- };
6
+ export declare const Browsers: BrowsersMap;
15
7
  export declare const getPlatformId: (browser: string) => any;
8
+ export declare const BufferJSON: {
9
+ replacer: (k: any, value: any) => any;
10
+ reviver: (_: any, value: any) => any;
11
+ };
16
12
  export declare const getKeyAuthor: (key: proto.IMessageKey | undefined | null, meId?: string) => string;
17
- export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer;
18
- export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array;
19
- export declare const encodeWAMessage: (message: proto.IMessage) => Buffer;
13
+ export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer<ArrayBuffer>;
14
+ export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array<ArrayBuffer>;
15
+ export declare const encodeWAMessage: (message: proto.IMessage) => Buffer<ArrayBuffer>;
16
+ export declare const encodeNewsletterMessage: (message: proto.IMessage) => Uint8Array<ArrayBufferLike>;
20
17
  export declare const generateRegistrationId: () => number;
21
- export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array;
18
+ export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array<ArrayBuffer>;
22
19
  export declare const toNumber: (t: Long | number | null | undefined) => number;
23
20
  /** unix timestamp of a date in seconds */
24
21
  export declare const unixTimestampSeconds: (date?: Date) => number;
@@ -37,9 +34,9 @@ export declare const delayCancellable: (ms: number) => {
37
34
  export declare function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error: any) => void) => void): Promise<T>;
38
35
  export declare const generateMessageIDV2: (userId?: string) => string;
39
36
  export declare const generateMessageID: () => string;
40
- export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => boolean | undefined, timeoutMs?: number) => Promise<void>;
41
- export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number) => Promise<void>;
42
- export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: Logger) => void;
37
+ export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
38
+ export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
39
+ export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: ILogger) => void;
43
40
  /**
44
41
  * utility that fetches latest baileys version from the master branch.
45
42
  * Use to ensure your WA connection is always on the latest version
@@ -57,7 +54,7 @@ export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<an
57
54
  * A utility that fetches the latest web version of whatsapp.
58
55
  * Use to ensure your WA connection is always on the latest version
59
56
  */
60
- export declare const fetchLatestWaWebVersion: (options: AxiosRequestConfig<any>) => Promise<{
57
+ export declare const fetchLatestWaWebVersion: (options: AxiosRequestConfig<{}>) => Promise<{
61
58
  version: WAVersion;
62
59
  isLatest: boolean;
63
60
  error?: undefined;
@@ -87,6 +84,6 @@ export declare const getCodeFromWSError: (error: Error) => number;
87
84
  * Is the given platform WA business
88
85
  * @param platform AuthenticationCreds.platform
89
86
  */
90
- export declare const isWABusinessPlatform: (platform: string) => boolean;
87
+ export declare const isWABusinessPlatform: (platform: string) => platform is "smba" | "smbi";
91
88
  export declare function trimUndefined(obj: any): any;
92
89
  export declare function bytesToCrockford(buffer: Buffer): string;
@@ -1,19 +1,61 @@
1
- "use strict";
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
39
+ exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
40
+ exports.promiseTimeout = promiseTimeout;
41
+ exports.bindWaitForEvent = bindWaitForEvent;
42
+ exports.trimUndefined = trimUndefined;
43
+ exports.bytesToCrockford = bytesToCrockford;
7
44
  const boom_1 = require("@hapi/boom");
8
45
  const axios_1 = __importDefault(require("axios"));
9
46
  const crypto_1 = require("crypto");
10
47
  const os_1 = require("os");
11
- const fetch_1 = require("node-fetch")
12
48
  const WAProto_1 = require("../../WAProto");
13
49
  const baileys_version_json_1 = require("../Defaults/baileys-version.json");
14
50
  const Types_1 = require("../Types");
15
51
  const WABinary_1 = require("../WABinary");
16
- const baileysVersion = [2, 3000, 1027934701]
52
+ const COMPANION_PLATFORM_MAP = {
53
+ 'Chrome': '49',
54
+ 'Edge': '50',
55
+ 'Firefox': '51',
56
+ 'Opera': '53',
57
+ 'Safari': '54'
58
+ };
17
59
  const PLATFORM_MAP = {
18
60
  'aix': 'AIX',
19
61
  'darwin': 'Mac OS',
@@ -28,12 +70,12 @@ exports.Browsers = {
28
70
  macOS: (browser) => ['Mac OS', browser, '14.4.1'],
29
71
  baileys: (browser) => ['Baileys', browser, '6.5.0'],
30
72
  windows: (browser) => ['Windows', browser, '10.0.22631'],
73
+ /** The appropriate browser based on your OS & release */
31
74
  appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
32
75
  };
33
-
34
76
  const getPlatformId = (browser) => {
35
77
  const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
36
- return platformType ? platformType.toString() : '1'; //chrome
78
+ return platformType ? platformType.toString() : '49'; //chrome
37
79
  };
38
80
  exports.getPlatformId = getPlatformId;
39
81
  exports.BufferJSON = {
@@ -76,6 +118,8 @@ const unpadRandomMax16 = (e) => {
76
118
  exports.unpadRandomMax16 = unpadRandomMax16;
77
119
  const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
78
120
  exports.encodeWAMessage = encodeWAMessage;
121
+ const encodeNewsletterMessage = (message) => (WAProto_1.proto.Message.encode(message).finish());
122
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
79
123
  const generateRegistrationId = () => {
80
124
  return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
81
125
  };
@@ -90,7 +134,7 @@ const encodeBigEndian = (e, t = 4) => {
90
134
  return a;
91
135
  };
92
136
  exports.encodeBigEndian = encodeBigEndian;
93
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
137
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
94
138
  exports.toNumber = toNumber;
95
139
  /** unix timestamp of a date in seconds */
96
140
  const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
@@ -156,7 +200,6 @@ async function promiseTimeout(ms, promise) {
156
200
  .finally(cancel);
157
201
  return p;
158
202
  }
159
- exports.promiseTimeout = promiseTimeout;
160
203
  const generateMessageIDV2 = (userId) => {
161
204
  const data = Buffer.alloc(8 + 20 + 16);
162
205
  data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
@@ -174,7 +217,7 @@ const generateMessageIDV2 = (userId) => {
174
217
  };
175
218
  exports.generateMessageIDV2 = generateMessageIDV2;
176
219
  // generate a random ID to attach to a message
177
- const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
220
+ const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
178
221
  exports.generateMessageID = generateMessageID;
179
222
  function bindWaitForEvent(ev, event) {
180
223
  return async (check, timeoutMs) => {
@@ -188,8 +231,8 @@ function bindWaitForEvent(ev, event) {
188
231
  }
189
232
  };
190
233
  ev.on('connection.update', closeListener);
191
- listener = (update) => {
192
- if (check(update)) {
234
+ listener = async (update) => {
235
+ if (await check(update)) {
193
236
  resolve();
194
237
  }
195
238
  };
@@ -201,14 +244,12 @@ function bindWaitForEvent(ev, event) {
201
244
  }));
202
245
  };
203
246
  }
204
- exports.bindWaitForEvent = bindWaitForEvent;
205
247
  const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
206
248
  exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
207
249
  const printQRIfNecessaryListener = (ev, logger) => {
208
250
  ev.on('connection.update', async ({ qr }) => {
209
251
  if (qr) {
210
- const QR = await import('qrcode-terminal')
211
- .then(m => m.default || m)
252
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
212
253
  .catch(() => {
213
254
  logger.error('QR code terminal not added as dependency');
214
255
  });
@@ -217,61 +258,8 @@ const printQRIfNecessaryListener = (ev, logger) => {
217
258
  });
218
259
  };
219
260
  exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
220
- /**
221
- * utility that fetches latest baileys version from the master branch.
222
- * Use to ensure your WA connection is always on the latest version
223
- */
224
- const fetchLatestWaWebVersion = async (options = {}) => {
225
- try {
226
- const defaultHeaders = {
227
- 'User-Agent':
228
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
229
- 'Accept': '*/*'
230
- }
231
-
232
- const headers = { ...defaultHeaders, ...options.headers }
233
-
234
- const response = await fetch_1('https://web.whatsapp.com/sw.js', {
235
- method: 'GET',
236
- headers
237
- })
238
-
239
- if (!response.ok) {
240
- throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
241
- }
242
-
243
- const data = await response.text()
244
- const regex = /"client_revision":\s*(\d+)/ // regex cukup begini untuk Node
245
- const match = data.match(regex)
246
-
247
- if (!match || !match[1]) {
248
- return {
249
- version: baileysVersion,
250
- isLatest: false,
251
- error: { message: 'Client revision not found' }
252
- }
253
- }
254
-
255
- const clientRevision = match[1]
256
- return {
257
- version: [2, 3000, +clientRevision],
258
- isLatest: true
259
- }
260
- } catch (error) {
261
- return {
262
- version: baileysVersion,
263
- isLatest: false,
264
- error
265
- }
266
- }
267
- }
268
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
269
- /**
270
- * utility that fetches latest baileys version from the master branch.
271
- * Use to ensure your WA connection is always on the latest version
272
- */
273
261
  const fetchLatestBaileysVersion = async (options = {}) => {
274
- const URL = 'https://raw.githubusercontent.com/kiuur/bails/master/src/Defaults/baileys-version.json';
262
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
275
263
  try {
276
264
  const result = await axios_1.default.get(URL, {
277
265
  ...options,
@@ -291,6 +279,42 @@ const fetchLatestBaileysVersion = async (options = {}) => {
291
279
  }
292
280
  };
293
281
  exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
282
+ /**
283
+ * A utility that fetches the latest web version of whatsapp.
284
+ * Use to ensure your WA connection is always on the latest version
285
+ */
286
+ const fetchLatestWaWebVersion = async (options) => {
287
+ try {
288
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
289
+ ...options,
290
+ responseType: 'json'
291
+ });
292
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
293
+ const match = data.match(regex);
294
+ if (!(match === null || match === void 0 ? void 0 : match[1])) {
295
+ return {
296
+ version: baileys_version_json_1.version,
297
+ isLatest: false,
298
+ error: {
299
+ message: 'Could not find client revision in the fetched content'
300
+ }
301
+ };
302
+ }
303
+ const clientRevision = match[1];
304
+ return {
305
+ version: [2, 3000, +clientRevision],
306
+ isLatest: true
307
+ };
308
+ }
309
+ catch (error) {
310
+ return {
311
+ version: baileys_version_json_1.version,
312
+ isLatest: false,
313
+ error
314
+ };
315
+ }
316
+ };
317
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
294
318
  /** unique message tag prefix for MD clients */
295
319
  const generateMdTagPrefix = () => {
296
320
  const bytes = (0, crypto_1.randomBytes)(4);
@@ -298,6 +322,7 @@ const generateMdTagPrefix = () => {
298
322
  };
299
323
  exports.generateMdTagPrefix = generateMdTagPrefix;
300
324
  const STATUS_MAP = {
325
+ 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
301
326
  'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
302
327
  'read': WAProto_1.proto.WebMessageInfo.Status.READ,
303
328
  'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
@@ -346,7 +371,8 @@ const getCallStatusFromNode = ({ tag, attrs }) => {
346
371
  status = 'timeout';
347
372
  }
348
373
  else {
349
- status = 'reject';
374
+ // fired when accepted/rejected/timeout/caller hangs up
375
+ status = 'terminate';
350
376
  }
351
377
  break;
352
378
  case 'reject':
@@ -395,7 +421,6 @@ function trimUndefined(obj) {
395
421
  }
396
422
  return obj;
397
423
  }
398
- exports.trimUndefined = trimUndefined;
399
424
  const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
400
425
  function bytesToCrockford(buffer) {
401
426
  let value = 0;
@@ -414,8 +439,3 @@ function bytesToCrockford(buffer) {
414
439
  }
415
440
  return crockford.join('');
416
441
  }
417
- exports.bytesToCrockford = bytesToCrockford;
418
- const encodeNewsletterMessage = (message) => {
419
- return WAProto_1.proto.Message.encode(message).finish()
420
- }
421
- exports.encodeNewsletterMessage = encodeNewsletterMessage;
@@ -6,10 +6,14 @@ export declare const processHistoryMessage: (item: proto.IHistorySync) => {
6
6
  chats: Chat[];
7
7
  contacts: Contact[];
8
8
  messages: proto.IWebMessageInfo[];
9
+ syncType: proto.HistorySync.HistorySyncType;
10
+ progress: number | null | undefined;
9
11
  };
10
12
  export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
11
13
  chats: Chat[];
12
14
  contacts: Contact[];
13
15
  messages: proto.IWebMessageInfo[];
16
+ syncType: proto.HistorySync.HistorySyncType;
17
+ progress: number | null | undefined;
14
18
  }>;
15
19
  export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined;
@@ -32,13 +32,9 @@ const processHistoryMessage = (item) => {
32
32
  case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
33
  case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
34
  case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
35
+ case WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND:
35
36
  for (const chat of item.conversations) {
36
- contacts.push({
37
- id: chat.id,
38
- name: chat.name || undefined,
39
- lid: chat.lidJid || undefined,
40
- jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
41
- });
37
+ contacts.push({ id: chat.id, name: chat.name || undefined, lid: chat.lidJid || undefined, jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : chat.pnJid });
42
38
  const msgs = chat.messages || [];
43
39
  delete chat.messages;
44
40
  delete chat.archived;
@@ -79,6 +75,8 @@ const processHistoryMessage = (item) => {
79
75
  chats,
80
76
  contacts,
81
77
  messages,
78
+ syncType: item.syncType,
79
+ progress: item.progress
82
80
  };
83
81
  };
84
82
  exports.processHistoryMessage = processHistoryMessage;