@queenanya/baileys 6.5.8 → 6.6.0

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