@nexustechpro/baileys 1.1.3 → 1.1.4

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.
@@ -1,414 +1,298 @@
1
- import { Boom } from '@hapi/boom';
2
- import { createHash, randomBytes } from 'crypto';
3
- import { proto } from '../../WAProto/index.js';
4
- const baileysVersion = [2, 3000, 1027934701];
5
- import { DisconnectReason } from '../Types/index.js';
6
- import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
7
- import { sha256 } from './crypto.js';
1
+ import { Boom } from '@hapi/boom'
2
+ import { createHash, randomBytes } from 'crypto'
3
+ import { proto } from '../../WAProto/index.js'
4
+ const baileysVersion = [2, 3000, 1033105955]
5
+ import { DisconnectReason } from '../Types/index.js'
6
+ import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js'
7
+ import { sha256 } from './crypto.js'
8
+
8
9
  export const BufferJSON = {
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
- replacer: (k, value) => {
11
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
- return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
13
- }
14
- return value;
15
- },
16
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
- reviver: (_, value) => {
18
- if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
19
- return Buffer.from(value.data, 'base64');
20
- }
21
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
22
- const keys = Object.keys(value);
23
- if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
24
- const values = Object.values(value);
25
- if (values.every(v => typeof v === 'number')) {
26
- return Buffer.from(values);
27
- }
28
- }
10
+ replacer: (k, value) => {
11
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
13
+ }
14
+ return value
15
+ },
16
+ reviver: (_, value) => {
17
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
18
+ return Buffer.from(value.data, 'base64')
19
+ }
20
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
21
+ const keys = Object.keys(value)
22
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
23
+ const values = Object.values(value)
24
+ if (values.every(v => typeof v === 'number')) {
25
+ return Buffer.from(values)
29
26
  }
30
- return value;
27
+ }
31
28
  }
32
- };
33
- export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participant || key?.remoteJid) || '';
29
+ return value
30
+ }
31
+ }
32
+
33
+ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || ''
34
+
35
+ export const isStringNullOrEmpty = (value) => value == null || value === ''
36
+
34
37
  export const writeRandomPadMax16 = (msg) => {
35
- const pad = randomBytes(1);
36
- const padLength = (pad[0] & 0x0f) + 1;
37
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
38
- };
38
+ const pad = randomBytes(1)
39
+ const padLength = (pad[0] & 0x0f) + 1
40
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)])
41
+ }
42
+
39
43
  export const unpadRandomMax16 = (e) => {
40
- const t = new Uint8Array(e);
41
- if (0 === t.length) {
42
- throw new Error('unpadPkcs7 given empty bytes');
43
- }
44
- var r = t[t.length - 1];
45
- if (r > t.length) {
46
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
47
- }
48
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
49
- };
50
- // code is inspired by whatsmeow
44
+ const t = new Uint8Array(e)
45
+ if (0 === t.length) throw new Error('unpadPkcs7 given empty bytes')
46
+ var r = t[t.length - 1]
47
+ if (r > t.length) throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
48
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
49
+ }
50
+
51
51
  export const generateParticipantHashV2 = (participants) => {
52
- participants.sort();
53
- const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
54
- return '2:' + sha256Hash.slice(0, 6);
55
- };
56
-
57
- /**
58
- * Encode a WhatsApp message to protobuf format
59
- * Handles both raw JSON objects and pre-created protobuf objects seamlessly for ANY message type
60
- * @param {Object|proto.Message} message - Raw message object or protobuf Message
61
- * @returns {Buffer} Encoded message with random padding
62
- */
52
+ participants.sort()
53
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64')
54
+ return '2:' + sha256Hash.slice(0, 6)
55
+ }
56
+
63
57
  export const encodeWAMessage = (message) => {
58
+ try {
59
+ if (message && typeof message === 'object' && message.$type === proto.Message) {
60
+ return writeRandomPadMax16(proto.Message.encode(message).finish())
61
+ }
62
+ if (message && typeof message === 'object') {
63
+ const protoMessage = proto.Message.fromObject(message)
64
+ return writeRandomPadMax16(proto.Message.encode(protoMessage).finish())
65
+ }
66
+ return writeRandomPadMax16(proto.Message.encode(message).finish())
67
+ } catch (error) {
64
68
  try {
65
- // Check if message is already a protobuf Message instance
66
- if (message && typeof message === 'object' && message.$type === proto.Message) {
67
- // Already a protobuf object, encode directly
68
- return writeRandomPadMax16(proto.Message.encode(message).finish());
69
- }
70
-
71
- // Convert raw JSON object to protobuf Message
72
- if (message && typeof message === 'object') {
73
- // Use proto.Message.fromObject for automatic conversion
74
- const protoMessage = proto.Message.fromObject(message);
75
- return writeRandomPadMax16(proto.Message.encode(protoMessage).finish());
76
- }
77
-
78
- // Fallback for edge cases
79
- return writeRandomPadMax16(proto.Message.encode(message).finish());
80
- } catch (error) {
81
- // If conversion fails, attempt direct encoding as last resort
82
- try {
83
- return writeRandomPadMax16(proto.Message.encode(message).finish());
84
- } catch (e) {
85
- console.warn('Message encoding failed:', error.message, e.message);
86
- throw new Error(`Failed to encode message: ${error.message}`);
87
- }
69
+ return writeRandomPadMax16(proto.Message.encode(message).finish())
70
+ } catch (e) {
71
+ console.warn('Message encoding failed:', error.message, e.message)
72
+ throw new Error(`Failed to encode message: ${error.message}`)
88
73
  }
89
- };
90
- export const generateRegistrationId = () => {
91
- return Uint16Array.from(randomBytes(2))[0] & 16383;
92
- };
74
+ }
75
+ }
76
+
77
+ export const generateRegistrationId = () => Uint16Array.from(randomBytes(2))[0] & 16383
78
+
93
79
  export const encodeBigEndian = (e, t = 4) => {
94
- let r = e;
95
- const a = new Uint8Array(t);
96
- for (let i = t - 1; i >= 0; i--) {
97
- a[i] = 255 & r;
98
- r >>>= 8;
99
- }
100
- return a;
101
- };
102
- export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
103
- /** unix timestamp of a date in seconds */
104
- export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
80
+ let r = e
81
+ const a = new Uint8Array(t)
82
+ for (let i = t - 1; i >= 0; i--) {
83
+ a[i] = 255 & r
84
+ r >>>= 8
85
+ }
86
+ return a
87
+ }
88
+
89
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0
90
+
91
+ export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
92
+
105
93
  export const debouncedTimeout = (intervalMs = 1000, task) => {
106
- let timeout;
107
- return {
108
- start: (newIntervalMs, newTask) => {
109
- task = newTask || task;
110
- intervalMs = newIntervalMs || intervalMs;
111
- timeout && clearTimeout(timeout);
112
- timeout = setTimeout(() => task?.(), intervalMs);
113
- },
114
- cancel: () => {
115
- timeout && clearTimeout(timeout);
116
- timeout = undefined;
117
- },
118
- setTask: (newTask) => (task = newTask),
119
- setInterval: (newInterval) => (intervalMs = newInterval)
120
- };
121
- };
122
- export const delay = (ms) => delayCancellable(ms).delay;
94
+ let timeout
95
+ return {
96
+ start: (newIntervalMs, newTask) => {
97
+ task = newTask || task
98
+ intervalMs = newIntervalMs || intervalMs
99
+ timeout && clearTimeout(timeout)
100
+ timeout = setTimeout(() => task?.(), intervalMs)
101
+ },
102
+ cancel: () => {
103
+ timeout && clearTimeout(timeout)
104
+ timeout = undefined
105
+ },
106
+ setTask: (newTask) => (task = newTask),
107
+ setInterval: (newInterval) => (intervalMs = newInterval)
108
+ }
109
+ }
110
+
111
+ export const delay = (ms) => delayCancellable(ms).delay
112
+
123
113
  export const delayCancellable = (ms) => {
124
- const stack = new Error().stack;
125
- let timeout;
126
- let reject;
127
- const delay = new Promise((resolve, _reject) => {
128
- timeout = setTimeout(resolve, ms);
129
- reject = _reject;
130
- });
131
- const cancel = () => {
132
- clearTimeout(timeout);
133
- reject(new Boom('Cancelled', {
134
- statusCode: 500,
135
- data: {
136
- stack
137
- }
138
- }));
139
- };
140
- return { delay, cancel };
141
- };
114
+ const stack = new Error().stack
115
+ let timeout
116
+ let reject
117
+ const delay = new Promise((resolve, _reject) => {
118
+ timeout = setTimeout(resolve, ms)
119
+ reject = _reject
120
+ })
121
+ const cancel = () => {
122
+ clearTimeout(timeout)
123
+ reject(new Boom('Cancelled', { statusCode: 500, data: { stack } }))
124
+ }
125
+ return { delay, cancel }
126
+ }
127
+
142
128
  export async function promiseTimeout(ms, promise) {
143
- if (!ms) {
144
- return new Promise(promise);
145
- }
146
- const stack = new Error().stack;
147
- // Create a promise that rejects in <ms> milliseconds
148
- const { delay, cancel } = delayCancellable(ms);
149
- const p = new Promise((resolve, reject) => {
150
- delay
151
- .then(() => reject(new Boom('Timed Out', {
152
- statusCode: DisconnectReason.timedOut,
153
- data: {
154
- stack
155
- }
156
- })))
157
- .catch(err => reject(err));
158
- promise(resolve, reject);
159
- }).finally(cancel);
160
- return p;
129
+ if (!ms) return new Promise(promise)
130
+ const stack = new Error().stack
131
+ const { delay, cancel } = delayCancellable(ms)
132
+ const p = new Promise((resolve, reject) => {
133
+ delay.then(() => reject(new Boom('Timed Out', { statusCode: DisconnectReason.timedOut, data: { stack } }))).catch(err => reject(err))
134
+ promise(resolve, reject)
135
+ }).finally(cancel)
136
+ return p
161
137
  }
162
- // inspired from whatsmeow code
163
- // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
138
+
164
139
  export const generateMessageIDV2 = (userId) => {
165
- const data = Buffer.alloc(8 + 20 + 16);
166
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
167
- if (userId) {
168
- const id = jidDecode(userId);
169
- if (id?.user) {
170
- data.write(id.user, 8);
171
- data.write('@c.us', 8 + id.user.length);
172
- }
140
+ const data = Buffer.alloc(8 + 20 + 16)
141
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
142
+ if (userId) {
143
+ const id = jidDecode(userId)
144
+ if (id?.user) {
145
+ data.write(id.user, 8)
146
+ data.write('@c.us', 8 + id.user.length)
173
147
  }
174
- const random = randomBytes(16);
175
- random.copy(data, 28);
176
- const hash = createHash('sha256').update(data).digest();
177
- return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
178
- };
179
- // generate a random ID to attach to a message
180
- export const generateMessageID = () => 'NEXUSTECHPRO-' + randomBytes(6).toString('hex').toUpperCase();
148
+ }
149
+ const random = randomBytes(16)
150
+ random.copy(data, 28)
151
+ const hash = createHash('sha256').update(data).digest()
152
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18)
153
+ }
154
+
155
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase()
156
+
181
157
  export function bindWaitForEvent(ev, event) {
182
- return async (check, timeoutMs) => {
183
- let listener;
184
- let closeListener;
185
- await promiseTimeout(timeoutMs, (resolve, reject) => {
186
- closeListener = ({ connection, lastDisconnect }) => {
187
- if (connection === 'close') {
188
- reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
189
- }
190
- };
191
- ev.on('connection.update', closeListener);
192
- listener = async (update) => {
193
- if (await check(update)) {
194
- resolve();
195
- }
196
- };
197
- ev.on(event, listener);
198
- }).finally(() => {
199
- ev.off(event, listener);
200
- ev.off('connection.update', closeListener);
201
- });
202
- };
158
+ return async (check, timeoutMs) => {
159
+ let listener
160
+ let closeListener
161
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
162
+ closeListener = ({ connection, lastDisconnect }) => {
163
+ if (connection === 'close') reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
164
+ }
165
+ ev.on('connection.update', closeListener)
166
+ listener = async (update) => {
167
+ if (await check(update)) resolve()
168
+ }
169
+ ev.on(event, listener)
170
+ }).finally(() => {
171
+ ev.off(event, listener)
172
+ ev.off('connection.update', closeListener)
173
+ })
174
+ }
203
175
  }
204
- export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
205
- /**
206
- * utility that fetches latest baileys version from the master branch.
207
- * Use to ensure your WA connection is always on the latest version
208
- */
176
+
177
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update')
178
+
209
179
  export const fetchLatestBaileysVersion = async (options = {}) => {
210
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
211
- try {
212
- const response = await fetch(URL, {
213
- dispatcher: options.dispatcher,
214
- method: 'GET',
215
- headers: options.headers
216
- });
217
- if (!response.ok) {
218
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
219
- }
220
- const text = await response.text();
221
- // Extract version from line 7 (const version = [...])
222
- const lines = text.split('\n');
223
- const versionLine = lines[6]; // Line 7 (0-indexed)
224
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
225
- if (versionMatch) {
226
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
227
- return {
228
- version,
229
- isLatest: true
230
- };
231
- }
232
- else {
233
- throw new Error('Could not parse version from Defaults/index.ts');
234
- }
235
- }
236
- catch (error) {
237
- return {
238
- version: baileysVersion,
239
- isLatest: false,
240
- error
241
- };
242
- }
243
- };
244
- /**
245
- * A utility that fetches the latest web version of whatsapp.
246
- * Use to ensure your WA connection is always on the latest version
247
- */
180
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts'
181
+ try {
182
+ const response = await fetch(URL, { dispatcher: options.dispatcher, method: 'GET', headers: options.headers })
183
+ if (!response.ok) throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status })
184
+ const text = await response.text()
185
+ const lines = text.split('\n')
186
+ const versionLine = lines[6]
187
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/)
188
+ if (versionMatch) {
189
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])]
190
+ return { version, isLatest: true }
191
+ } else throw new Error('Could not parse version from Defaults/index.ts')
192
+ } catch (error) {
193
+ return { version: baileysVersion, isLatest: false, error }
194
+ }
195
+ }
196
+
248
197
  export const fetchLatestWaWebVersion = async (options = {}) => {
249
- try {
250
- // Absolute minimal headers required to bypass anti-bot detection
251
- const defaultHeaders = {
252
- 'sec-fetch-site': 'none',
253
- 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
254
- };
255
- const headers = { ...defaultHeaders, ...options.headers };
256
- const response = await fetch('https://web.whatsapp.com/sw.js', {
257
- ...options,
258
- method: 'GET',
259
- headers
260
- });
261
- if (!response.ok) {
262
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
263
- }
264
- const data = await response.text();
265
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
266
- const match = data.match(regex);
267
- if (!match?.[1]) {
268
- return {
269
- version: baileysVersion,
270
- isLatest: false,
271
- error: {
272
- message: 'Could not find client revision in the fetched content'
273
- }
274
- };
275
- }
276
- const clientRevision = match[1];
277
- return {
278
- version: [2, 3000, +clientRevision],
279
- isLatest: true
280
- };
281
- }
282
- catch (error) {
283
- return {
284
- version: baileysVersion,
285
- isLatest: false,
286
- error
287
- };
288
- }
289
- };
290
- /** unique message tag prefix for MD clients */
198
+ try {
199
+ const defaultHeaders = { 'sec-fetch-site': 'none', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' }
200
+ const headers = { ...defaultHeaders, ...options.headers }
201
+ const response = await fetch('https://web.whatsapp.com/sw.js', { ...options, method: 'GET', headers })
202
+ if (!response.ok) throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status })
203
+ const data = await response.text()
204
+ const regex = /\\?"client_revision\\?":\s*(\d+)/
205
+ const match = data.match(regex)
206
+ if (!match?.[1]) return { version: baileysVersion, isLatest: false, error: { message: 'Could not find client revision in the fetched content' } }
207
+ const clientRevision = match[1]
208
+ return { version: [2, 3000, +clientRevision], isLatest: true }
209
+ } catch (error) {
210
+ return { version: baileysVersion, isLatest: false, error }
211
+ }
212
+ }
213
+
291
214
  export const generateMdTagPrefix = () => {
292
- const bytes = randomBytes(4);
293
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
294
- };
295
- const STATUS_MAP = {
296
- sender: proto.WebMessageInfo.Status.SERVER_ACK,
297
- played: proto.WebMessageInfo.Status.PLAYED,
298
- read: proto.WebMessageInfo.Status.READ,
299
- 'read-self': proto.WebMessageInfo.Status.READ
300
- };
301
- /**
302
- * Given a type of receipt, returns what the new status of the message should be
303
- * @param type type from receipt
304
- */
215
+ const bytes = randomBytes(4)
216
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
217
+ }
218
+
219
+ const STATUS_MAP = { sender: proto.WebMessageInfo.Status.SERVER_ACK, played: proto.WebMessageInfo.Status.PLAYED, read: proto.WebMessageInfo.Status.READ, 'read-self': proto.WebMessageInfo.Status.READ }
220
+
305
221
  export const getStatusFromReceiptType = (type) => {
306
- const status = STATUS_MAP[type];
307
- if (typeof type === 'undefined') {
308
- return proto.WebMessageInfo.Status.DELIVERY_ACK;
309
- }
310
- return status;
311
- };
312
- const CODE_MAP = {
313
- conflict: DisconnectReason.connectionReplaced
314
- };
315
- /**
316
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
317
- * @param reason the string reason given, eg. "conflict"
318
- */
222
+ const status = STATUS_MAP[type]
223
+ if (typeof type === 'undefined') return proto.WebMessageInfo.Status.DELIVERY_ACK
224
+ return status
225
+ }
226
+
227
+ const CODE_MAP = { conflict: DisconnectReason.connectionReplaced }
228
+
319
229
  export const getErrorCodeFromStreamError = (node) => {
320
- const [reasonNode] = getAllBinaryNodeChildren(node);
321
- let reason = reasonNode?.tag || 'unknown';
322
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
323
- if (statusCode === DisconnectReason.restartRequired) {
324
- reason = 'restart required';
325
- }
326
- return {
327
- reason,
328
- statusCode
329
- };
330
- };
230
+ const [reasonNode] = getAllBinaryNodeChildren(node)
231
+ let reason = reasonNode?.tag || 'unknown'
232
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession)
233
+ if (statusCode === DisconnectReason.restartRequired) reason = 'restart required'
234
+ return { reason, statusCode }
235
+ }
236
+
331
237
  export const getCallStatusFromNode = ({ tag, attrs }) => {
332
- let status;
333
- switch (tag) {
334
- case 'offer':
335
- case 'offer_notice':
336
- status = 'offer';
337
- break;
338
- case 'terminate':
339
- if (attrs.reason === 'timeout') {
340
- status = 'timeout';
341
- }
342
- else {
343
- //fired when accepted/rejected/timeout/caller hangs up
344
- status = 'terminate';
345
- }
346
- break;
347
- case 'reject':
348
- status = 'reject';
349
- break;
350
- case 'accept':
351
- status = 'accept';
352
- break;
353
- default:
354
- status = 'ringing';
355
- break;
356
- }
357
- return status;
358
- };
359
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
238
+ let status
239
+ switch (tag) {
240
+ case 'offer':
241
+ case 'offer_notice':
242
+ status = 'offer'
243
+ break
244
+ case 'terminate':
245
+ status = attrs.reason === 'timeout' ? 'timeout' : 'terminate'
246
+ break
247
+ case 'reject':
248
+ status = 'reject'
249
+ break
250
+ case 'accept':
251
+ status = 'accept'
252
+ break
253
+ default:
254
+ status = 'ringing'
255
+ break
256
+ }
257
+ return status
258
+ }
259
+
260
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: '
261
+
360
262
  export const getCodeFromWSError = (error) => {
361
- let statusCode = 500;
362
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
363
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
364
- if (!Number.isNaN(code) && code >= 400) {
365
- statusCode = code;
366
- }
367
- }
368
- else if (
369
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
370
- error?.code?.startsWith('E') ||
371
- error?.message?.includes('timed out')) {
372
- // handle ETIMEOUT, ENOTFOUND etc
373
- statusCode = 408;
374
- }
375
- return statusCode;
376
- };
377
- /**
378
- * Is the given platform WA business
379
- * @param platform AuthenticationCreds.platform
380
- */
381
- export const isWABusinessPlatform = (platform) => {
382
- return platform === 'smbi' || platform === 'smba';
383
- };
384
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
+ let statusCode = 500
264
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
265
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length)
266
+ if (!Number.isNaN(code) && code >= 400) statusCode = code
267
+ } else if (error?.code?.startsWith('E') || error?.message?.includes('timed out')) statusCode = 408
268
+ return statusCode
269
+ }
270
+
271
+ export const isWABusinessPlatform = (platform) => platform === 'smbi' || platform === 'smba'
272
+
385
273
  export function trimUndefined(obj) {
386
- for (const key in obj) {
387
- if (typeof obj[key] === 'undefined') {
388
- delete obj[key];
389
- }
390
- }
391
- return obj;
274
+ for (const key in obj) if (typeof obj[key] === 'undefined') delete obj[key]
275
+ return obj
392
276
  }
393
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
277
+
278
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ'
279
+
394
280
  export function bytesToCrockford(buffer) {
395
- let value = 0;
396
- let bitCount = 0;
397
- const crockford = [];
398
- for (const element of buffer) {
399
- value = (value << 8) | (element & 0xff);
400
- bitCount += 8;
401
- while (bitCount >= 5) {
402
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
403
- bitCount -= 5;
404
- }
405
- }
406
- if (bitCount > 0) {
407
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
281
+ let value = 0
282
+ let bitCount = 0
283
+ const crockford = []
284
+ for (const element of buffer) {
285
+ value = (value << 8) | (element & 0xff)
286
+ bitCount += 8
287
+ while (bitCount >= 5) {
288
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31))
289
+ bitCount -= 5
408
290
  }
409
- return crockford.join('');
291
+ }
292
+ if (bitCount > 0) crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31))
293
+ return crockford.join('')
410
294
  }
295
+
411
296
  export function encodeNewsletterMessage(message) {
412
- return proto.Message.encode(message).finish();
413
- }
414
- //# sourceMappingURL=generics.js.map
297
+ return proto.Message.encode(message).finish()
298
+ }