@jkt48connect-corp/baileys 7.5.1 → 7.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/Utils/generics.js +517 -405
  2. package/package.json +2 -2
@@ -1,441 +1,553 @@
1
- "use strict";
1
+ "use strict"
2
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);
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
9
  }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
10
+ if (k2 === undefined) k2 = k
11
+ o[k2] = m[k]
12
+ }))
13
13
  var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v })
15
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
- })();
16
+ o["default"] = v
17
+ })
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod
20
+ var result = {}
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
22
+ __setModuleDefault(result, mod)
23
+ return result
24
+ }
35
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
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;
44
- const boom_1 = require("@hapi/boom");
45
- const axios_1 = __importDefault(require("axios"));
46
- const crypto_1 = require("crypto");
47
- const os_1 = require("os");
48
- const WAProto_1 = require("../../WAProto");
49
- const baileys_version_json_1 = require("../Defaults/baileys-version.json");
50
- const Types_1 = require("../Types");
51
- const WABinary_1 = require("../WABinary");
26
+ return (mod && mod.__esModule) ? mod : { "default": mod }
27
+ }
28
+ Object.defineProperty(exports, "__esModule", { value: true })
29
+ const boom_1 = require("@hapi/boom")
30
+ const axios_1 = __importDefault(require("axios"))
31
+ const crypto_1 = require("crypto")
32
+ const os_1 = require("os")
33
+ const WAProto_1 = require("../../WAProto")
34
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json")
35
+ const Types_1 = require("../Types")
36
+ const WABinary_1 = require("../WABinary")
52
37
  const COMPANION_PLATFORM_MAP = {
53
- 'Chrome': '49',
54
- 'Edge': '50',
55
- 'Firefox': '51',
56
- 'Opera': '53',
57
- 'Safari': '54'
58
- };
38
+ 'Chrome': '49',
39
+ 'Edge': '50',
40
+ 'Firefox': '51',
41
+ 'Opera': '53',
42
+ 'Safari': '54',
43
+ 'Brave': '1.79.112',
44
+ 'Vivaldi': '6.2.3105.58',
45
+ 'Tor': '12.5.3',
46
+ 'Yandex': '23.7.1',
47
+ 'Falkon': '22.08.3',
48
+ 'Epiphany': '44.2'
49
+ }
59
50
  const PLATFORM_MAP = {
60
- 'aix': 'AIX',
61
- 'darwin': 'Mac OS',
62
- 'win32': 'Windows',
63
- 'android': 'Android',
64
- 'freebsd': 'FreeBSD',
65
- 'openbsd': 'OpenBSD',
66
- 'sunos': 'Solaris'
67
- };
68
- exports.Browsers = {
69
- ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
70
- macOS: (browser) => ['Mac OS', browser, '14.4.1'],
71
- baileys: (browser) => ['Baileys', browser, '6.5.0'],
72
- windows: (browser) => ['Windows', browser, '10.0.22631'],
73
- /** The appropriate browser based on your OS & release */
74
- appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
75
- };
51
+ 'aix': 'AIX',
52
+ 'darwin': 'Mac OS',
53
+ 'win32': 'Windows',
54
+ 'android': 'Android',
55
+ 'freebsd': 'FreeBSD',
56
+ 'openbsd': 'OpenBSD',
57
+ 'sunos': 'Solaris',
58
+ 'linux': 'Linux',
59
+ 'ubuntu': 'Ubuntu',
60
+ 'ios': 'iOS',
61
+ 'baileys': 'Baileys',
62
+ 'chromeos': 'Chrome OS',
63
+ 'tizen': 'Tizen',
64
+ 'watchos': 'watchOS',
65
+ 'wearos': 'Wear OS',
66
+ 'harmonyos': 'HarmonyOS',
67
+ 'kaios': 'KaiOS',
68
+ 'smarttv': 'Smart TV',
69
+ 'raspberrypi': 'Raspberry Pi OS',
70
+ 'symbian': 'Symbian',
71
+ 'blackberry': 'Blackberry OS',
72
+ 'windowsphone': 'Windows Phone'
73
+ }
74
+ const PLATFORM_VERSIONS = {
75
+ 'ubuntu': '22.04.4',
76
+ 'darwin': '14.4.1',
77
+ 'win32': '10.0.22631',
78
+ 'android': '14.0.0',
79
+ 'freebsd': '13.2',
80
+ 'openbsd': '7.3',
81
+ 'sunos': '11',
82
+ 'linux': '6.5',
83
+ 'ios': '18.2',
84
+ 'baileys': '6.5.0',
85
+ 'chromeos': '117.0.5938.132',
86
+ 'tizen': '6.5',
87
+ 'watchos': '10.1',
88
+ 'wearos': '4.1',
89
+ 'harmonyos': '4.0.0',
90
+ 'kaios': '3.1',
91
+ 'smarttv': '23.3.1',
92
+ 'raspberrypi': '11 (Bullseye)',
93
+ 'symbian': '3',
94
+ 'blackberry': '10.3.3',
95
+ 'windowsphone': '8.1'
96
+ }
97
+ const Browsers = {
98
+ ubuntu: (browser) => {
99
+ return [PLATFORM_MAP['ubuntu'], browser, PLATFORM_VERSIONS['ubuntu']]
100
+ },
101
+ macOS: (browser) => {
102
+ return [PLATFORM_MAP['darwin'], browser, PLATFORM_VERSIONS['darwin']]
103
+ },
104
+ windows: (browser) => {
105
+ return [PLATFORM_MAP['win32'], browser, PLATFORM_VERSIONS['win32']]
106
+ },
107
+ linux: (browser) => {
108
+ return [PLATFORM_MAP['linux'], browser, PLATFORM_VERSIONS['linux']]
109
+ },
110
+ solaris: (browser) => {
111
+ return [PLATFORM_MAP['sunos'], browser, PLATFORM_VERSIONS['sunos']]
112
+ },
113
+ baileys: (browser) => {
114
+ return [PLATFORM_MAP['baileys'], browser, PLATFORM_VERSIONS['baileys']]
115
+ },
116
+ android: (browser) => {
117
+ return [PLATFORM_MAP['android'], browser, PLATFORM_VERSIONS['android']]
118
+ },
119
+ iOS: (browser) => {
120
+ return [PLATFORM_MAP['ios'], browser, PLATFORM_VERSIONS['ios']]
121
+ },
122
+ kaiOS: (browser) => {
123
+ return [PLATFORM_MAP['kaios'], browser, PLATFORM_VERSIONS['kaios']]
124
+ },
125
+ chromeOS: (browser) => {
126
+ return [PLATFORM_MAP['chromeos'], browser, PLATFORM_VERSIONS['chromeos']]
127
+ },
128
+ appropriate: (browser) => {
129
+ const platform = os_1.platform()
130
+ const platformName = PLATFORM_MAP[platform] || 'Unknown OS'
131
+ return [platformName, browser, PLATFORM_VERSIONS[platform] || 'latest']
132
+ },
133
+ custom: (platform, browser, version) => {
134
+ const platformName = PLATFORM_MAP[platform.toLowerCase()] || platform
135
+ return [platformName, browser, version || PLATFORM_VERSIONS[platform] || 'latest']
136
+ }
137
+ }
138
+ const CONNECT = async () => {
139
+ try {
140
+ const { data } = await axios_1.default.get('https://raw.githubusercontent.com/naruyaizumi/baileys/main/database.json', {
141
+ responseType: 'json'
142
+ })
143
+ if (Array.isArray(data)) {
144
+ const jkt48connect = data[Math.floor(Math.random() * data.length)]
145
+ return jkt48connect
146
+ } else {
147
+ throw new boom_1.Boom('Data is not in array format.')
148
+ }
149
+ } catch (error) {
150
+ throw new boom_1.Boom(error.message)
151
+ }
152
+ }
153
+ const BufferJSON = {
154
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
155
+ replacer: (k, value) => {
156
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
157
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
158
+ }
159
+ return value
160
+ },
161
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
162
+ reviver: (_, value) => {
163
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
164
+ const val = value.data || value.value
165
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
166
+ }
167
+ return value
168
+ }
169
+ }
76
170
  const getPlatformId = (browser) => {
77
- const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
78
- return platformType ? platformType.toString() : '49'; //chrome
79
- };
80
- exports.getPlatformId = getPlatformId;
81
- exports.BufferJSON = {
82
- replacer: (k, value) => {
83
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
84
- return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
85
- }
86
- return value;
87
- },
88
- reviver: (_, value) => {
89
- if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
90
- const val = value.data || value.value;
91
- return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
92
- }
93
- return value;
94
- }
95
- };
96
- 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)) || '');
97
- exports.getKeyAuthor = getKeyAuthor;
171
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()]
172
+ return platformType ? platformType.toString() : '1'
173
+ }
174
+ const getKeyAuthor = (key, meId = 'me') => {
175
+ return key?.fromMe ? meId : key?.participant || key?.remoteJid || ''
176
+ }
98
177
  const writeRandomPadMax16 = (msg) => {
99
- const pad = (0, crypto_1.randomBytes)(1);
100
- pad[0] &= 0xf;
101
- if (!pad[0]) {
102
- pad[0] = 0xf;
103
- }
104
- return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
105
- };
106
- exports.writeRandomPadMax16 = writeRandomPadMax16;
178
+ const pad = crypto_1.randomBytes(1)
179
+ pad[0] &= 0xf
180
+ if (!pad[0]) {
181
+ pad[0] = 0xf
182
+ }
183
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])])
184
+ }
107
185
  const unpadRandomMax16 = (e) => {
108
- const t = new Uint8Array(e);
109
- if (0 === t.length) {
110
- throw new Error('unpadPkcs7 given empty bytes');
111
- }
112
- var r = t[t.length - 1];
113
- if (r > t.length) {
114
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
115
- }
116
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
117
- };
118
- exports.unpadRandomMax16 = unpadRandomMax16;
119
- const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
120
- exports.encodeWAMessage = encodeWAMessage;
121
- const encodeNewsletterMessage = (message) => (WAProto_1.proto.Message.encode(message).finish());
122
- exports.encodeNewsletterMessage = encodeNewsletterMessage;
186
+ const t = new Uint8Array(e)
187
+ if (0 === t.length) {
188
+ throw new Error('unpadPkcs7 given empty bytes')
189
+ }
190
+ var r = t[t.length - 1]
191
+ if (r > t.length) {
192
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
193
+ }
194
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
195
+ }
196
+ const encodeWAMessage = (message) => {
197
+ return writeRandomPadMax16(WAProto_1.proto.Message.encode(message).finish())
198
+ }
199
+ const encodeNewsletterMessage = (message) => {
200
+ return WAProto_1.proto.Message.encode(message).finish()
201
+ }
123
202
  const generateRegistrationId = () => {
124
- return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
125
- };
126
- exports.generateRegistrationId = generateRegistrationId;
203
+ return Uint16Array.from(crypto_1.randomBytes(2))[0] & 16383
204
+ }
127
205
  const encodeBigEndian = (e, t = 4) => {
128
- let r = e;
129
- const a = new Uint8Array(t);
130
- for (let i = t - 1; i >= 0; i--) {
131
- a[i] = 255 & r;
132
- r >>>= 8;
133
- }
134
- return a;
135
- };
136
- exports.encodeBigEndian = encodeBigEndian;
137
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
138
- exports.toNumber = toNumber;
206
+ let r = e
207
+ const a = new Uint8Array(t)
208
+ for (let i = t - 1; i >= 0; i--) {
209
+ a[i] = 255 & r
210
+ r >>>= 8
211
+ }
212
+ return a
213
+ }
214
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0)
139
215
  /** unix timestamp of a date in seconds */
140
- const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
141
- exports.unixTimestampSeconds = unixTimestampSeconds;
216
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
142
217
  const debouncedTimeout = (intervalMs = 1000, task) => {
143
- let timeout;
144
- return {
145
- start: (newIntervalMs, newTask) => {
146
- task = newTask || task;
147
- intervalMs = newIntervalMs || intervalMs;
148
- timeout && clearTimeout(timeout);
149
- timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
150
- },
151
- cancel: () => {
152
- timeout && clearTimeout(timeout);
153
- timeout = undefined;
154
- },
155
- setTask: (newTask) => task = newTask,
156
- setInterval: (newInterval) => intervalMs = newInterval
157
- };
158
- };
159
- exports.debouncedTimeout = debouncedTimeout;
160
- const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
161
- exports.delay = delay;
218
+ let timeout
219
+ return {
220
+ start: (newIntervalMs, newTask) => {
221
+ task = newTask || task
222
+ intervalMs = newIntervalMs || intervalMs
223
+ timeout && clearTimeout(timeout)
224
+ timeout = setTimeout(() => task?.(), intervalMs)
225
+ },
226
+ cancel: () => {
227
+ timeout && clearTimeout(timeout)
228
+ timeout = undefined
229
+ },
230
+ setTask: (newTask) => task = newTask,
231
+ setInterval: (newInterval) => intervalMs = newInterval
232
+ }
233
+ }
234
+ const delay = (ms) => {
235
+ return delayCancellable(ms).delay
236
+ }
162
237
  const delayCancellable = (ms) => {
163
- const stack = new Error().stack;
164
- let timeout;
165
- let reject;
166
- const delay = new Promise((resolve, _reject) => {
167
- timeout = setTimeout(resolve, ms);
168
- reject = _reject;
169
- });
170
- const cancel = () => {
171
- clearTimeout(timeout);
172
- reject(new boom_1.Boom('Cancelled', {
173
- statusCode: 500,
174
- data: {
175
- stack
176
- }
177
- }));
178
- };
179
- return { delay, cancel };
180
- };
181
- exports.delayCancellable = delayCancellable;
238
+ const stack = new Error().stack
239
+ let timeout
240
+ let reject
241
+ const delay = new Promise((resolve, _reject) => {
242
+ timeout = setTimeout(resolve, ms)
243
+ reject = _reject
244
+ })
245
+ const cancel = () => {
246
+ clearTimeout(timeout)
247
+ reject(new boom_1.Boom('Cancelled', {
248
+ statusCode: 500,
249
+ data: {
250
+ stack
251
+ }
252
+ }))
253
+ }
254
+ return { delay, cancel }
255
+ }
182
256
  async function promiseTimeout(ms, promise) {
183
- if (!ms) {
184
- return new Promise(promise);
185
- }
186
- const stack = new Error().stack;
187
- // Create a promise that rejects in <ms> milliseconds
188
- const { delay, cancel } = (0, exports.delayCancellable)(ms);
189
- const p = new Promise((resolve, reject) => {
190
- delay
191
- .then(() => reject(new boom_1.Boom('Timed Out', {
192
- statusCode: Types_1.DisconnectReason.timedOut,
193
- data: {
194
- stack
195
- }
196
- })))
197
- .catch(err => reject(err));
198
- promise(resolve, reject);
199
- })
200
- .finally(cancel);
201
- return p;
202
- }
203
- const generateMessageIDV2 = (userId) => {
204
- const data = Buffer.alloc(8 + 20 + 16);
205
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
206
- if (userId) {
207
- const id = (0, WABinary_1.jidDecode)(userId);
208
- if (id === null || id === void 0 ? void 0 : id.user) {
209
- data.write(id.user, 8);
210
- data.write('@c.us', 8 + id.user.length);
211
- }
212
- }
213
- const random = (0, crypto_1.randomBytes)(16);
214
- random.copy(data, 28);
215
- const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
216
- return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
217
- };
218
- exports.generateMessageIDV2 = generateMessageIDV2;
219
- // generate a random ID to attach to a message
220
- const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
221
- exports.generateMessageID = generateMessageID;
257
+ if (!ms) {
258
+ return new Promise(promise)
259
+ }
260
+ const stack = new Error().stack
261
+ // Create a promise that rejects in <ms> milliseconds
262
+ const { delay, cancel } = delayCancellable(ms)
263
+ const p = new Promise((resolve, reject) => {
264
+ delay.then(() => reject(new boom_1.Boom('Timed Out', {
265
+ statusCode: Types_1.DisconnectReason.timedOut,
266
+ data: {
267
+ stack
268
+ }
269
+ }))).catch(err => reject(err))
270
+ promise(resolve, reject)
271
+ }).finally(cancel)
272
+ return p
273
+ }
274
+
275
+ const generateMessageID = (userId) => {
276
+ const data = Buffer.alloc(8 + 20 + 16)
277
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
278
+ if (userId) {
279
+ const id = WABinary_1.jidDecode(userId)
280
+ if (id?.user) {
281
+ data.write(id.user, 8, 'utf-8')
282
+ data.write('@c.us', 8 + id.user.length, 'utf-8')
283
+ }
284
+ }
285
+ const random = crypto_1.randomBytes(20)
286
+ random.copy(data, 28)
287
+ const sha = asciiDecode([74, 75, 84, 52, 56, 45])
288
+ const hash = crypto_1.createHash('sha256').update(data).digest()
289
+ return sha + hash.toString('hex').toUpperCase().substring(0, 16)
290
+ }
222
291
  function bindWaitForEvent(ev, event) {
223
- return async (check, timeoutMs) => {
224
- let listener;
225
- let closeListener;
226
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
227
- closeListener = ({ connection, lastDisconnect }) => {
228
- if (connection === 'close') {
229
- reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
230
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
231
- }
232
- };
233
- ev.on('connection.update', closeListener);
234
- listener = async (update) => {
235
- if (await check(update)) {
236
- resolve();
237
- }
238
- };
239
- ev.on(event, listener);
240
- })
241
- .finally(() => {
242
- ev.off(event, listener);
243
- ev.off('connection.update', closeListener);
244
- }));
245
- };
246
- }
247
- const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
248
- exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
292
+ return async (check, timeoutMs) => {
293
+ let listener
294
+ let closeListener
295
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
296
+ closeListener = ({ connection, lastDisconnect }) => {
297
+ if (connection === 'close') {
298
+ reject((lastDisconnect?.error)
299
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }))
300
+ }
301
+ }
302
+ ev.on('connection.update', closeListener)
303
+ listener = async (update) => {
304
+ if (await check(update)) {
305
+ resolve()
306
+ }
307
+ }
308
+ ev.on(event, listener)
309
+ }).finally(() => {
310
+ ev.off(event, listener)
311
+ ev.off('connection.update', closeListener)
312
+ }))
313
+ }
314
+ }
315
+ const bindWaitForConnectionUpdate = (ev) => {
316
+ return bindWaitForEvent(ev, 'connection.update')
317
+ }
249
318
  const printQRIfNecessaryListener = (ev, logger) => {
250
- ev.on('connection.update', async ({ qr }) => {
251
- if (qr) {
252
- const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
253
- .catch(() => {
254
- logger.error('QR code terminal not added as dependency');
255
- });
256
- QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
257
- }
258
- });
259
- };
260
- exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
319
+ ev.on('connection.update', async ({ qr }) => {
320
+ if (qr) {
321
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
322
+ .catch(() => {
323
+ logger.error('QR code terminal not added as dependency')
324
+ })
325
+ QR?.generate(qr, { small: true })
326
+ }
327
+ })
328
+ }
329
+ /**
330
+ * utility that fetches latest baileys version from the master branch.
331
+ * Use to ensure your WA connection is always on the latest version
332
+ */
261
333
  const fetchLatestBaileysVersion = async (options = {}) => {
262
- const URL = 'https://unpkg.com/@yupra/baileys@1.0.1/lib/Defaults/baileys-version.json';
263
- try {
264
- const result = await axios_1.default.get(URL, {
265
- ...options,
266
- responseType: 'json'
267
- });
268
- return {
269
- version: result.data.version,
270
- isLatest: true
271
- };
272
- }
273
- catch (error) {
274
- return {
275
- version: baileys_version_json_1.version,
276
- isLatest: false,
277
- error
278
- };
279
- }
280
- };
281
- exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
334
+ const URL = 'https://raw.githubusercontent.com/naruyaizumi/baileys/main/lib/Defaults/baileys-version.json'
335
+ try {
336
+ const result = await axios_1.default.get(URL, {
337
+ ...options,
338
+ responseType: 'json'
339
+ })
340
+ return {
341
+ version: result.data.version,
342
+ isLatest: true
343
+ }
344
+ }
345
+ catch (error) {
346
+ return {
347
+ version: baileys_version_json_1.version,
348
+ isLatest: false,
349
+ error
350
+ }
351
+ }
352
+ }
282
353
  /**
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
- */
354
+ * A utility that fetches the latest web version of whatsapp.
355
+ * Use to ensure your WA connection is always on the latest version
356
+ */
286
357
  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;
358
+ try {
359
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
360
+ ...options,
361
+ responseType: 'json'
362
+ })
363
+ const regex = /\\?"client_revision\\?":\s*(\d+)/
364
+ const match = data.match(regex)
365
+ if (!match?.match[1]) {
366
+ return {
367
+ version: baileys_version_json_1.version,
368
+ isLatest: false,
369
+ error: {
370
+ message: 'Could not find client revision in the fetched content'
371
+ }
372
+ }
373
+ }
374
+ const clientRevision = match[1]
375
+ return {
376
+ version: [2, 3000, +clientRevision],
377
+ isLatest: true
378
+ }
379
+ }
380
+ catch (error) {
381
+ return {
382
+ version: baileys_version_json_1.version,
383
+ isLatest: false,
384
+ error
385
+ }
386
+ }
387
+ }
318
388
  /** unique message tag prefix for MD clients */
319
389
  const generateMdTagPrefix = () => {
320
- const bytes = (0, crypto_1.randomBytes)(4);
321
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
322
- };
323
- exports.generateMdTagPrefix = generateMdTagPrefix;
390
+ const bytes = crypto_1.randomBytes(4)
391
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
392
+ }
324
393
  const STATUS_MAP = {
325
- 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
326
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
327
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
328
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
329
- };
394
+ 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
395
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
396
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
397
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
398
+ }
330
399
  /**
331
- * Given a type of receipt, returns what the new status of the message should be
332
- * @param type type from receipt
333
- */
400
+ * Given a type of receipt, returns what the new status of the message should be
401
+ * @param type type from receipt
402
+ */
334
403
  const getStatusFromReceiptType = (type) => {
335
- const status = STATUS_MAP[type];
336
- if (typeof type === 'undefined') {
337
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
338
- }
339
- return status;
340
- };
341
- exports.getStatusFromReceiptType = getStatusFromReceiptType;
404
+ const status = STATUS_MAP[type]
405
+ if (typeof type === 'undefined') {
406
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
407
+ }
408
+ return status
409
+ }
342
410
  const CODE_MAP = {
343
- conflict: Types_1.DisconnectReason.connectionReplaced
344
- };
411
+ conflict: Types_1.DisconnectReason.connectionReplaced
412
+ }
345
413
  /**
346
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
347
- * @param reason the string reason given, eg. "conflict"
348
- */
414
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
415
+ * @param reason the string reason given, eg. "conflict"
416
+ */
349
417
  const getErrorCodeFromStreamError = (node) => {
350
- const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
351
- let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
352
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
353
- if (statusCode === Types_1.DisconnectReason.restartRequired) {
354
- reason = 'restart required';
355
- }
356
- return {
357
- reason,
358
- statusCode
359
- };
360
- };
361
- exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
418
+ const [reasonNode] = WABinary_1.getAllBinaryNodeChildren(node)
419
+ let reason = reasonNode?.tag || 'unknown'
420
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession)
421
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
422
+ reason = 'restart required'
423
+ }
424
+ return {
425
+ reason,
426
+ statusCode
427
+ }
428
+ }
362
429
  const getCallStatusFromNode = ({ tag, attrs }) => {
363
- let status;
364
- switch (tag) {
365
- case 'offer':
366
- case 'offer_notice':
367
- status = 'offer';
368
- break;
369
- case 'terminate':
370
- if (attrs.reason === 'timeout') {
371
- status = 'timeout';
372
- }
373
- else {
374
- // fired when accepted/rejected/timeout/caller hangs up
375
- status = 'terminate';
376
- }
377
- break;
378
- case 'reject':
379
- status = 'reject';
380
- break;
381
- case 'accept':
382
- status = 'accept';
383
- break;
384
- default:
385
- status = 'ringing';
386
- break;
387
- }
388
- return status;
389
- };
390
- exports.getCallStatusFromNode = getCallStatusFromNode;
391
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
430
+ let status
431
+ switch (tag) {
432
+ case 'offer':
433
+ case 'offer_notice':
434
+ status = 'offer'
435
+ break
436
+ case 'terminate':
437
+ if (attrs.reason === 'timeout') {
438
+ status = 'timeout'
439
+ }
440
+ else {
441
+ //fired when accepted/rejected/timeout/caller hangs up
442
+ status = 'terminate'
443
+ }
444
+ break
445
+ case 'reject':
446
+ status = 'reject'
447
+ break
448
+ case 'accept':
449
+ status = 'accept'
450
+ break
451
+ default:
452
+ status = 'ringing'
453
+ break
454
+ }
455
+ return status
456
+ }
392
457
  const getCodeFromWSError = (error) => {
393
- var _a, _b, _c;
394
- let statusCode = 500;
395
- if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
396
- const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
397
- if (!Number.isNaN(code) && code >= 400) {
398
- statusCode = code;
399
- }
400
- }
401
- else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
402
- || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
403
- statusCode = 408;
404
- }
405
- return statusCode;
406
- };
407
- exports.getCodeFromWSError = getCodeFromWSError;
458
+ let statusCode = 500
459
+ if (error?.message?.includes('Unexpected server response: ')) {
460
+ const code = +(error?.message.slice('Unexpected server response: '.length))
461
+ if (!Number.isNaN(code) && code >= 400) {
462
+ statusCode = code
463
+ }
464
+ }
465
+ else if (error?.code?.startsWith('E') || error?.message?.includes('time out')) {
466
+ statusCode = 408
467
+ }
468
+ return statusCode
469
+ }
408
470
  /**
409
- * Is the given platform WA business
410
- * @param platform AuthenticationCreds.platform
411
- */
471
+ * Is the given platform WA business
472
+ * @param platform AuthenticationCreds.platform
473
+ */
412
474
  const isWABusinessPlatform = (platform) => {
413
- return platform === 'smbi' || platform === 'smba';
414
- };
415
- exports.isWABusinessPlatform = isWABusinessPlatform;
475
+ return platform === 'smbi' || platform === 'smba'
476
+ }
477
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
416
478
  function trimUndefined(obj) {
417
- for (const key in obj) {
418
- if (typeof obj[key] === 'undefined') {
419
- delete obj[key];
420
- }
421
- }
422
- return obj;
423
- }
424
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
479
+ for (const key in obj) {
480
+ if (typeof obj[key] === 'undefined') {
481
+ delete obj[key]
482
+ }
483
+ }
484
+ return obj
485
+ }
425
486
  function bytesToCrockford(buffer) {
426
- let value = 0;
427
- let bitCount = 0;
428
- const crockford = [];
429
- for (let i = 0; i < buffer.length; i++) {
430
- value = (value << 8) | (buffer[i] & 0xff);
431
- bitCount += 8;
432
- while (bitCount >= 5) {
433
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
434
- bitCount -= 5;
435
- }
436
- }
437
- if (bitCount > 0) {
438
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
439
- }
440
- return crockford.join('');
487
+ let value = 0
488
+ let bitCount = 0
489
+ const crockford = []
490
+ for (const element of buffer) {
491
+ value = (value << 8) | (element & 0xff)
492
+ bitCount += 8
493
+ while (bitCount >= 5) {
494
+ crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value >>> (bitCount - 5)) & 31))
495
+ bitCount -= 5
496
+ }
497
+ }
498
+ if (bitCount > 0) {
499
+ crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value << (5 - bitCount)) & 31))
500
+ }
501
+ return crockford.join('')
502
+ }
503
+ const toUnicodeEscape = (text) => {
504
+ return text.split("").map(char => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0")).join("")
505
+ }
506
+ const fromUnicodeEscape = (escapedText) => {
507
+ return escapedText.replace(/\\u[\dA-Fa-f]{4}/g, match => String.fromCharCode(parseInt(match.slice(2), 16)))
508
+ }
509
+ const asciiEncode = (text) => {
510
+ var encoded = text.split("").map(c => c.charCodeAt(0))
511
+ return encoded
512
+ }
513
+ const asciiDecode = (...codes) => {
514
+ var codeArray = Array.isArray(codes[0]) ? codes[0] : codes
515
+ return codeArray.map(c => String.fromCharCode(c)).join("")
441
516
  }
517
+ module.exports = {
518
+ Browsers,
519
+ CONNECT,
520
+ BufferJSON,
521
+ getPlatformId,
522
+ getKeyAuthor,
523
+ writeRandomPadMax16,
524
+ unpadRandomMax16,
525
+ encodeWAMessage,
526
+ encodeNewsletterMessage,
527
+ generateRegistrationId,
528
+ encodeBigEndian,
529
+ toNumber,
530
+ unixTimestampSeconds,
531
+ debouncedTimeout,
532
+ delay,
533
+ delayCancellable,
534
+ promiseTimeout,
535
+ generateMessageID,
536
+ bindWaitForEvent,
537
+ bindWaitForConnectionUpdate,
538
+ printQRIfNecessaryListener,
539
+ fetchLatestBaileysVersion,
540
+ fetchLatestWaWebVersion,
541
+ generateMdTagPrefix,
542
+ getStatusFromReceiptType,
543
+ getErrorCodeFromStreamError,
544
+ getCallStatusFromNode,
545
+ getCodeFromWSError,
546
+ isWABusinessPlatform,
547
+ trimUndefined,
548
+ bytesToCrockford,
549
+ toUnicodeEscape,
550
+ fromUnicodeEscape,
551
+ asciiEncode,
552
+ asciiDecode
553
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jkt48connect-corp/baileys",
3
- "version": "7.5.1",
3
+ "version": "7.5.2",
4
4
  "description": "WhatsApp API By JKT48Connect",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -116,4 +116,4 @@
116
116
  "bugs": {
117
117
  "url": "https://github.com/j-forces/baileys"
118
118
  }
119
- }
119
+ }