@queenanya/baileys 6.7.0 → 6.8.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 (129) hide show
  1. package/WASignalGroup/readme.md +6 -0
  2. package/lib/Defaults/baileys-version.json +3 -3
  3. package/lib/Defaults/index.d.ts +284 -284
  4. package/lib/Defaults/index.js +120 -120
  5. package/lib/Defaults/phonenumber-mcc.json +223 -223
  6. package/lib/Signal/libsignal.d.ts +3 -3
  7. package/lib/Signal/libsignal.js +152 -152
  8. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -17
  9. package/lib/Socket/Client/abstract-socket-client.js +13 -13
  10. package/lib/Socket/Client/index.d.ts +3 -3
  11. package/lib/Socket/Client/index.js +19 -19
  12. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -13
  13. package/lib/Socket/Client/mobile-socket-client.js +65 -65
  14. package/lib/Socket/Client/web-socket-client.d.ts +12 -12
  15. package/lib/Socket/Client/web-socket-client.js +62 -62
  16. package/lib/Socket/business.d.ts +135 -135
  17. package/lib/Socket/business.js +259 -259
  18. package/lib/Socket/chats.d.ts +79 -79
  19. package/lib/Socket/chats.js +854 -854
  20. package/lib/Socket/groups.d.ts +113 -113
  21. package/lib/Socket/groups.js +302 -302
  22. package/lib/Socket/index.d.ts +137 -137
  23. package/lib/Socket/index.js +10 -10
  24. package/lib/Socket/messages-recv.d.ts +124 -124
  25. package/lib/Socket/messages-recv.js +747 -747
  26. package/lib/Socket/messages-send.d.ts +119 -119
  27. package/lib/Socket/messages-send.js +663 -663
  28. package/lib/Socket/registration.d.ts +232 -232
  29. package/lib/Socket/registration.js +166 -166
  30. package/lib/Socket/socket.d.ts +42 -42
  31. package/lib/Socket/socket.js +588 -588
  32. package/lib/Store/index.d.ts +3 -3
  33. package/lib/Store/index.js +10 -10
  34. package/lib/Store/make-cache-manager-store.d.ts +13 -13
  35. package/lib/Store/make-cache-manager-store.js +83 -83
  36. package/lib/Store/make-in-memory-store.d.ts +117 -117
  37. package/lib/Store/make-in-memory-store.js +437 -437
  38. package/lib/Store/make-ordered-dictionary.d.ts +13 -13
  39. package/lib/Store/make-ordered-dictionary.js +81 -81
  40. package/lib/Store/object-repository.d.ts +10 -10
  41. package/lib/Store/object-repository.js +27 -27
  42. package/lib/Types/Auth.d.ts +108 -108
  43. package/lib/Types/Auth.js +2 -2
  44. package/lib/Types/Call.d.ts +13 -13
  45. package/lib/Types/Call.js +2 -2
  46. package/lib/Types/Chat.d.ts +102 -102
  47. package/lib/Types/Chat.js +4 -4
  48. package/lib/Types/Contact.d.ts +19 -19
  49. package/lib/Types/Contact.js +2 -2
  50. package/lib/Types/Events.d.ts +157 -157
  51. package/lib/Types/Events.js +2 -2
  52. package/lib/Types/GroupMetadata.d.ts +52 -52
  53. package/lib/Types/GroupMetadata.js +2 -2
  54. package/lib/Types/Label.d.ts +35 -35
  55. package/lib/Types/Label.js +27 -27
  56. package/lib/Types/LabelAssociation.d.ts +29 -29
  57. package/lib/Types/LabelAssociation.js +9 -9
  58. package/lib/Types/Message.d.ts +261 -261
  59. package/lib/Types/Message.js +9 -9
  60. package/lib/Types/Product.d.ts +78 -78
  61. package/lib/Types/Product.js +2 -2
  62. package/lib/Types/Signal.d.ts +57 -57
  63. package/lib/Types/Signal.js +2 -2
  64. package/lib/Types/Socket.d.ts +111 -111
  65. package/lib/Types/Socket.js +2 -2
  66. package/lib/Types/State.d.ts +27 -27
  67. package/lib/Types/State.js +2 -2
  68. package/lib/Types/index.d.ts +56 -56
  69. package/lib/Types/index.js +41 -41
  70. package/lib/Utils/auth-utils.d.ts +18 -18
  71. package/lib/Utils/auth-utils.js +204 -204
  72. package/lib/Utils/baileys-event-stream.d.ts +16 -16
  73. package/lib/Utils/baileys-event-stream.js +63 -63
  74. package/lib/Utils/business.d.ts +22 -22
  75. package/lib/Utils/business.js +234 -234
  76. package/lib/Utils/chat-utils.d.ts +71 -71
  77. package/lib/Utils/chat-utils.js +724 -724
  78. package/lib/Utils/crypto.d.ts +41 -41
  79. package/lib/Utils/crypto.js +151 -151
  80. package/lib/Utils/decode-wa-message.d.ts +19 -19
  81. package/lib/Utils/decode-wa-message.js +174 -174
  82. package/lib/Utils/event-buffer.d.ts +35 -35
  83. package/lib/Utils/event-buffer.js +514 -514
  84. package/lib/Utils/generics.d.ts +94 -94
  85. package/lib/Utils/generics.js +367 -367
  86. package/lib/Utils/history.d.ts +15 -15
  87. package/lib/Utils/history.js +91 -91
  88. package/lib/Utils/index.d.ts +17 -17
  89. package/lib/Utils/index.js +33 -33
  90. package/lib/Utils/link-preview.d.ts +21 -21
  91. package/lib/Utils/link-preview.js +93 -93
  92. package/lib/Utils/logger.d.ts +4 -4
  93. package/lib/Utils/logger.js +7 -7
  94. package/lib/Utils/lt-hash.d.ts +12 -12
  95. package/lib/Utils/lt-hash.js +51 -51
  96. package/lib/Utils/make-mutex.d.ts +7 -7
  97. package/lib/Utils/make-mutex.js +43 -43
  98. package/lib/Utils/messages-media.d.ts +107 -107
  99. package/lib/Utils/messages-media.js +680 -680
  100. package/lib/Utils/messages.d.ts +76 -76
  101. package/lib/Utils/messages.js +768 -768
  102. package/lib/Utils/noise-handler.d.ts +20 -20
  103. package/lib/Utils/noise-handler.js +142 -142
  104. package/lib/Utils/process-message.d.ts +41 -41
  105. package/lib/Utils/process-message.js +320 -320
  106. package/lib/Utils/signal.d.ts +32 -32
  107. package/lib/Utils/signal.js +151 -151
  108. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -12
  109. package/lib/Utils/use-multi-file-auth-state.js +80 -80
  110. package/lib/Utils/validate-connection.d.ts +11 -11
  111. package/lib/Utils/validate-connection.js +191 -222
  112. package/lib/WABinary/constants.d.ts +27 -27
  113. package/lib/WABinary/constants.js +40 -40
  114. package/lib/WABinary/decode.d.ts +7 -7
  115. package/lib/WABinary/decode.js +252 -252
  116. package/lib/WABinary/encode.d.ts +3 -3
  117. package/lib/WABinary/encode.js +228 -228
  118. package/lib/WABinary/generic-utils.d.ts +15 -15
  119. package/lib/WABinary/generic-utils.js +110 -110
  120. package/lib/WABinary/index.d.ts +5 -5
  121. package/lib/WABinary/index.js +21 -21
  122. package/lib/WABinary/jid-utils.d.ts +29 -29
  123. package/lib/WABinary/jid-utils.js +59 -59
  124. package/lib/WABinary/types.d.ts +18 -18
  125. package/lib/WABinary/types.js +2 -2
  126. package/lib/index.d.ts +10 -10
  127. package/lib/index.js +29 -29
  128. package/package.json +1 -1
  129. package/CHANGELOG.md +0 -4
@@ -1,367 +1,367 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.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.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;
7
- const boom_1 = require("@hapi/boom");
8
- const axios_1 = __importDefault(require("axios"));
9
- const crypto_1 = require("crypto");
10
- const os_1 = require("os");
11
- const WAProto_1 = require("../../WAProto");
12
- const baileys_version_json_1 = require("../Defaults/baileys-version.json");
13
- const Types_1 = require("../Types");
14
- const WABinary_1 = require("../WABinary");
15
- const PLATFORM_MAP = {
16
- 'aix': 'AIX',
17
- 'darwin': 'Mac OS',
18
- 'win32': 'Windows',
19
- 'android': 'Android'
20
- };
21
- exports.Browsers = {
22
- ubuntu: browser => ['Firefox (linux)', browser, '119.0'],
23
- macOS: browser => ['Firefox (linux)', browser, '119.0'],
24
- baileys: browser => ['Firefox (linux)', browser, '119.0'],
25
- windows: browser => ['Windows', browser, '10.0.22621'],
26
- /** The appropriate browser based on your OS & release */
27
- appropriate: browser => [PLATFORM_MAP[(0, os_1.platform)()] || 'Firefox (linux)', browser, (0, os_1.release)()]
28
- };
29
- exports.BufferJSON = {
30
- replacer: (k, value) => {
31
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
32
- return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
33
- }
34
- return value;
35
- },
36
- reviver: (_, value) => {
37
- if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
38
- const val = value.data || value.value;
39
- return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
40
- }
41
- return value;
42
- }
43
- };
44
- const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
45
- exports.getKeyAuthor = getKeyAuthor;
46
- const writeRandomPadMax16 = (msg) => {
47
- const pad = (0, crypto_1.randomBytes)(1);
48
- pad[0] &= 0xf;
49
- if (!pad[0]) {
50
- pad[0] = 0xf;
51
- }
52
- return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
53
- };
54
- exports.writeRandomPadMax16 = writeRandomPadMax16;
55
- const unpadRandomMax16 = (e) => {
56
- const t = new Uint8Array(e);
57
- if (0 === t.length) {
58
- throw new Error('unpadPkcs7 given empty bytes');
59
- }
60
- var r = t[t.length - 1];
61
- if (r > t.length) {
62
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
63
- }
64
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
65
- };
66
- exports.unpadRandomMax16 = unpadRandomMax16;
67
- const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
68
- exports.encodeWAMessage = encodeWAMessage;
69
- const generateRegistrationId = () => {
70
- return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
71
- };
72
- exports.generateRegistrationId = generateRegistrationId;
73
- const encodeBigEndian = (e, t = 4) => {
74
- let r = e;
75
- const a = new Uint8Array(t);
76
- for (let i = t - 1; i >= 0; i--) {
77
- a[i] = 255 & r;
78
- r >>>= 8;
79
- }
80
- return a;
81
- };
82
- exports.encodeBigEndian = encodeBigEndian;
83
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
84
- exports.toNumber = toNumber;
85
- /** unix timestamp of a date in seconds */
86
- const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
87
- exports.unixTimestampSeconds = unixTimestampSeconds;
88
- const debouncedTimeout = (intervalMs = 1000, task) => {
89
- let timeout;
90
- return {
91
- start: (newIntervalMs, newTask) => {
92
- task = newTask || task;
93
- intervalMs = newIntervalMs || intervalMs;
94
- timeout && clearTimeout(timeout);
95
- timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
96
- },
97
- cancel: () => {
98
- timeout && clearTimeout(timeout);
99
- timeout = undefined;
100
- },
101
- setTask: (newTask) => task = newTask,
102
- setInterval: (newInterval) => intervalMs = newInterval
103
- };
104
- };
105
- exports.debouncedTimeout = debouncedTimeout;
106
- const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
107
- exports.delay = delay;
108
- const delayCancellable = (ms) => {
109
- const stack = new Error().stack;
110
- let timeout;
111
- let reject;
112
- const delay = new Promise((resolve, _reject) => {
113
- timeout = setTimeout(resolve, ms);
114
- reject = _reject;
115
- });
116
- const cancel = () => {
117
- clearTimeout(timeout);
118
- reject(new boom_1.Boom('Cancelled', {
119
- statusCode: 500,
120
- data: {
121
- stack
122
- }
123
- }));
124
- };
125
- return { delay, cancel };
126
- };
127
- exports.delayCancellable = delayCancellable;
128
- async function promiseTimeout(ms, promise) {
129
- if (!ms) {
130
- return new Promise(promise);
131
- }
132
- const stack = new Error().stack;
133
- // Create a promise that rejects in <ms> milliseconds
134
- const { delay, cancel } = (0, exports.delayCancellable)(ms);
135
- const p = new Promise((resolve, reject) => {
136
- delay
137
- .then(() => reject(new boom_1.Boom('Timed Out', {
138
- statusCode: Types_1.DisconnectReason.timedOut,
139
- data: {
140
- stack
141
- }
142
- })))
143
- .catch(err => reject(err));
144
- promise(resolve, reject);
145
- })
146
- .finally(cancel);
147
- return p;
148
- }
149
- exports.promiseTimeout = promiseTimeout;
150
- // generate a random ID to attach to a message
151
- const generateMessageID = () => 'BAE5' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
152
- exports.generateMessageID = generateMessageID;
153
- function bindWaitForEvent(ev, event) {
154
- return async (check, timeoutMs) => {
155
- let listener;
156
- let closeListener;
157
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
158
- closeListener = ({ connection, lastDisconnect }) => {
159
- if (connection === 'close') {
160
- reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
161
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
162
- }
163
- };
164
- ev.on('connection.update', closeListener);
165
- listener = (update) => {
166
- if (check(update)) {
167
- resolve();
168
- }
169
- };
170
- ev.on(event, listener);
171
- })
172
- .finally(() => {
173
- ev.off(event, listener);
174
- ev.off('connection.update', closeListener);
175
- }));
176
- };
177
- }
178
- exports.bindWaitForEvent = bindWaitForEvent;
179
- const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
180
- exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
181
- const printQRIfNecessaryListener = (ev, logger) => {
182
- ev.on('connection.update', async ({ qr }) => {
183
- if (qr) {
184
- const QR = await import('qrcode-terminal')
185
- .then(m => m.default || m)
186
- .catch(() => {
187
- logger.error('QR code terminal not added as dependency');
188
- });
189
- QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
190
- }
191
- });
192
- };
193
- exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
194
- /**
195
- * utility that fetches latest baileys version from the master branch.
196
- * Use to ensure your WA connection is always on the latest version
197
- */
198
- const fetchLatestBaileysVersion = async (options = {}) => {
199
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
200
- try {
201
- const result = await axios_1.default.get(URL, {
202
- ...options,
203
- responseType: 'json'
204
- });
205
- return {
206
- version: result.data.version,
207
- isLatest: true
208
- };
209
- }
210
- catch (error) {
211
- return {
212
- version: baileys_version_json_1.version,
213
- isLatest: false,
214
- error
215
- };
216
- }
217
- };
218
- exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
219
- /**
220
- * A utility that fetches the latest web version of whatsapp.
221
- * Use to ensure your WA connection is always on the latest version
222
- */
223
- const fetchLatestWaWebVersion = async (options) => {
224
- try {
225
- const result = await axios_1.default.get('https://web.whatsapp.com/check-update?version=1&platform=web', {
226
- ...options,
227
- responseType: 'json'
228
- });
229
- const version = result.data.currentVersion.split('.');
230
- return {
231
- version: [+version[0], +version[1], +version[2]],
232
- isLatest: true
233
- };
234
- }
235
- catch (error) {
236
- return {
237
- version: baileys_version_json_1.version,
238
- isLatest: false,
239
- error
240
- };
241
- }
242
- };
243
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
244
- /** unique message tag prefix for MD clients */
245
- const generateMdTagPrefix = () => {
246
- const bytes = (0, crypto_1.randomBytes)(4);
247
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
248
- };
249
- exports.generateMdTagPrefix = generateMdTagPrefix;
250
- const STATUS_MAP = {
251
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
252
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
253
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
254
- };
255
- /**
256
- * Given a type of receipt, returns what the new status of the message should be
257
- * @param type type from receipt
258
- */
259
- const getStatusFromReceiptType = (type) => {
260
- const status = STATUS_MAP[type];
261
- if (typeof type === 'undefined') {
262
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
263
- }
264
- return status;
265
- };
266
- exports.getStatusFromReceiptType = getStatusFromReceiptType;
267
- const CODE_MAP = {
268
- conflict: Types_1.DisconnectReason.connectionReplaced
269
- };
270
- /**
271
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
272
- * @param reason the string reason given, eg. "conflict"
273
- */
274
- const getErrorCodeFromStreamError = (node) => {
275
- const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
276
- let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
277
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
278
- if (statusCode === Types_1.DisconnectReason.restartRequired) {
279
- reason = 'restart required';
280
- }
281
- return {
282
- reason,
283
- statusCode
284
- };
285
- };
286
- exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
287
- const getCallStatusFromNode = ({ tag, attrs }) => {
288
- let status;
289
- switch (tag) {
290
- case 'offer':
291
- case 'offer_notice':
292
- status = 'offer';
293
- break;
294
- case 'terminate':
295
- if (attrs.reason === 'timeout') {
296
- status = 'timeout';
297
- }
298
- else {
299
- status = 'reject';
300
- }
301
- break;
302
- case 'reject':
303
- status = 'reject';
304
- break;
305
- case 'accept':
306
- status = 'accept';
307
- break;
308
- default:
309
- status = 'ringing';
310
- break;
311
- }
312
- return status;
313
- };
314
- exports.getCallStatusFromNode = getCallStatusFromNode;
315
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
316
- const getCodeFromWSError = (error) => {
317
- var _a, _b, _c;
318
- let statusCode = 500;
319
- if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
320
- const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
321
- if (!Number.isNaN(code) && code >= 400) {
322
- statusCode = code;
323
- }
324
- }
325
- else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
326
- || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
327
- statusCode = 408;
328
- }
329
- return statusCode;
330
- };
331
- exports.getCodeFromWSError = getCodeFromWSError;
332
- /**
333
- * Is the given platform WA business
334
- * @param platform AuthenticationCreds.platform
335
- */
336
- const isWABusinessPlatform = (platform) => {
337
- return platform === 'smbi' || platform === 'smba';
338
- };
339
- exports.isWABusinessPlatform = isWABusinessPlatform;
340
- function trimUndefined(obj) {
341
- for (const key in obj) {
342
- if (typeof obj[key] === 'undefined') {
343
- delete obj[key];
344
- }
345
- }
346
- return obj;
347
- }
348
- exports.trimUndefined = trimUndefined;
349
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
350
- function bytesToCrockford(buffer) {
351
- let value = 0;
352
- let bitCount = 0;
353
- const crockford = [];
354
- for (let i = 0; i < buffer.length; i++) {
355
- value = (value << 8) | (buffer[i] & 0xff);
356
- bitCount += 8;
357
- while (bitCount >= 5) {
358
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
359
- bitCount -= 5;
360
- }
361
- }
362
- if (bitCount > 0) {
363
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
364
- }
365
- return crockford.join('');
366
- }
367
- exports.bytesToCrockford = bytesToCrockford;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.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.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;
7
+ const boom_1 = require("@hapi/boom");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const crypto_1 = require("crypto");
10
+ const os_1 = require("os");
11
+ const WAProto_1 = require("../../WAProto");
12
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
13
+ const Types_1 = require("../Types");
14
+ const WABinary_1 = require("../WABinary");
15
+ const PLATFORM_MAP = {
16
+ 'aix': 'AIX',
17
+ 'darwin': 'Mac OS',
18
+ 'win32': 'Windows',
19
+ 'android': 'Android'
20
+ };
21
+ exports.Browsers = {
22
+ ubuntu: browser => ['Ubuntu', browser, '20.0.04'],
23
+ macOS: browser => ['Mac OS', browser, '10.15.7'],
24
+ baileys: browser => ['Windows', browser, '10.0.22621'],
25
+ windows: browser => ['Windows', browser, '10.0.22621'],
26
+ /** The appropriate browser based on your OS & release */
27
+ appropriate: browser => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
28
+ };
29
+ exports.BufferJSON = {
30
+ replacer: (k, value) => {
31
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
32
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
33
+ }
34
+ return value;
35
+ },
36
+ reviver: (_, value) => {
37
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
38
+ const val = value.data || value.value;
39
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
40
+ }
41
+ return value;
42
+ }
43
+ };
44
+ const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
45
+ exports.getKeyAuthor = getKeyAuthor;
46
+ const writeRandomPadMax16 = (msg) => {
47
+ const pad = (0, crypto_1.randomBytes)(1);
48
+ pad[0] &= 0xf;
49
+ if (!pad[0]) {
50
+ pad[0] = 0xf;
51
+ }
52
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
53
+ };
54
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
55
+ const unpadRandomMax16 = (e) => {
56
+ const t = new Uint8Array(e);
57
+ if (0 === t.length) {
58
+ throw new Error('unpadPkcs7 given empty bytes');
59
+ }
60
+ var r = t[t.length - 1];
61
+ if (r > t.length) {
62
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
63
+ }
64
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
65
+ };
66
+ exports.unpadRandomMax16 = unpadRandomMax16;
67
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
68
+ exports.encodeWAMessage = encodeWAMessage;
69
+ const generateRegistrationId = () => {
70
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
71
+ };
72
+ exports.generateRegistrationId = generateRegistrationId;
73
+ const encodeBigEndian = (e, t = 4) => {
74
+ let r = e;
75
+ const a = new Uint8Array(t);
76
+ for (let i = t - 1; i >= 0; i--) {
77
+ a[i] = 255 & r;
78
+ r >>>= 8;
79
+ }
80
+ return a;
81
+ };
82
+ exports.encodeBigEndian = encodeBigEndian;
83
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
84
+ exports.toNumber = toNumber;
85
+ /** unix timestamp of a date in seconds */
86
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
87
+ exports.unixTimestampSeconds = unixTimestampSeconds;
88
+ const debouncedTimeout = (intervalMs = 1000, task) => {
89
+ let timeout;
90
+ return {
91
+ start: (newIntervalMs, newTask) => {
92
+ task = newTask || task;
93
+ intervalMs = newIntervalMs || intervalMs;
94
+ timeout && clearTimeout(timeout);
95
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
96
+ },
97
+ cancel: () => {
98
+ timeout && clearTimeout(timeout);
99
+ timeout = undefined;
100
+ },
101
+ setTask: (newTask) => task = newTask,
102
+ setInterval: (newInterval) => intervalMs = newInterval
103
+ };
104
+ };
105
+ exports.debouncedTimeout = debouncedTimeout;
106
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
107
+ exports.delay = delay;
108
+ const delayCancellable = (ms) => {
109
+ const stack = new Error().stack;
110
+ let timeout;
111
+ let reject;
112
+ const delay = new Promise((resolve, _reject) => {
113
+ timeout = setTimeout(resolve, ms);
114
+ reject = _reject;
115
+ });
116
+ const cancel = () => {
117
+ clearTimeout(timeout);
118
+ reject(new boom_1.Boom('Cancelled', {
119
+ statusCode: 500,
120
+ data: {
121
+ stack
122
+ }
123
+ }));
124
+ };
125
+ return { delay, cancel };
126
+ };
127
+ exports.delayCancellable = delayCancellable;
128
+ async function promiseTimeout(ms, promise) {
129
+ if (!ms) {
130
+ return new Promise(promise);
131
+ }
132
+ const stack = new Error().stack;
133
+ // Create a promise that rejects in <ms> milliseconds
134
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
135
+ const p = new Promise((resolve, reject) => {
136
+ delay
137
+ .then(() => reject(new boom_1.Boom('Timed Out', {
138
+ statusCode: Types_1.DisconnectReason.timedOut,
139
+ data: {
140
+ stack
141
+ }
142
+ })))
143
+ .catch(err => reject(err));
144
+ promise(resolve, reject);
145
+ })
146
+ .finally(cancel);
147
+ return p;
148
+ }
149
+ exports.promiseTimeout = promiseTimeout;
150
+ // generate a random ID to attach to a message
151
+ const generateMessageID = () => 'BAE5' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
152
+ exports.generateMessageID = generateMessageID;
153
+ function bindWaitForEvent(ev, event) {
154
+ return async (check, timeoutMs) => {
155
+ let listener;
156
+ let closeListener;
157
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
158
+ closeListener = ({ connection, lastDisconnect }) => {
159
+ if (connection === 'close') {
160
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
161
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
162
+ }
163
+ };
164
+ ev.on('connection.update', closeListener);
165
+ listener = (update) => {
166
+ if (check(update)) {
167
+ resolve();
168
+ }
169
+ };
170
+ ev.on(event, listener);
171
+ })
172
+ .finally(() => {
173
+ ev.off(event, listener);
174
+ ev.off('connection.update', closeListener);
175
+ }));
176
+ };
177
+ }
178
+ exports.bindWaitForEvent = bindWaitForEvent;
179
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
180
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
181
+ const printQRIfNecessaryListener = (ev, logger) => {
182
+ ev.on('connection.update', async ({ qr }) => {
183
+ if (qr) {
184
+ const QR = await import('qrcode-terminal')
185
+ .then(m => m.default || m)
186
+ .catch(() => {
187
+ logger.error('QR code terminal not added as dependency');
188
+ });
189
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
190
+ }
191
+ });
192
+ };
193
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
194
+ /**
195
+ * utility that fetches latest baileys version from the master branch.
196
+ * Use to ensure your WA connection is always on the latest version
197
+ */
198
+ const fetchLatestBaileysVersion = async (options = {}) => {
199
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
200
+ try {
201
+ const result = await axios_1.default.get(URL, {
202
+ ...options,
203
+ responseType: 'json'
204
+ });
205
+ return {
206
+ version: result.data.version,
207
+ isLatest: true
208
+ };
209
+ }
210
+ catch (error) {
211
+ return {
212
+ version: baileys_version_json_1.version,
213
+ isLatest: false,
214
+ error
215
+ };
216
+ }
217
+ };
218
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
219
+ /**
220
+ * A utility that fetches the latest web version of whatsapp.
221
+ * Use to ensure your WA connection is always on the latest version
222
+ */
223
+ const fetchLatestWaWebVersion = async (options) => {
224
+ try {
225
+ const result = await axios_1.default.get('https://web.whatsapp.com/check-update?version=1&platform=web', {
226
+ ...options,
227
+ responseType: 'json'
228
+ });
229
+ const version = result.data.currentVersion.split('.');
230
+ return {
231
+ version: [+version[0], +version[1], +version[2]],
232
+ isLatest: true
233
+ };
234
+ }
235
+ catch (error) {
236
+ return {
237
+ version: baileys_version_json_1.version,
238
+ isLatest: false,
239
+ error
240
+ };
241
+ }
242
+ };
243
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
244
+ /** unique message tag prefix for MD clients */
245
+ const generateMdTagPrefix = () => {
246
+ const bytes = (0, crypto_1.randomBytes)(4);
247
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
248
+ };
249
+ exports.generateMdTagPrefix = generateMdTagPrefix;
250
+ const STATUS_MAP = {
251
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
252
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
253
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
254
+ };
255
+ /**
256
+ * Given a type of receipt, returns what the new status of the message should be
257
+ * @param type type from receipt
258
+ */
259
+ const getStatusFromReceiptType = (type) => {
260
+ const status = STATUS_MAP[type];
261
+ if (typeof type === 'undefined') {
262
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
263
+ }
264
+ return status;
265
+ };
266
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
267
+ const CODE_MAP = {
268
+ conflict: Types_1.DisconnectReason.connectionReplaced
269
+ };
270
+ /**
271
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
272
+ * @param reason the string reason given, eg. "conflict"
273
+ */
274
+ const getErrorCodeFromStreamError = (node) => {
275
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
276
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
277
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
278
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
279
+ reason = 'restart required';
280
+ }
281
+ return {
282
+ reason,
283
+ statusCode
284
+ };
285
+ };
286
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
287
+ const getCallStatusFromNode = ({ tag, attrs }) => {
288
+ let status;
289
+ switch (tag) {
290
+ case 'offer':
291
+ case 'offer_notice':
292
+ status = 'offer';
293
+ break;
294
+ case 'terminate':
295
+ if (attrs.reason === 'timeout') {
296
+ status = 'timeout';
297
+ }
298
+ else {
299
+ status = 'reject';
300
+ }
301
+ break;
302
+ case 'reject':
303
+ status = 'reject';
304
+ break;
305
+ case 'accept':
306
+ status = 'accept';
307
+ break;
308
+ default:
309
+ status = 'ringing';
310
+ break;
311
+ }
312
+ return status;
313
+ };
314
+ exports.getCallStatusFromNode = getCallStatusFromNode;
315
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
316
+ const getCodeFromWSError = (error) => {
317
+ var _a, _b, _c;
318
+ let statusCode = 500;
319
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
320
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
321
+ if (!Number.isNaN(code) && code >= 400) {
322
+ statusCode = code;
323
+ }
324
+ }
325
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
326
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
327
+ statusCode = 408;
328
+ }
329
+ return statusCode;
330
+ };
331
+ exports.getCodeFromWSError = getCodeFromWSError;
332
+ /**
333
+ * Is the given platform WA business
334
+ * @param platform AuthenticationCreds.platform
335
+ */
336
+ const isWABusinessPlatform = (platform) => {
337
+ return platform === 'smbi' || platform === 'smba';
338
+ };
339
+ exports.isWABusinessPlatform = isWABusinessPlatform;
340
+ function trimUndefined(obj) {
341
+ for (const key in obj) {
342
+ if (typeof obj[key] === 'undefined') {
343
+ delete obj[key];
344
+ }
345
+ }
346
+ return obj;
347
+ }
348
+ exports.trimUndefined = trimUndefined;
349
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
350
+ function bytesToCrockford(buffer) {
351
+ let value = 0;
352
+ let bitCount = 0;
353
+ const crockford = [];
354
+ for (let i = 0; i < buffer.length; i++) {
355
+ value = (value << 8) | (buffer[i] & 0xff);
356
+ bitCount += 8;
357
+ while (bitCount >= 5) {
358
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
359
+ bitCount -= 5;
360
+ }
361
+ }
362
+ if (bitCount > 0) {
363
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
364
+ }
365
+ return crockford.join('');
366
+ }
367
+ exports.bytesToCrockford = bytesToCrockford;