zaileys 1.1.40 → 2.0.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.
package/dist/index.js CHANGED
@@ -1,2033 +1,24 @@
1
- 'use strict';
2
-
3
- var makeWASocket = require('baileys');
4
- var EventEmitter = require('events');
5
- var nanospinner = require('nanospinner');
6
- var NodeCache2 = require('node-cache');
7
- var pino = require('pino');
8
- var fs = require('fs');
9
- var lowdb = require('lowdb');
10
- var FileSync = require('lowdb/adapters/FileSync');
11
- var path = require('path');
12
- var chalk = require('chalk');
13
- var _2 = require('lodash');
14
- var z2 = require('zod/v4');
15
- var figlet = require('figlet');
16
- var QRCode = require('qrcode');
17
- var zod = require('zod');
18
-
19
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
20
-
21
- var makeWASocket__default = /*#__PURE__*/_interopDefault(makeWASocket);
22
- var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
23
- var NodeCache2__default = /*#__PURE__*/_interopDefault(NodeCache2);
24
- var pino__default = /*#__PURE__*/_interopDefault(pino);
25
- var lowdb__default = /*#__PURE__*/_interopDefault(lowdb);
26
- var FileSync__default = /*#__PURE__*/_interopDefault(FileSync);
27
- var chalk__default = /*#__PURE__*/_interopDefault(chalk);
28
- var _2__default = /*#__PURE__*/_interopDefault(_2);
29
- var z2__default = /*#__PURE__*/_interopDefault(z2);
30
- var figlet__default = /*#__PURE__*/_interopDefault(figlet);
31
- var QRCode__default = /*#__PURE__*/_interopDefault(QRCode);
32
-
33
- // src/classes/Client.ts
34
- var sendError = (text) => new Error(chalk__default.default.red(text));
35
- var toJson = (object) => {
36
- try {
37
- return JSON.parse(object);
38
- } catch {
39
- return _2__default.default.attempt(() => JSON.parse(JSON.stringify(object) || "{}"));
40
- }
41
- };
42
- var toString = (object) => {
43
- try {
44
- return JSON.stringify(object);
45
- } catch {
46
- const result = _2__default.default.attempt(() => JSON.stringify(toJson(object) || "{}"));
47
- return _2__default.default.isError(result) ? "{}" : result;
48
- }
49
- };
50
- var shuffleString = (str) => {
51
- return _2__default.default.shuffle([...str]).join("");
52
- };
53
- var tryAgain = async (fn) => {
54
- const RETRY_DELAY = 200;
55
- const MAX_RETRIES = 10;
56
- for (let x = 0; x < MAX_RETRIES; x++) {
57
- try {
58
- return await fn();
59
- } catch (_e) {
60
- await new Promise((r) => setTimeout(r, RETRY_DELAY));
61
- }
62
- }
63
- throw sendError("Max retries reached");
64
- };
65
- var findWord = (text = "", word = "") => {
66
- if (!text) return null;
67
- return _2__default.default.includes(text.toLowerCase(), word.toLowerCase());
68
- };
69
- var normalizeText = (text = "") => {
70
- if (!text) return null;
71
- return _2__default.default.replace(text, /\u202E([\s\S]*?)\u202C/g, (_e, segmen) => {
72
- const arr = _2__default.default.toArray(segmen);
73
- const reversed = _2__default.default.reverse(_2__default.default.clone(arr));
74
- return _2__default.default.join(reversed, "");
75
- }).replace(/[\u202A-\u202E\u202C]/g, "");
76
- };
77
- var extractJids = (text = "") => {
78
- if (!text) return [];
79
- const ids = /* @__PURE__ */ new Set();
80
- for (const match of text.matchAll(/@(\d+)/g)) {
81
- ids.add(match[1]);
82
- }
83
- return _2__default.default.flatMap([...ids], (id) => [`${id}@s.whatsapp.net`, `${id}@g.us`]);
84
- };
85
- var extractUrls = (text = "") => {
86
- if (!text) return [];
87
- const regex = /https?:\/\/(?:[-\w.])+(?:\.[a-zA-Z]{2,})+(?:\/[^\s<>"']*)?/g;
88
- return _2__default.default.castArray(text.match(regex) || []);
89
- };
90
- var getMentions = (text = "") => {
91
- if (!text) return [];
92
- const ids = /* @__PURE__ */ new Set();
93
- for (const match of text.matchAll(/@(\d+)/g)) {
94
- ids.add(match[1]);
95
- }
96
- return _2__default.default.toArray(ids);
97
- };
98
- var randomize = (arr) => {
99
- return arr[Math.floor(Math.random() * arr.length)];
100
- };
101
- var delay = (ms) => {
102
- return new Promise((resolve) => setTimeout(resolve, ms));
103
- };
104
- var CHUNK_SIZE = 1e3;
105
- var JsonDB = class {
106
- session = "zaileys-sessions";
107
- db;
108
- storeDir;
109
- async initialize(session) {
110
- this.session = session;
111
- const authPath = `sessions/${this.session}/auth.json`;
112
- this.storeDir = `sessions/${this.session}/stores`;
113
- const dirAuth = path.dirname(authPath);
114
- if (!fs.existsSync(dirAuth)) fs.mkdirSync(dirAuth, { recursive: true });
115
- if (!fs.existsSync(this.storeDir)) fs.mkdirSync(this.storeDir, { recursive: true });
116
- const adapter = new FileSync__default.default(authPath);
117
- this.db = lowdb__default.default(adapter);
118
- this.db.defaults([]).write();
119
- }
120
- tryRecoverRaw(raw) {
121
- const s = raw.trim();
122
- try {
123
- return JSON.parse(s);
124
- } catch (_error) {
125
- try {
126
- const a = s.indexOf("[");
127
- const b = s.lastIndexOf("]");
128
- if (a !== -1 && b !== -1 && b > a) {
129
- const sub = s.slice(a, b + 1);
130
- return JSON.parse(sub);
131
- }
132
- } catch (_error2) {
133
- }
134
- try {
135
- const wrapped = `[${s.replace(/}\s*{/g, "},{")}]`;
136
- return JSON.parse(wrapped);
137
- } catch (_error2) {
138
- }
139
- try {
140
- const lines = _2__default.default.filter(
141
- _2__default.default.map(s.split(/\\r?\\n/), (l) => l.trim()),
142
- Boolean
143
- );
144
- const parsedResults = _2__default.default.map(lines, (l) => {
145
- try {
146
- return JSON.parse(l);
147
- } catch (_error2) {
148
- return null;
149
- }
150
- });
151
- const parsed = _2__default.default.filter(parsedResults, (item) => item !== null);
152
- if (parsed.length) return parsed;
153
- } catch (_error2) {
154
- }
155
- }
156
- return null;
157
- }
158
- async chunks(key) {
159
- const files = _2__default.default.filter(fs.readdirSync(this.storeDir), (f) => _2__default.default.startsWith(f, `${key}-`) && _2__default.default.endsWith(f, ".json")).sort();
160
- const result = [];
161
- for (const file of files) {
162
- const full = `${this.storeDir}/${file}`;
163
- const adapter = new FileSync__default.default(full);
164
- const db = lowdb__default.default(adapter);
165
- try {
166
- db.defaults([]).write();
167
- result.push(...toJson(db.value()));
168
- } catch {
169
- let raw = "";
170
- try {
171
- raw = fs.readFileSync(full, "utf8");
172
- } catch (_error) {
173
- raw = "";
174
- }
175
- const recovered = raw ? this.tryRecoverRaw(raw) : null;
176
- if (recovered) {
177
- db.setState(Array.isArray(recovered) ? recovered : [recovered]).write();
178
- result.push(...toJson(db.value()));
179
- } else {
180
- const corrupt = `${full}.corrupt.${Date.now()}`;
181
- try {
182
- fs.renameSync(full, corrupt);
183
- } catch (_renameErr) {
184
- }
185
- try {
186
- fs.writeFileSync(full, "[]", "utf8");
187
- } catch (_writeFileErr) {
188
- }
189
- }
190
- }
191
- }
192
- return result;
193
- }
194
- async writeChunks(key, items) {
195
- _2__default.default.forEach(
196
- _2__default.default.filter(fs.readdirSync(this.storeDir), (f) => _2__default.default.startsWith(f, `${key}-`) && _2__default.default.endsWith(f, ".json")),
197
- (f) => fs.unlinkSync(`${this.storeDir}/${f}`)
198
- );
199
- let index = 0;
200
- for (let i = 0; i < items.length; i += CHUNK_SIZE) {
201
- const chunk = items.slice(i, i + CHUNK_SIZE);
202
- const file = `${this.storeDir}/${key}-${index}.json`;
203
- const adapter = new FileSync__default.default(file);
204
- const db = lowdb__default.default(adapter);
205
- db.setState(chunk).write();
206
- try {
207
- db.write();
208
- } catch (err) {
209
- if (err?.code === "ENOENT") {
210
- try {
211
- fs.renameSync(`${file}.tmp`, file);
212
- } catch (_renameErr) {
213
- try {
214
- db.write();
215
- } catch (_writeErr) {
216
- try {
217
- fs.writeFileSync(file, JSON.stringify(chunk), "utf8");
218
- } catch (_writeFileErr) {
219
- }
220
- }
221
- }
222
- } else {
223
- throw err;
224
- }
225
- }
226
- index++;
227
- }
228
- }
229
- store(key) {
230
- return {
231
- read: async (id) => {
232
- const list = await this.chunks(key);
233
- const row = _2__default.default.find(list, (i) => i.id === id);
234
- return row ? JSON.parse(row.value) : null;
235
- },
236
- write: async (obj) => {
237
- const list = await this.chunks(key);
238
- const id = obj.key && typeof obj.key === "object" && "id" in obj.key ? obj.key.id : obj.id;
239
- const serialized = JSON.stringify(obj);
240
- const idx = list.findIndex((i) => i.id === id);
241
- if (idx !== -1) list[idx].value = serialized;
242
- else list.push({ id, value: serialized });
243
- await this.writeChunks(key, list);
244
- }
245
- };
246
- }
247
- async upsert(id, value) {
248
- const replacer = JSON.stringify(value, makeWASocket.BufferJSON.replacer);
249
- const dbValue = this.db.value();
250
- const data = Array.isArray(dbValue) ? dbValue : [];
251
- const idx = _2__default.default.findIndex(data, (i) => i.id === id);
252
- if (idx !== -1) {
253
- data[idx].value = replacer;
254
- } else {
255
- data.push({ id, value: replacer });
256
- }
257
- this.db.setState(data).write();
258
- }
259
- async read(id) {
260
- const dbValue = this.db.value();
261
- const data = Array.isArray(dbValue) ? dbValue : [];
262
- const row = _2__default.default.find(data, (i) => i.id === id);
263
- if (!row || !row.value) return null;
264
- const creds = typeof row.value === "object" ? toString(row.value) : row.value;
265
- return JSON.parse(creds, makeWASocket.BufferJSON.reviver);
266
- }
267
- async remove(id) {
268
- const dbValue = this.db.value();
269
- const data = Array.isArray(dbValue) ? dbValue : [];
270
- const filtered = _2__default.default.filter(data, (i) => i.id !== id);
271
- this.db.setState(filtered).write();
272
- }
273
- async clear() {
274
- const dbValue = this.db.value();
275
- const data = Array.isArray(dbValue) ? dbValue : [];
276
- const filtered = _2__default.default.filter(data, (i) => i.id === "creds");
277
- this.db.setState(filtered).write();
278
- }
279
- async delete() {
280
- this.db.setState([]);
281
- await this.db.write();
282
- }
283
- };
284
-
285
- // src/utils/decrypt.ts
286
- var allocate = (str) => {
287
- let n = 0;
288
- let p = str.length;
289
- if (!p) return new Uint8Array(1);
290
- while (--p % 4 > 1 && str.charAt(p) === "=") ++n;
291
- return new Uint8Array(Math.ceil(str.length * 3) / 4 - n).fill(0);
292
- };
293
- var parseTimestamp = (timestamp) => {
294
- if (typeof timestamp === "string") return parseInt(timestamp, 10);
295
- if (typeof timestamp === "number") return timestamp;
296
- return timestamp;
297
- };
298
- var fromObject = (args) => {
299
- const fingerprint = args.fingerprint || {};
300
- const f = {
301
- ...fingerprint,
302
- deviceIndexes: Array.isArray(fingerprint.deviceIndexes) ? fingerprint.deviceIndexes : []
303
- };
304
- const message = {
305
- keyData: Array.isArray(args.keyData) ? args.keyData : new Uint8Array(),
306
- fingerprint: {
307
- rawId: fingerprint.rawId || 0,
308
- currentIndex: fingerprint.rawId || 0,
309
- deviceIndexes: f.deviceIndexes
310
- },
311
- timestamp: parseTimestamp(args.timestamp)
312
- };
313
- if (typeof args.keyData === "string") {
314
- message.keyData = allocate(args.keyData);
315
- }
316
- return message;
317
- };
318
-
319
- // src/modules/store.ts
320
- var StoreHandler = async (db) => {
321
- return {
322
- bind: (client) => {
323
- client?.socket?.ev.on("messaging-history.set", async (update) => {
324
- const { chats, contacts, messages } = update;
325
- for (const chat of chats) {
326
- await db.store("chats").write(chat);
327
- }
328
- for (const contact of contacts) {
329
- await db.store("contacts").write(contact);
330
- }
331
- for (const message of messages) {
332
- if (!message.message) return;
333
- if (message.message?.protocolMessage) return;
334
- await db.store("messages").write(message);
335
- }
336
- });
337
- client?.socket?.ev.on("messages.upsert", async ({ messages }) => {
338
- for (const message of messages) {
339
- await db.store("messages").write(message);
340
- }
341
- });
342
- client?.socket?.ev.on("chats.upsert", async (chats) => {
343
- for (const chat of chats) {
344
- await db.store("chats").write(chat);
345
- }
346
- });
347
- client?.socket?.ev.on("contacts.upsert", async (contacts) => {
348
- for (const contact of contacts) {
349
- await db.store("contacts").write(contact);
350
- }
351
- });
352
- client?.socket?.ev.on("groups.update", async ([event]) => {
353
- if (event.id) {
354
- const metadata = await client?.socket?.groupMetadata(event.id);
355
- client.cache.set(event.id, metadata);
356
- }
357
- });
358
- client?.socket?.ev.on("group-participants.update", async (event) => {
359
- const metadata = await client?.socket?.groupMetadata(event.id);
360
- client.cache.set(event.id, metadata);
361
- });
362
- }
363
- };
364
- };
365
-
366
- // src/modules/auth.ts
367
- var AuthHandler = async (db) => {
368
- const creds = await tryAgain(() => db.read("creds")) || makeWASocket.initAuthCreds();
369
- const store = await StoreHandler(db);
370
- return {
371
- db,
372
- store,
373
- state: {
374
- creds,
375
- keys: {
376
- get: async (type, ids) => {
377
- const data = {};
378
- for (const id of ids) {
379
- let value = await tryAgain(() => db.read(`${type}-${id}`));
380
- if (type === "app-state-sync-key" && value) {
381
- value = fromObject(value);
382
- }
383
- if (value !== null && value !== void 0) {
384
- data[id] = value;
385
- }
386
- }
387
- return data;
388
- },
389
- set: async (data) => {
390
- for (const category in data) {
391
- for (const id in data[category]) {
392
- const value = data[category][id];
393
- const name = `${category}-${id}`;
394
- if (value) {
395
- await tryAgain(() => db.upsert(name, value));
396
- } else {
397
- await tryAgain(() => db.remove(name));
398
- }
399
- }
400
- }
401
- }
402
- }
403
- },
404
- clear: async () => {
405
- await tryAgain(() => db.clear());
406
- },
407
- saveCreds: async () => {
408
- await tryAgain(() => db.upsert("creds", creds));
409
- },
410
- removeCreds: async () => {
411
- await tryAgain(() => db.delete());
412
- }
413
- };
414
- };
415
- var PluginsHandler = (necessary, props) => {
416
- const plugins = _2__default.default.find(props.plugins, (x) => x?.necessary == necessary);
417
- return plugins;
418
- };
419
-
420
- // src/modules/database.ts
421
- var CredsHandler = async (props) => {
422
- const db = PluginsHandler("database", props) || new JsonDB();
423
- await db.initialize(props.session || "default");
424
- return await AuthHandler(db);
425
- };
426
- var defaultBoolean = (state) => z2.z.boolean().default(state).optional();
427
- var defaultString = (state) => z2.z.string().default(state).optional();
428
- var AdsReplyType = z2.z.custom();
429
-
430
- // src/types/classes/Client.ts
431
- var PluginsType = z2__default.default.array(
432
- z2__default.default.object({
433
- necessary: z2__default.default.string()
434
- }).passthrough()
435
- ).optional();
436
- var LimiterType = z2__default.default.object({
437
- durationMs: z2__default.default.number(),
438
- maxMessages: z2__default.default.number()
439
- }).optional();
440
- var CitationType = z2__default.default.partialRecord(z2__default.default.string(), z2__default.default.number().array()).optional();
441
- var FakeReplyType = z2__default.default.object({
442
- provider: z2__default.default.enum(["whatsapp", "meta", "chatgpt", "copilot", "instagram", "tiktok"])
443
- }).optional();
444
- var ClientBaseType = z2__default.default.object({
445
- session: z2__default.default.string().default("zaileys-sessions").optional(),
446
- prefix: z2__default.default.string().optional(),
447
- ignoreMe: defaultBoolean(true),
448
- showLogs: defaultBoolean(true),
449
- autoMentions: defaultBoolean(true),
450
- autoOnline: defaultBoolean(true),
451
- autoRead: defaultBoolean(true),
452
- autoPresence: defaultBoolean(true),
453
- autoRejectCall: defaultBoolean(true),
454
- plugins: PluginsType,
455
- limiter: LimiterType,
456
- citation: CitationType,
457
- fakeReply: FakeReplyType
458
- });
459
- var ClientAuthPairingType = z2__default.default.object({
460
- authType: z2__default.default.literal("pairing"),
461
- phoneNumber: z2__default.default.number()
462
- });
463
- var ClientAuthQRType = z2__default.default.object({
464
- authType: z2__default.default.literal("qr")
465
- });
466
- var ClientOptionsType = z2__default.default.discriminatedUnion("authType", [ClientAuthPairingType.extend(ClientBaseType.shape), ClientAuthQRType.extend(ClientBaseType.shape)]);
467
- var EventEnumType = z2__default.default.enum(["connection", "messages", "calls", "webhooks"]);
468
- var displayBanner = async (text = "ZAILEYS") => {
469
- figlet__default.default(text, async (err, data) => {
470
- if (err) return;
471
- console.log(chalk__default.default.gray.italic(data));
472
- });
473
- };
474
-
475
- // src/extractor/calls.ts
476
- var CallsExtractor = async (client, caller) => {
477
- const payload = {};
478
- payload.callId = caller.id;
479
- payload.roomId = caller.chatId;
480
- payload.callerId = caller.from;
481
- payload.date = caller.date;
482
- payload.offline = caller.offline;
483
- payload.status = caller.status;
484
- payload.isVideo = !!caller.isVideo;
485
- payload.isGroup = !!caller.isGroup;
486
- return payload;
487
- };
488
- var MessagesMediaType = {
489
- text: "text",
490
- conversation: "text",
491
- imageMessage: "image",
492
- contactMessage: "contact",
493
- locationMessage: "location",
494
- documentMessage: "document",
495
- audioMessage: "audio",
496
- videoMessage: "video",
497
- protocolMessage: "protocol",
498
- contactsArrayMessage: "contacts",
499
- highlyStructuredMessage: "highlyStructured",
500
- sendPaymentMessage: "sendPayment",
501
- liveLocationMessage: "location",
502
- requestPaymentMessage: "requestPayment",
503
- declinePaymentRequestMessage: "declinePaymentRequest",
504
- cancelPaymentRequestMessage: "cancelPaymentRequest",
505
- templateMessage: "template",
506
- stickerMessage: "sticker",
507
- groupInviteMessage: "groupInvite",
508
- templateButtonReplyMessage: "buttons",
509
- productMessage: "product",
510
- deviceSentMessage: "deviceSent",
511
- listMessage: "list",
512
- viewOnceMessage: "viewOnce",
513
- orderMessage: "order",
514
- listResponseMessage: "list",
515
- ephemeralMessage: "ephemeral",
516
- invoiceMessage: "invoice",
517
- buttonsMessage: "buttons",
518
- buttonsResponseMessage: "buttons",
519
- paymentInviteMessage: "paymentInvite",
520
- interactiveMessage: "interactive",
521
- reactionMessage: "reaction",
522
- stickerSyncRmrMessage: "sticker",
523
- interactiveResponseMessage: "interactiveResponse",
524
- pollCreationMessage: "pollCreation",
525
- pollUpdateMessage: "pollUpdate",
526
- keepInChatMessage: "keepInChat",
527
- documentWithCaptionMessage: "document",
528
- requestPhoneNumberMessage: "requestPhoneNumber",
529
- viewOnceMessageV2: "viewOnce",
530
- encReactionMessage: "reaction",
531
- editedMessage: "text",
532
- viewOnceMessageV2Extension: "viewOnce",
533
- pollCreationMessageV2: "pollCreation",
534
- scheduledCallCreationMessage: "scheduledCallCreation",
535
- groupMentionedMessage: "groupMentioned",
536
- pinInChatMessage: "pinInChat",
537
- pollCreationMessageV3: "pollCreation",
538
- scheduledCallEditMessage: "scheduledCallEdit",
539
- ptvMessage: "ptv",
540
- botInvokeMessage: "botInvoke",
541
- callLogMesssage: "callLog",
542
- encCommentMessage: "encComment",
543
- bcallMessage: "bcall",
544
- lottieStickerMessage: "lottieSticker",
545
- eventMessage: "event",
546
- commentMessage: "comment",
547
- newsletterAdminInviteMessage: "text",
548
- extendedTextMessageWithParentKey: "text",
549
- extendedTextMessage: "text",
550
- placeholderMessage: "placeholder",
551
- encEventUpdateMessage: "encEventUpdate"
552
- };
553
- var MessagesVerifiedPlatformType = {
554
- whatsapp: "0@s.whatsapp.net",
555
- meta: "13135550002@s.whatsapp.net",
556
- chatgpt: "18002428478@s.whatsapp.net",
557
- copilot: "18772241042@s.whatsapp.net",
558
- instagram: "447723442971@s.whatsapp.net",
559
- tiktok: "6285574670498@s.whatsapp.net"
560
- };
561
- var MessagesEnumType = zod.z.enum([
562
- "text",
563
- "image",
564
- "contact",
565
- "location",
566
- "document",
567
- "audio",
568
- "video",
569
- "protocol",
570
- "contacts",
571
- "highlyStructured",
572
- "sendPayment",
573
- "requestPayment",
574
- "declinePaymentRequest",
575
- "cancelPaymentRequest",
576
- "template",
577
- "sticker",
578
- "groupInvite",
579
- "product",
580
- "deviceSent",
581
- "list",
582
- "viewOnce",
583
- "order",
584
- "ephemeral",
585
- "invoice",
586
- "buttons",
587
- "paymentInvite",
588
- "interactive",
589
- "reaction",
590
- "sticker",
591
- "interactiveResponse",
592
- "pollCreation",
593
- "pollUpdate",
594
- "keepInChat",
595
- "document",
596
- "requestPhoneNumber",
597
- "viewOnce",
598
- "reaction",
599
- "text",
600
- "viewOnce",
601
- "pollCreation",
602
- "scheduledCallCreation",
603
- "groupMentioned",
604
- "pinInChat",
605
- "pollCreation",
606
- "scheduledCallEdit",
607
- "ptv",
608
- "botInvoke",
609
- "callLog",
610
- "encComment",
611
- "bcall",
612
- "lottieSticker",
613
- "event",
614
- "comment",
615
- "placeholder",
616
- "encEventUpdate"
617
- ]);
618
- var MessagesDeviceEnumType = zod.z.enum([
619
- "unknown",
620
- "android",
621
- "ios",
622
- "desktop",
623
- "web"
624
- ]);
625
- var ExtractorMessagesType = zod.z.object({
626
- chatId: zod.z.string(),
627
- channelId: zod.z.string(),
628
- uniqueId: zod.z.string(),
629
- receiverId: zod.z.string(),
630
- receiverName: zod.z.string(),
631
- roomId: zod.z.string(),
632
- roomName: zod.z.string(),
633
- senderLid: zod.z.string(),
634
- senderId: zod.z.string(),
635
- senderName: zod.z.string(),
636
- senderDevice: MessagesDeviceEnumType,
637
- chatType: MessagesEnumType,
638
- timestamp: zod.z.number(),
639
- text: zod.z.string().nullable(),
640
- mentions: zod.z.string().array(),
641
- links: zod.z.string().array(),
642
- isPrefix: zod.z.boolean(),
643
- isSpam: zod.z.boolean(),
644
- isFromMe: zod.z.boolean(),
645
- isTagMe: zod.z.boolean(),
646
- isGroup: zod.z.boolean(),
647
- isStory: zod.z.boolean(),
648
- isViewOnce: zod.z.boolean(),
649
- isEdited: zod.z.boolean(),
650
- isDeleted: zod.z.boolean(),
651
- isPinned: zod.z.boolean(),
652
- isUnPinned: zod.z.boolean(),
653
- isChannel: zod.z.boolean(),
654
- isBroadcast: zod.z.boolean(),
655
- isEphemeral: zod.z.boolean(),
656
- isForwarded: zod.z.boolean(),
657
- citation: zod.z.record(zod.z.string(), zod.z.boolean()).nullable(),
658
- media: zod.z.object({
659
- buffer: zod.z.function(),
660
- stream: zod.z.function()
661
- }).loose().nullable(),
662
- message: zod.z.function({
663
- input: [],
664
- output: zod.z.record(zod.z.string(), zod.z.any())
665
- }),
666
- get replied() {
667
- return ExtractorMessagesType.nullable();
668
- }
669
- });
670
- var limiterCache = new NodeCache2__default.default({ stdTTL: 60 * 60 });
671
- var LimiterHandler = async (key, max, ms) => {
672
- try {
673
- if (max <= 0) {
674
- return false;
675
- }
676
- const state = limiterCache.get(key);
677
- const now = Date.now();
678
- if (!state || now - state.firstRequestTime > ms) {
679
- const newState2 = {
680
- count: 1,
681
- firstRequestTime: now
682
- };
683
- limiterCache.set(key, newState2, Math.ceil(ms / 1e3) + 10);
684
- return false;
685
- }
686
- const newState = {
687
- count: state.count + 1,
688
- firstRequestTime: state.firstRequestTime
689
- };
690
- limiterCache.set(key, newState, Math.ceil((ms - (now - state.firstRequestTime)) / 1e3) + 10);
691
- if (newState.count > max) {
692
- return true;
693
- }
694
- return false;
695
- } catch (err) {
696
- console.error("Error detecting spam:", err);
697
- return false;
698
- }
699
- };
700
-
701
- // src/extractor/messages.ts
702
- var MessagesExtractor = async (client, message, isExtract) => {
703
- let MAX_REPLIES = 0;
704
- const CLONE = message;
705
- const extract = async (obj, isReplied) => {
706
- let msg = toJson(obj);
707
- if (!msg.message || !msg?.key?.id) {
708
- return null;
709
- }
710
- if (msg?.messageStubType || !!msg?.messageStubParameters || msg?.message?.botInvokeMessage || msg.message?.protocolMessage?.peerDataOperationRequestResponseMessage) {
711
- return null;
712
- }
713
- if (msg?.key?.fromMe && msg?.key?.remoteJid != "status@broadcast" && client.props?.ignoreMe && !MAX_REPLIES && !isExtract) {
714
- return null;
715
- }
716
- const pinId = msg?.message?.pinInChatMessage?.key?.id;
717
- const isPinned = msg?.message?.pinInChatMessage?.type == 1;
718
- const isUnPinned = msg?.message?.pinInChatMessage?.type == 2;
719
- if (pinId && client.db) {
720
- const read = await client.db.store("messages").read(pinId);
721
- msg = read;
722
- }
723
- const protocolId = !msg?.message?.protocolMessage?.editedMessage && msg?.message?.protocolMessage?.key?.id;
724
- const isDeleted = !!protocolId;
725
- if (protocolId && client.db) {
726
- const read = await client.db.store("messages").read(protocolId);
727
- msg = read;
728
- }
729
- const edited = msg?.message?.protocolMessage?.editedMessage || msg?.message?.editedMessage;
730
- if (edited) {
731
- const id = edited?.message?.protocolMessage?.key?.id;
732
- if (id && client.db) {
733
- const read3 = await client.db.store("messages").read(id);
734
- const editType = makeWASocket.getContentType(edited?.message?.protocolMessage?.editedMessage);
735
- const readType = makeWASocket.getContentType(read3?.message);
736
- let editing = void 0;
737
- if (editType && edited?.message?.protocolMessage?.editedMessage) {
738
- editing = edited.message.protocolMessage.editedMessage[editType];
739
- if (readType && read3?.message) {
740
- read3.message[readType] = _2__default.default.merge(read3.message[readType], editing);
741
- }
742
- }
743
- msg = read3 || msg;
744
- }
745
- }
746
- const contentType = makeWASocket.getContentType(msg?.message?.protocolMessage?.editedMessage || msg?.message);
747
- if (!contentType) return null;
748
- const payload = {};
749
- payload.chatId = msg?.message?.protocolMessage?.key?.id || msg?.key?.id || "";
750
- payload.channelId = "";
751
- payload.uniqueId = "";
752
- payload.receiverId = makeWASocket.jidNormalizedUser(client.socket?.user?.id || "");
753
- payload.receiverName = client.socket?.user?.name || client.socket?.user?.verifiedName || "";
754
- payload.roomId = makeWASocket.jidNormalizedUser(message?.key?.remoteJid || "");
755
- if (client.db) {
756
- const roomName = await client.db.store("chats").read(payload.roomId);
757
- payload.roomName = toJson(roomName)?.name || "";
758
- }
759
- payload.senderLid = msg?.message?.protocolMessage?.key?.senderLid || msg?.key?.senderLid || msg?.key?.participantLid || "";
760
- payload.senderId = makeWASocket.jidNormalizedUser(msg?.participant || msg?.key?.participant || msg?.key?.remoteJid);
761
- if (client.db) {
762
- const senderName = await client.db.store("chats").read(payload.senderId);
763
- payload.senderLid = payload.senderLid || toJson(senderName)?.lidJid || "";
764
- payload.senderName = msg?.pushName || msg?.verifiedBizName || toJson(senderName)?.name || payload.receiverName;
765
- }
766
- payload.senderDevice = makeWASocket.getDevice(payload.chatId);
767
- if (payload.senderId == payload.receiverId) {
768
- payload.senderName = payload.receiverName;
769
- }
770
- payload.roomName = payload.roomName || payload.senderName || _2__default.default.split(payload.roomId || "", "@")[0];
771
- payload.roomName = normalizeText(payload.roomName);
772
- payload.chatType = MessagesMediaType[contentType];
773
- payload.timestamp = Number(msg?.messageTimestamp || 0);
774
- payload.text = null;
775
- payload.mentions = [];
776
- payload.links = [];
777
- payload.isPrefix = false;
778
- payload.isSpam = false;
779
- payload.isFromMe = message?.key?.fromMe || false;
780
- payload.isTagMe = false;
781
- payload.isGroup = _2__default.default.includes(payload.roomId, "@g.us");
782
- payload.isStory = _2__default.default.includes(payload.roomId, "@broadcast");
783
- payload.isViewOnce = false;
784
- payload.isEdited = false;
785
- payload.isDeleted = isDeleted;
786
- payload.isPinned = isPinned;
787
- payload.isUnPinned = isUnPinned;
788
- payload.isChannel = _2__default.default.includes(payload.roomId, "@newsletter");
789
- payload.isBroadcast = !!message?.broadcast;
790
- payload.isEphemeral = false;
791
- payload.isForwarded = false;
792
- if (!isReplied && !isExtract) {
793
- const limiter = await LimiterHandler(payload.roomId, client.props.limiter?.maxMessages || 3, client.props.limiter?.durationMs || 5e3);
794
- payload.isSpam = limiter;
795
- }
796
- payload.receiverName = normalizeText(payload.receiverName);
797
- payload.senderName = normalizeText(payload.senderName);
798
- payload.citation = null;
799
- payload.media = null;
800
- payload.replied = null;
801
- payload.channelId = _2__default.default.join([_2__default.default.split(payload.roomId, "@")[0], _2__default.default.split(payload.senderId, "@")[0]], "-");
802
- payload.uniqueId = _2__default.default.join([payload.channelId, payload.chatId], "-");
803
- const citation = client.props?.citation || {};
804
- if (Object.keys(citation).length) {
805
- payload.citation = {};
806
- for (const key of Object.keys(citation)) {
807
- const slug = "is" + _2__default.default.upperFirst(_2__default.default.camelCase(key));
808
- const citationEntry = citation[key];
809
- if (citationEntry && Array.isArray(citationEntry)) {
810
- const senderId = payload.senderId.split("@")[0];
811
- const roomId = payload.roomId.split("@")[0];
812
- const citationRecord = citation;
813
- payload.citation[slug] = (senderId ? (citationRecord[key] || []).includes(Number(senderId)) : false) || (roomId ? (citationRecord[key] || []).includes(Number(roomId)) : false);
814
- }
815
- }
816
- }
817
- const media = msg?.message?.editedMessage?.[contentType] || msg?.message?.protocolMessage?.editedMessage?.[contentType] || msg?.message?.[contentType]?.message?.documentMessage || msg?.message?.[contentType];
818
- if (payload.chatType != "text") {
819
- payload.media = {
820
- ..._2__default.default.omit(media, [
821
- "url",
822
- "contextInfo",
823
- "fileSha256",
824
- "fileEncSha256",
825
- "mediaKey",
826
- "directPath",
827
- "waveform",
828
- "thumbnail",
829
- "jpegThumbnail",
830
- "thumbnailEncSha256",
831
- "thumbnailSha256",
832
- "thumbnailDirectPath",
833
- "firstFrameSidecar",
834
- "streamingSidecar",
835
- "scansSidecar",
836
- "callKey",
837
- "message",
838
- "key",
839
- "midQualityFileSha256"
840
- ]),
841
- buffer: () => makeWASocket.downloadMediaMessage(msg, "buffer", {}),
842
- stream: () => makeWASocket.downloadMediaMessage(msg, "stream", {})
843
- };
844
- }
845
- const repliedContext = toJson(msg?.message?.[contentType])?.contextInfo;
846
- const repliedId = repliedContext?.stanzaId;
847
- if (repliedId && MAX_REPLIES < 1 && client.db) {
848
- MAX_REPLIES++;
849
- const replied = await client.db.store("messages").read(repliedId);
850
- if (!replied) {
851
- payload.replied = await extract(msg, true);
852
- } else {
853
- payload.replied = await extract(replied, true);
854
- }
855
- MAX_REPLIES = 0;
856
- }
857
- const text = typeof media == "string" ? media : media?.text || media?.caption || media?.name || media?.displayName || media?.conversation || media?.contentText || media?.selectedDisplayText || "";
858
- payload.text = normalizeText(text) || "";
859
- payload.mentions = getMentions(payload.text || "");
860
- payload.links = extractUrls(payload.text || "");
861
- const messaging = toJson(msg?.message?.[contentType]);
862
- payload.isPrefix = !!(client.props?.prefix && _2__default.default.startsWith(payload.text, client.props?.prefix));
863
- payload.isTagMe = _2__default.default.includes(payload.mentions, _2__default.default.split(payload.receiverId, "@")[0] || "");
864
- payload.isEdited = !!edited;
865
- payload.isEphemeral = !!findWord(toString(messaging?.contextInfo), "ephemeralSettingTimestamp");
866
- payload.isForwarded = !!findWord(toString(messaging?.contextInfo), "forwardingScore");
867
- payload.isViewOnce = !!messaging?.viewOnce;
868
- if (payload.isPrefix) {
869
- payload.text = _2__default.default.replace(payload.text, new RegExp(`^${client.props?.prefix}`), "");
870
- }
871
- if (isReplied && payload?.receiverId != payload?.senderId) {
872
- payload.isFromMe = false;
873
- }
874
- if (isReplied && payload?.receiverId == payload?.senderId) {
875
- payload.isFromMe = true;
876
- }
877
- payload.message = () => CLONE;
878
- return payload;
879
- };
880
- return extract(message);
881
- };
882
- var Listener = class {
883
- client;
884
- async bind(client, db) {
885
- this.client = client;
886
- this.client.db = db;
887
- this.client.socket?.ev.on("connection.update", async (update) => {
888
- await this.connection(update);
889
- });
890
- this.client.socket?.ev.on("messages.upsert", async ({ messages }) => {
891
- for (const message of messages) {
892
- await this.messages(message);
893
- }
894
- });
895
- this.client.socket?.ev.on("call", async (callers) => {
896
- for (const caller of callers) {
897
- await this.calls(caller);
898
- }
899
- });
900
- this.client.socket?.ev.on("creds.update", () => {
901
- });
902
- if (this.client.socket?.ws) {
903
- const originalEmit = this.client.socket.ws.emit.bind(this.client.socket.ws);
904
- this.client.socket.ws.emit = (event, ...args) => {
905
- if (event === "error" && args[0]) {
906
- const errorMessage = args[0].message || args[0]?.toString();
907
- if (_2__default.default.includes(errorMessage, "Closing open session in favor of incoming prekey bundle") || _2__default.default.includes(errorMessage, "Closing stale open session for new outgoing prekey bundle") || _2__default.default.includes(errorMessage, "Closing session: SessionEntry")) {
908
- this.handleSessionClosing();
909
- }
910
- }
911
- return originalEmit(event, ...args);
912
- };
913
- }
914
- }
915
- async handleSessionClosing() {
916
- this.client.spinner.start("Processing session changes...");
917
- await makeWASocket.delay(3e3);
918
- this.client.spinner.success("Session processing completed");
919
- }
920
- async connection(update) {
921
- const { connection, lastDisconnect, qr } = update;
922
- this.client.emit("connection", { status: "connecting" });
923
- if (this.client.props.authType === "qr" && qr) {
924
- this.client.spinner.info(`Please scan the QR
925
-
926
- ${await QRCode__default.default.toString(qr, { type: "terminal", small: true })}`);
927
- return;
928
- }
929
- if (connection === "close") {
930
- const code = toJson(lastDisconnect?.error)?.output?.statusCode;
931
- const errorMessage = lastDisconnect?.error?.message || "";
932
- const isReconnect = typeof code === "number" && code !== makeWASocket.DisconnectReason.loggedOut;
933
- if (_2__default.default.includes(errorMessage, "Closing open session in favor of incoming prekey bundle") || _2__default.default.includes(errorMessage, "Closing stale open session for new outgoing prekey bundle") || _2__default.default.includes(errorMessage, "Closing session: SessionEntry")) {
934
- this.client.spinner.start("Processing session changes...");
935
- await new Promise((resolve) => setTimeout(resolve, 2e3));
936
- this.client.spinner.success("Session processing completed");
937
- return;
938
- }
939
- this.client.spinner.error(`[Connection Closed] [${code}] ${errorMessage}`);
940
- if (code === 401 || code === 405 || code === 500) {
941
- this.client.spinner.error("Invalid session, please delete manually");
942
- this.client.spinner.error(`Session "${this.client.props.session}" has not valid, please delete it`);
943
- return;
944
- }
945
- if (isReconnect) {
946
- this.client.spinner.warn("Connection lost. Attempting auto-reload...");
947
- const clientRecord = this.client;
948
- if (typeof clientRecord.autoReload === "function") {
949
- await clientRecord.autoReload();
950
- }
951
- }
952
- } else if (connection === "open") {
953
- if (this.client.socket?.user) {
954
- const id = makeWASocket.jidNormalizedUser(this.client.socket.user.id).split("@")[0];
955
- const name = this.client.socket.user.name || this.client.socket.user.verifiedName;
956
- const clientRecord = this.client;
957
- if (typeof clientRecord.resetRetryCount === "function") {
958
- clientRecord.resetRetryCount();
959
- }
960
- this.client.spinner.success(`Connected as ${chalk__default.default.green(name || id)}`);
961
- this.client.emit("connection", { status: "open" });
962
- }
963
- }
964
- }
965
- async messages(message) {
966
- if (this.client.props?.autoRead && this.client.socket) {
967
- if (message?.key) {
968
- await this.client.socket.readMessages([message.key]);
969
- }
970
- }
971
- const extract = await MessagesExtractor(this.client, message);
972
- if (extract) {
973
- this.client.emit("messages", extract);
974
- }
975
- }
976
- async calls(caller) {
977
- if (this.client.props?.autoRejectCall && this.client.socket) {
978
- await this.client.socket.rejectCall(caller.id, caller.from);
979
- }
980
- const extract = await CallsExtractor(this.client, caller);
981
- this.client.emit("calls", extract);
982
- }
983
- };
984
- var RelayTextType = z2.z.string().or(z2.z.object({
985
- text: z2.z.string(),
986
- roomId: z2.z.string().optional(),
987
- options: z2.z.custom().optional(),
988
- externalAdReply: AdsReplyType.optional()
989
- }));
990
- var RelayReplyType = z2.z.string().or(
991
- z2.z.object({
992
- text: z2.z.string(),
993
- roomId: z2.z.string().optional(),
994
- options: z2.z.custom().optional(),
995
- externalAdReply: AdsReplyType.optional()
996
- })
997
- );
998
- var RelayForwardType = z2.z.string().or(
999
- z2.z.object({
1000
- text: z2.z.string(),
1001
- isForwardMany: defaultBoolean(false),
1002
- roomId: z2.z.string().optional(),
1003
- options: z2.z.custom().optional(),
1004
- externalAdReply: AdsReplyType.optional()
1005
- })
1006
- );
1007
- var RelayImageEnumType = z2.z.enum(["text", "reply", "forward"]);
1008
- var RelayImageType = z2.z.object({
1009
- image: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
1010
- text: z2.z.string().optional(),
1011
- viewOnce: defaultBoolean(false),
1012
- roomId: z2.z.string().optional(),
1013
- externalAdReply: AdsReplyType.optional()
1014
- });
1015
- var RelayVideoEnumType = z2.z.enum(["text", "reply", "forward"]);
1016
- var RelayVideoType = z2.z.object({
1017
- video: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
1018
- text: z2.z.string().optional(),
1019
- viewOnce: defaultBoolean(false),
1020
- roomId: z2.z.string().optional()
1021
- });
1022
- var RelayAudioEnumType = z2.z.enum(["text", "reply", "forward"]);
1023
- var RelayAudioType = z2.z.object({
1024
- audio: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
1025
- viewOnce: defaultBoolean(false),
1026
- roomId: z2.z.string().optional(),
1027
- externalAdReply: AdsReplyType.optional()
1028
- });
1029
- var RelayStickerEnumType = z2.z.enum(["text", "reply", "forward"]);
1030
- var RelayStickerType = z2.z.object({
1031
- sticker: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
1032
- roomId: z2.z.string().optional()
1033
- });
1034
- var RelayEditType = z2.z.object({
1035
- text: z2.z.string(),
1036
- message: z2.z.function({
1037
- input: [],
1038
- output: z2.z.any()
1039
- }).optional()
1040
- });
1041
- var RelayDeleteType = z2.z.object({
1042
- message: z2.z.function({
1043
- input: [],
1044
- output: z2.z.any()
1045
- }).optional()
1046
- });
1047
- var ExtractorCallsType = z2.z.object({
1048
- callId: z2.z.string(),
1049
- roomId: z2.z.string(),
1050
- callerId: z2.z.string(),
1051
- date: z2.z.date(),
1052
- offline: z2.z.boolean(),
1053
- status: z2.z.enum(["accept", "offer", "reject", "ringing", "terminate", "timeout"]),
1054
- isVideo: z2.z.boolean(),
1055
- isGroup: z2.z.boolean()
1056
- });
1057
-
1058
- // src/types/relay/reject.ts
1059
- var RelayRejectType = ExtractorCallsType.pick({
1060
- callId: true,
1061
- callerId: true
1062
- });
1063
- var RelayPresenceType = z2.z.enum(["typing", "recording", "online", "offline", "paused"]);
1064
- var RelayReactionType = z2.z.emoji().or(
1065
- z2.z.object({
1066
- emoticon: z2.z.emoji(),
1067
- message: z2.z.function({
1068
- input: [],
1069
- output: z2.z.any()
1070
- }).optional()
1071
- })
1072
- );
1073
- var RelayLocationEnumType = z2.z.enum(["text", "reply", "forward"]);
1074
- var RelayLocationType = z2.z.object({
1075
- latitude: z2.z.number(),
1076
- longitude: z2.z.number(),
1077
- title: z2.z.string().optional(),
1078
- footer: z2.z.string().optional(),
1079
- roomId: z2.z.string().optional(),
1080
- externalAdReply: AdsReplyType.optional()
1081
- });
1082
- var RelayContactEnumType = z2.z.enum(["text", "reply", "forward"]);
1083
- var RelayContactType = z2.z.object({
1084
- title: z2.z.string().optional(),
1085
- contacts: z2.z.object({
1086
- fullname: z2.z.string(),
1087
- nickname: z2.z.string().optional(),
1088
- organization: z2.z.string().optional(),
1089
- phoneNumber: z2.z.number(),
1090
- website: z2.z.url().optional()
1091
- }).array(),
1092
- roomId: z2.z.string().optional()
1093
- });
1094
- var RelayPollEnumType = z2.z.enum(["text", "reply", "forward"]);
1095
- var RelayPollCreateType = z2.z.object({
1096
- action: z2.z.literal("create"),
1097
- name: z2.z.string(),
1098
- answers: z2.z.string().array(),
1099
- isMultiple: defaultBoolean(false),
1100
- roomId: z2.z.string().optional()
1101
- });
1102
- z2.z.object({
1103
- action: z2.z.literal("result"),
1104
- name: z2.z.string(),
1105
- votes: z2.z.tuple([z2.z.string(), z2.z.number()]).array(),
1106
- roomId: z2.z.string().optional()
1107
- });
1108
- var RelayPollType = z2.z.discriminatedUnion("action", [RelayPollCreateType]);
1109
- var RelayDocumentEnumType = z2.z.enum(["text", "reply", "forward"]);
1110
- var RelayDocumentType = z2.z.object({
1111
- document: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
1112
- mimetype: z2.z.string(),
1113
- text: z2.z.string().optional(),
1114
- fileName: z2.z.string().optional(),
1115
- roomId: z2.z.string().optional(),
1116
- externalAdReply: AdsReplyType.optional()
1117
- });
1118
- var RelayButtonEnumType = z2.z.enum(["text", "reply", "forward"]);
1119
- var RelayButtonSimpleType = z2.z.object({
1120
- type: z2.z.literal("simple"),
1121
- text: z2.z.string(),
1122
- footer: z2.z.string().optional(),
1123
- buttons: z2.z.object({
1124
- id: z2.z.string(),
1125
- text: z2.z.string()
1126
- }).array(),
1127
- roomId: z2.z.string().optional(),
1128
- externalAdReply: AdsReplyType.optional()
1129
- });
1130
- var RelayButtonInteractiveReplyType = z2.z.object({
1131
- type: z2.z.literal("quick_reply"),
1132
- id: z2.z.string(),
1133
- text: z2.z.string()
1134
- });
1135
- var RelayButtonInteractiveUrlType = z2.z.object({
1136
- type: z2.z.literal("cta_url"),
1137
- id: z2.z.string(),
1138
- url: z2.z.url(),
1139
- text: z2.z.string()
1140
- });
1141
- var RelayButtonInteractiveCopyType = z2.z.object({
1142
- type: z2.z.literal("cta_copy"),
1143
- id: z2.z.string(),
1144
- copy: z2.z.string(),
1145
- text: z2.z.string()
1146
- });
1147
- var RelayButtonInteractiveCallType = z2.z.object({
1148
- type: z2.z.literal("cta_call"),
1149
- id: z2.z.string(),
1150
- phoneNumber: z2.z.string(),
1151
- text: z2.z.string()
1152
- });
1153
- var RelayButtonInteractiveType = z2.z.object({
1154
- type: z2.z.literal("interactive"),
1155
- text: z2.z.string(),
1156
- footer: z2.z.string().optional(),
1157
- buttons: z2.z.discriminatedUnion("type", [RelayButtonInteractiveReplyType, RelayButtonInteractiveUrlType, RelayButtonInteractiveCopyType, RelayButtonInteractiveCallType]).array(),
1158
- roomId: z2.z.string().optional(),
1159
- externalAdReply: AdsReplyType.optional()
1160
- });
1161
- z2.z.object({
1162
- type: z2.z.literal("list"),
1163
- text: z2.z.string(),
1164
- footer: z2.z.string(),
1165
- roomId: z2.z.string().optional(),
1166
- externalAdReply: AdsReplyType.optional()
1167
- });
1168
- var RelayButtonType = z2.z.discriminatedUnion("type", [RelayButtonSimpleType, RelayButtonInteractiveType]);
1169
- var RelayGroupCreateType = z2.z.object({
1170
- title: z2.z.string(),
1171
- members: z2.z.string().array()
1172
- });
1173
- var RelayGroupActionType = z2.z.object({
1174
- roomId: z2.z.string(),
1175
- action: z2.z.enum(["add", "kick", "promote", "demote"]),
1176
- members: z2.z.string().array()
1177
- });
1178
- var RelayGroupUpdateType = z2.z.object({
1179
- roomId: z2.z.string(),
1180
- text: z2.z.string(),
1181
- action: z2.z.enum(["subject", "description"])
1182
- });
1183
- var RelayGroupSettingsType = z2.z.object({
1184
- roomId: z2.z.string(),
1185
- action: z2.z.enum(["open", "close", "lock", "unlock"])
1186
- });
1187
- var RelayGroupLeaveType = z2.z.object({
1188
- roomId: z2.z.string()
1189
- });
1190
- var RelayGroupLinksType = z2.z.object({
1191
- roomId: z2.z.string(),
1192
- action: z2.z.enum(["get", "revoke"])
1193
- });
1194
- var RelayGroupInviteType = z2.z.object({
1195
- url: z2.z.url().regex(/^https:\/\/chat\.whatsapp\.com\/[A-Za-z0-9_-]{5,}$/),
1196
- action: z2.z.enum(["join", "info"])
1197
- });
1198
- var RelayGroupRequestsListType = z2.z.object({
1199
- roomId: z2.z.string()
1200
- });
1201
- var RelayGroupRequestsApproveType = z2.z.object({
1202
- roomId: z2.z.string(),
1203
- members: z2.z.string().array()
1204
- });
1205
- var RelayGroupRequestsRejectType = z2.z.object({
1206
- roomId: z2.z.string(),
1207
- members: z2.z.string().array()
1208
- });
1209
- var RelayGroupMetadataType = z2.z.object({
1210
- roomId: z2.z.string()
1211
- });
1212
- var RelayPrivacyUpdateControlType = z2.z.object({
1213
- action: z2.z.literal("control"),
1214
- type: z2.z.enum(["block", "unblock"]),
1215
- senderId: z2.z.string()
1216
- });
1217
- var RelayPrivacyUpdateLastSeenType = z2.z.object({
1218
- action: z2.z.literal("lastSeen"),
1219
- type: z2.z.enum(["all", "contacts", "contact_blacklist", "none"])
1220
- });
1221
- var RelayPrivacyUpdateOnlineType = z2.z.object({
1222
- action: z2.z.literal("online"),
1223
- type: z2.z.enum(["all", "match_last_seen"])
1224
- });
1225
- var RelayPrivacyUpdateAvatarType = z2.z.object({
1226
- action: z2.z.literal("avatar"),
1227
- type: z2.z.enum(["all", "contacts", "contact_blacklist", "none"])
1228
- });
1229
- var RelayPrivacyUpdateStoryType = z2.z.object({
1230
- action: z2.z.literal("story"),
1231
- type: z2.z.enum(["all", "contacts", "contact_blacklist", "none"])
1232
- });
1233
- var RelayPrivacyUpdateReadType = z2.z.object({
1234
- action: z2.z.literal("read"),
1235
- type: z2.z.enum(["all", "none"])
1236
- });
1237
- var RelayPrivacyGroupsAddType = z2.z.object({
1238
- action: z2.z.literal("groupsAdd"),
1239
- type: z2.z.enum(["all", "contacts", "contact_blacklist"])
1240
- });
1241
- var RelayPrivacyEphemeralType = z2.z.object({
1242
- action: z2.z.literal("ephemeral"),
1243
- type: z2.z.enum(["remove", "24h", "7d", "90d"])
1244
- });
1245
- var RelayPrivacyUpdateType = z2.z.discriminatedUnion("action", [
1246
- RelayPrivacyUpdateControlType,
1247
- RelayPrivacyUpdateLastSeenType,
1248
- RelayPrivacyUpdateOnlineType,
1249
- RelayPrivacyUpdateAvatarType,
1250
- RelayPrivacyUpdateStoryType,
1251
- RelayPrivacyUpdateReadType,
1252
- RelayPrivacyGroupsAddType,
1253
- RelayPrivacyEphemeralType
1254
- ]);
1255
- var RelayProfileBioType = z2.z.object({
1256
- senderId: z2.z.string()
1257
- });
1258
- var RelayProfileUpdateType = z2.z.object({
1259
- type: z2.z.enum(["name", "bio", "avatar"]),
1260
- text: z2.z.string().optional(),
1261
- roomId: z2.z.string().optional(),
1262
- avatar: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)).or(z2.z.literal("remove"))
1263
- });
1264
- var RelayProfileCheckType = z2.z.object({
1265
- senderId: z2.z.string()
1266
- });
1267
-
1268
- // src/classes/Relay.ts
1269
- var Relay = class {
1270
- client;
1271
- message;
1272
- db;
1273
- ctx;
1274
- bind(client, db) {
1275
- this.client = client;
1276
- this.db = db;
1277
- this.ctx = client;
1278
- this.ctx.db = db;
1279
- this.client.on("messages", (ctx) => {
1280
- this.message = ctx;
1281
- });
1282
- }
1283
- async initial(props) {
1284
- await makeWASocket.delay(0);
1285
- if (!props?.disabledPresence) {
1286
- if (this.client.props?.autoPresence) {
1287
- if (props?.isAudio) {
1288
- this.client.socket?.sendPresenceUpdate("recording", this.message?.roomId);
1289
- } else {
1290
- this.client.socket?.sendPresenceUpdate("composing", this.message?.roomId);
1291
- }
1292
- }
1293
- }
1294
- }
1295
- // GENERAL RELAY
1296
- async text(props) {
1297
- await this.initial();
1298
- const params = RelayTextType.parse(props);
1299
- let extend = { contextInfo: {} };
1300
- if (this.client.props.autoMentions) {
1301
- extend.contextInfo.mentionedJid = extractJids(this.message.text);
1302
- }
1303
- if (typeof params == "string") {
1304
- if (this.client.socket) {
1305
- const res = await this.client.socket.sendMessage(this.message?.roomId, {
1306
- text: params,
1307
- ...extend
1308
- });
1309
- return await MessagesExtractor(this.ctx, res, true);
1310
- }
1311
- }
1312
- if (typeof params == "object") {
1313
- const obj = { ...extend, ...params.options };
1314
- if (params.externalAdReply) {
1315
- obj.contextInfo = { externalAdReply: params.externalAdReply };
1316
- }
1317
- if (this.client.socket) {
1318
- if (params.text != "$$media$$") {
1319
- obj.text = params?.text;
1320
- }
1321
- const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj);
1322
- return await MessagesExtractor(this.ctx, res, true);
1323
- }
1324
- }
1325
- }
1326
- async reply(props) {
1327
- await this.initial();
1328
- const params = RelayReplyType.parse(props);
1329
- const quoted = this.message?.message();
1330
- let extend = { contextInfo: {} };
1331
- if (this.client.props.autoMentions) {
1332
- extend.contextInfo.mentionedJid = extractJids(this.message.text);
1333
- }
1334
- if (this.client.props?.fakeReply?.provider) {
1335
- const provider = this.client.props.fakeReply.provider;
1336
- if (quoted && quoted.key) {
1337
- quoted.key.remoteJid = MessagesVerifiedPlatformType[provider];
1338
- }
1339
- }
1340
- const options = quoted ? { quoted } : void 0;
1341
- if (typeof params == "string") {
1342
- if (this.client.socket) {
1343
- const res = await this.client.socket.sendMessage(this.message?.roomId, { text: params, ...extend }, options);
1344
- return await MessagesExtractor(this.ctx, res, true);
1345
- }
1346
- }
1347
- if (typeof params == "object") {
1348
- const obj = { ...extend, ...params.options };
1349
- if (params.externalAdReply) {
1350
- obj.contextInfo = { externalAdReply: params.externalAdReply };
1351
- }
1352
- if (this.client.socket) {
1353
- if (params.text != "$$media$$") {
1354
- obj.text = params?.text;
1355
- }
1356
- const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj, options);
1357
- return await MessagesExtractor(this.ctx, res, true);
1358
- }
1359
- }
1360
- }
1361
- async forward(props) {
1362
- await this.initial();
1363
- const params = RelayForwardType.parse(props);
1364
- const quoted = this.message?.message();
1365
- let extend = { contextInfo: { isForwarded: true } };
1366
- if (this.client.props.autoMentions) {
1367
- extend.contextInfo.mentionedJid = extractJids(this.message.text);
1368
- }
1369
- if (this.client.props?.fakeReply?.provider) {
1370
- const provider = this.client.props.fakeReply.provider;
1371
- if (quoted && quoted.key) {
1372
- quoted.key.remoteJid = MessagesVerifiedPlatformType[provider];
1373
- }
1374
- }
1375
- if (typeof params == "string") {
1376
- if (this.client.socket) {
1377
- const res = await this.client.socket.sendMessage(this.message?.roomId, { text: params, ...extend });
1378
- return await MessagesExtractor(this.ctx, res, true);
1379
- }
1380
- }
1381
- if (typeof params == "object") {
1382
- const obj = { ...extend, ...params.options };
1383
- if (params.externalAdReply) {
1384
- obj.contextInfo.externalAdReply = params.externalAdReply;
1385
- }
1386
- if (params.isForwardMany) {
1387
- extend.contextInfo.forwardingScore = 999999;
1388
- }
1389
- if (this.client.socket) {
1390
- if (params.text != "$$media$$") {
1391
- obj.text = params?.text;
1392
- }
1393
- const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj);
1394
- return await MessagesExtractor(this.ctx, res, true);
1395
- }
1396
- }
1397
- }
1398
- async edit(props) {
1399
- await this.initial({ disabledPresence: true });
1400
- const params = RelayEditType.parse(props);
1401
- const message = params.message();
1402
- const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { text: params.text, edit: message?.key });
1403
- return await MessagesExtractor(this.ctx, res, true);
1404
- }
1405
- async delete(props) {
1406
- await this.initial({ disabledPresence: true });
1407
- const params = RelayDeleteType.parse(props);
1408
- const message = params.message();
1409
- const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { delete: message?.key });
1410
- return await MessagesExtractor(this.ctx, res, true);
1411
- }
1412
- async reject(props) {
1413
- const params = RelayRejectType.parse(props);
1414
- return await this.client.socket.rejectCall(params.callId, params.callerId);
1415
- }
1416
- async presence(props) {
1417
- await this.initial({ disabledPresence: true });
1418
- const params = RelayPresenceType.parse(props);
1419
- const opts = {
1420
- typing: "composing",
1421
- recording: "recording",
1422
- online: "available",
1423
- offline: "unavailable",
1424
- paused: "paused"
1425
- };
1426
- return await this.client.socket.sendPresenceUpdate(opts[params], this.message.roomId);
1427
- }
1428
- async reaction(props) {
1429
- await this.initial({ disabledPresence: true });
1430
- const params = RelayReactionType.parse(props);
1431
- const message = typeof params == "string" ? this.message.message() : params.message();
1432
- const text = typeof params == "string" ? params : params.emoticon;
1433
- const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { react: { text, key: message?.key } });
1434
- return await MessagesExtractor(this.ctx, res, true);
1435
- }
1436
- // MEDIA RELAY
1437
- async document(type, props) {
1438
- await this.initial();
1439
- const enumType = RelayDocumentEnumType.parse(type);
1440
- const params = RelayDocumentType.parse(props);
1441
- const options = {
1442
- document: typeof params.document === "string" ? { url: params.document } : params.document,
1443
- caption: params.text,
1444
- mimetype: params.mimetype,
1445
- fileName: params.fileName,
1446
- contextInfo: { externalAdReply: params.externalAdReply }
1447
- };
1448
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1449
- }
1450
- async image(type, props) {
1451
- await this.initial();
1452
- const enumType = RelayImageEnumType.parse(type);
1453
- const params = RelayImageType.parse(props);
1454
- const options = {
1455
- image: typeof params.image === "string" ? { url: params.image } : params.image,
1456
- jpegThumbnail: params.image,
1457
- caption: params.text,
1458
- viewOnce: params.viewOnce,
1459
- contextInfo: { externalAdReply: params.externalAdReply, isQuestion: true }
1460
- };
1461
- return this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1462
- }
1463
- async sticker(type, props) {
1464
- await this.initial();
1465
- const enumType = RelayStickerEnumType.parse(type);
1466
- const params = RelayStickerType.parse(props);
1467
- const options = { sticker: typeof params.sticker === "string" ? { url: params.sticker } : params.sticker };
1468
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1469
- }
1470
- async video(type, props) {
1471
- await this.initial();
1472
- const enumType = RelayVideoEnumType.parse(type);
1473
- const params = RelayVideoType.parse(props);
1474
- const options = {
1475
- video: typeof params.video === "string" ? { url: params.video } : params.video,
1476
- caption: params.text,
1477
- viewOnce: params.viewOnce
1478
- };
1479
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1480
- }
1481
- async audio(type, props) {
1482
- const enumType = RelayAudioEnumType.parse(type);
1483
- const params = RelayAudioType.parse(props);
1484
- const options = {
1485
- audio: typeof params.audio === "string" ? { url: params.audio } : params.audio,
1486
- viewOnce: params.viewOnce,
1487
- contextInfo: { externalAdReply: params.externalAdReply }
1488
- };
1489
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1490
- }
1491
- async voice(type, props) {
1492
- const enumType = RelayAudioEnumType.parse(type);
1493
- const params = RelayAudioType.parse(props);
1494
- const options = {
1495
- audio: typeof params.audio === "string" ? { url: params.audio } : params.audio,
1496
- ptt: true,
1497
- viewOnce: params.viewOnce,
1498
- mimetype: "audio/ogg; codecs=opus",
1499
- contextInfo: { externalAdReply: params.externalAdReply }
1500
- };
1501
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1502
- }
1503
- async note(type, props) {
1504
- await this.initial();
1505
- const enumType = RelayVideoEnumType.parse(type);
1506
- const params = RelayVideoType.parse(props);
1507
- const options = { video: typeof params.video === "string" ? { url: params.video } : params.video, caption: params.text, ptv: true };
1508
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1509
- }
1510
- async gif(type, props) {
1511
- await this.initial();
1512
- const enumType = RelayVideoEnumType.parse(type);
1513
- const params = RelayVideoType.parse(props);
1514
- const options = { video: typeof params.video === "string" ? { url: params.video } : params.video, gifPlayback: true };
1515
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1516
- }
1517
- async location(type, props) {
1518
- await this.initial();
1519
- const enumType = RelayLocationEnumType.parse(type);
1520
- const params = RelayLocationType.parse(props);
1521
- const options = {
1522
- location: {
1523
- degreesLatitude: params.latitude,
1524
- degreesLongitude: params.longitude,
1525
- url: params.title,
1526
- address: params.footer,
1527
- name: params.title
1528
- },
1529
- contextInfo: { externalAdReply: params.externalAdReply }
1530
- };
1531
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1532
- }
1533
- async contacts(type, props) {
1534
- await this.initial();
1535
- const enumType = RelayContactEnumType.parse(type);
1536
- const params = RelayContactType.parse(props);
1537
- const contacts = params.contacts.map((x) => {
1538
- const vcard = [
1539
- "BEGIN:VCARD",
1540
- "VERSION:3.0",
1541
- `FN:${x.fullname}`,
1542
- `ORG:${x.organization || ""}`,
1543
- `TEL;type=CELL;type=VOICE;waid=${x.phoneNumber}:${x.phoneNumber}`,
1544
- "END:VCARD"
1545
- ].join("\n");
1546
- return { displayName: x.fullname, vcard };
1547
- });
1548
- const options = {
1549
- contacts: {
1550
- displayName: params?.title,
1551
- contacts
1552
- }
1553
- };
1554
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1555
- }
1556
- async poll(type, props) {
1557
- await this.initial();
1558
- const enumType = RelayPollEnumType.parse(type);
1559
- const params = RelayPollType.parse(props);
1560
- const options = {};
1561
- if (params.action == "create") {
1562
- options.poll = {
1563
- name: params.name,
1564
- values: params.answers,
1565
- selectableCount: !!params.isMultiple ? 1 : 0,
1566
- toAnnouncementGroup: true
1567
- };
1568
- }
1569
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1570
- }
1571
- async button(type, props) {
1572
- await this.initial();
1573
- const enumType = RelayButtonEnumType.parse(type);
1574
- const params = RelayButtonType.parse(props);
1575
- const options = {
1576
- text: params.text,
1577
- footer: params.footer,
1578
- contextInfo: { externalAdReply: params.externalAdReply }
1579
- };
1580
- if (params.type == "simple") {
1581
- options.buttons = params.buttons.map((x) => ({ buttonId: x.id, buttonText: { displayText: x.text } }));
1582
- }
1583
- if (params.type == "interactive") {
1584
- options.interactiveButtons = params.buttons.map((x) => {
1585
- let schema = { name: x.type };
1586
- if (x.type == "quick_reply") {
1587
- schema.buttonParamsJson = toString({
1588
- id: x.id,
1589
- display_text: x.text
1590
- });
1591
- }
1592
- if (x.type == "cta_url") {
1593
- schema.buttonParamsJson = toString({
1594
- id: x.id,
1595
- display_text: x.text,
1596
- url: x.url,
1597
- merchant_url: x.url
1598
- });
1599
- }
1600
- if (x.type == "cta_copy") {
1601
- schema.buttonParamsJson = toString({
1602
- id: x.id,
1603
- display_text: x.text,
1604
- copy_code: x.copy
1605
- });
1606
- }
1607
- if (x.type == "cta_call") {
1608
- schema.buttonParamsJson = toString({
1609
- id: x.id,
1610
- display_text: x.text,
1611
- phone_number: x.phoneNumber
1612
- });
1613
- }
1614
- return schema;
1615
- });
1616
- }
1617
- this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
1618
- }
1619
- // GROUP RELAY
1620
- group() {
1621
- const client = this.ctx;
1622
- const create = async (props) => {
1623
- const params = RelayGroupCreateType.parse(props);
1624
- try {
1625
- return await client.socket.groupCreate(params.title, params.members);
1626
- } catch (error) {
1627
- client.spinner.error("Failed create group. Make sure members has valid number.\n\n" + error);
1628
- return null;
1629
- }
1630
- };
1631
- const action = async (props) => {
1632
- const params = RelayGroupActionType.parse(props);
1633
- const opts = {
1634
- add: "add",
1635
- kick: "remove",
1636
- promote: "promote",
1637
- demote: "demote"
1638
- };
1639
- try {
1640
- return await client.socket.groupParticipantsUpdate(params.roomId, params.members, opts[params.action]);
1641
- } catch (error) {
1642
- client.spinner.error("Failed update user. Make sure this number is in the group and as admin.\n\n" + error);
1643
- return null;
1644
- }
1645
- };
1646
- const update = async (props) => {
1647
- const params = RelayGroupUpdateType.parse(props);
1648
- const opts = {
1649
- subject: "groupUpdateSubject",
1650
- description: "groupUpdateDescription"
1651
- };
1652
- try {
1653
- return await client.socket[opts[props.action]](params.roomId, props.text);
1654
- } catch (error) {
1655
- client.spinner.error("Failed update group. Make sure this number is in the group and as admin.\n\n" + error);
1656
- return null;
1657
- }
1658
- };
1659
- const settings = async (props) => {
1660
- const params = RelayGroupSettingsType.parse(props);
1661
- const opts = {
1662
- open: "not_announcement",
1663
- close: "announcement",
1664
- lock: "locked",
1665
- unlock: "unlocked"
1666
- };
1667
- try {
1668
- return await client.socket.groupSettingUpdate(params.roomId, opts[params.action]);
1669
- } catch (error) {
1670
- client.spinner.error("Failed settings group. Make sure this number is in the group and as admin.\n\n" + error);
1671
- return null;
1672
- }
1673
- };
1674
- const leave = async (props) => {
1675
- const params = RelayGroupLeaveType.parse(props);
1676
- try {
1677
- return await client.socket.groupLeave(params.roomId);
1678
- } catch (error) {
1679
- client.spinner.error("Failed leave group. Make sure this number is in the group.\n\n" + error);
1680
- return null;
1681
- }
1682
- };
1683
- const links = async (props) => {
1684
- const params = RelayGroupLinksType.parse(props);
1685
- const opts = {
1686
- get: "groupInviteCode",
1687
- revoke: "groupRevokeInvite"
1688
- };
1689
- try {
1690
- const code = await client.socket[opts[params.action]](params.roomId);
1691
- return `https://chat.whatsapp.com/` + code;
1692
- } catch (error) {
1693
- client.spinner.error("Failed get group link. Make sure this number is in the group and as admin.\n\n" + error);
1694
- return null;
1695
- }
1696
- };
1697
- const invite = async (props) => {
1698
- const params = RelayGroupInviteType.parse(props);
1699
- const opts = {
1700
- join: "groupAcceptInvite",
1701
- info: "groupGetInviteInfo"
1702
- };
1703
- try {
1704
- const code = params.url.split("https://chat.whatsapp.com/");
1705
- return await client.socket[opts[params.action]](code[1]);
1706
- } catch (error) {
1707
- client.spinner.error("Failed get group link. Make sure this number is in the group and as admin.\n\n" + error);
1708
- return null;
1709
- }
1710
- };
1711
- const metadata = async (props) => {
1712
- const params = RelayGroupMetadataType.parse(props);
1713
- try {
1714
- const meta = await client.socket.groupMetadata(params.roomId);
1715
- return meta;
1716
- } catch (error) {
1717
- client.spinner.error("Failed get group metadata. Make sure this number is in the group and as admin.\n\n" + error);
1718
- return null;
1719
- }
1720
- };
1721
- const requests = {
1722
- list: async (props) => {
1723
- const params = RelayGroupRequestsListType.parse(props);
1724
- return await client.socket.groupRequestParticipantsList(params.roomId);
1725
- },
1726
- approve: async (props) => {
1727
- const params = RelayGroupRequestsApproveType.parse(props);
1728
- return await client.socket.groupRequestParticipantsUpdate(params.roomId, params.members, "approve");
1729
- },
1730
- reject: async (props) => {
1731
- const params = RelayGroupRequestsRejectType.parse(props);
1732
- return await client.socket.groupRequestParticipantsUpdate(params.roomId, params.members, "reject");
1733
- }
1734
- };
1735
- return {
1736
- create,
1737
- action,
1738
- update,
1739
- settings,
1740
- leave,
1741
- links,
1742
- invite,
1743
- metadata,
1744
- requests
1745
- };
1746
- }
1747
- // PRIVACY RELAY
1748
- privacy() {
1749
- const client = this.ctx;
1750
- const update = async (props) => {
1751
- const params = RelayPrivacyUpdateType.parse(props);
1752
- try {
1753
- if (params.action == "control") {
1754
- return await client.socket.updateBlockStatus(params.senderId, params.type);
1755
- }
1756
- if (params.action == "lastSeen") {
1757
- return await client.socket.updateLastSeenPrivacy(params.type);
1758
- }
1759
- if (params.action == "online") {
1760
- return await client.socket.updateOnlinePrivacy(params.type);
1761
- }
1762
- if (params.action == "avatar") {
1763
- return await client.socket.updateProfilePicturePrivacy(params.type);
1764
- }
1765
- if (params.action == "story") {
1766
- return await client.socket.updateStatusPrivacy(params.type);
1767
- }
1768
- if (params.action == "read") {
1769
- return await client.socket.updateReadReceiptsPrivacy(params.type);
1770
- }
1771
- if (params.action == "groupsAdd") {
1772
- return await client.socket.updateGroupsAddPrivacy(params.type);
1773
- }
1774
- if (params.action == "ephemeral") {
1775
- const opts = { remove: 0, "24h": 86400, "7d": 604800, "90d": 7776e3 };
1776
- return await client.socket.updateDefaultDisappearingMode(opts[params.type]);
1777
- }
1778
- } catch (error) {
1779
- client.spinner.error("Failed update privacy, please try again.\n\n" + error);
1780
- return null;
1781
- }
1782
- };
1783
- const fetch = {
1784
- settings: async () => {
1785
- return await client.socket.fetchPrivacySettings(true);
1786
- },
1787
- blocklists: async () => {
1788
- return await client.socket.fetchBlocklist();
1789
- }
1790
- };
1791
- return {
1792
- update,
1793
- fetch
1794
- };
1795
- }
1796
- // PROFILE RELAY
1797
- profile() {
1798
- const client = this.ctx;
1799
- const bio = async (props) => {
1800
- const params = RelayProfileBioType.parse(props);
1801
- try {
1802
- return await client.socket.fetchStatus(params.senderId);
1803
- } catch (error) {
1804
- client.spinner.error("Failed fetch profile bio. Make sure senderId is valid.\n\n" + error);
1805
- return null;
1806
- }
1807
- };
1808
- const avatar = async (props) => {
1809
- const params = RelayProfileBioType.parse(props);
1810
- try {
1811
- return await client.socket.profilePictureUrl(params.senderId);
1812
- } catch (error) {
1813
- client.spinner.error("Failed fetch profile avatar. Make sure senderId is valid.\n\n" + error);
1814
- return null;
1815
- }
1816
- };
1817
- const business = async (props) => {
1818
- const params = RelayProfileBioType.parse(props);
1819
- try {
1820
- return await client.socket.getBusinessProfile(params.senderId);
1821
- } catch (error) {
1822
- client.spinner.error("Failed fetch profile business. Make sure senderId is valid.\n\n" + error);
1823
- return null;
1824
- }
1825
- };
1826
- const update = async (props) => {
1827
- const params = RelayProfileUpdateType.parse(props);
1828
- try {
1829
- if (params.type == "name") {
1830
- return await client.socket.updateProfileName(params.text);
1831
- }
1832
- if (params.type == "bio") {
1833
- return await client.socket.updateProfileStatus(params.text);
1834
- }
1835
- if (params.type == "avatar") {
1836
- if (params.avatar == "remove") {
1837
- return await client.socket.removeProfilePicture(params.roomId);
1838
- }
1839
- const avatar2 = typeof params.avatar == "string" ? { url: params.avatar } : params.avatar;
1840
- return await client.socket.updateProfilePicture(params.roomId, avatar2);
1841
- }
1842
- } catch (error) {
1843
- client.spinner.error("Failed update profile. Make sure senderId is valid.\n\n" + error);
1844
- return null;
1845
- }
1846
- };
1847
- const check = async (props) => {
1848
- const params = RelayProfileCheckType.parse(props);
1849
- try {
1850
- const [wa] = await client.socket.onWhatsApp(params.senderId);
1851
- if (!wa) return { isOnWhatsApp: false };
1852
- const pic = await avatar({ senderId: wa.jid });
1853
- const status = await bio({ senderId: wa.jid });
1854
- const obj = {
1855
- isOnWhatsApp: true,
1856
- avatar: pic,
1857
- bio: status,
1858
- ...wa
1859
- };
1860
- return obj;
1861
- } catch (error) {
1862
- client.spinner.error("Failed check profile. Make sure senderId is valid.\n\n" + error);
1863
- return null;
1864
- }
1865
- };
1866
- return {
1867
- bio,
1868
- avatar,
1869
- business,
1870
- update,
1871
- check
1872
- };
1873
- }
1874
- };
1875
- var Client = class {
1876
- props;
1877
- db;
1878
- logger = pino__default.default({ level: "silent", enabled: false });
1879
- events = new EventEmitter__default.default();
1880
- relay;
1881
- retryCount = 0;
1882
- maxRetries = 10;
1883
- connectionTimeout;
1884
- spinner = nanospinner.createSpinner("", { color: "green" });
1885
- socket;
1886
- cache = new NodeCache2__default.default({ stdTTL: 5 * 60, useClones: false });
1887
- constructor(props) {
1888
- this.props = ClientOptionsType.parse(props);
1889
- this.initialize();
1890
- return new Proxy(this, {
1891
- get(target, prop) {
1892
- if (typeof prop === "string" && (prop in target || _2__default.default.includes(["on", "emit"], prop))) return target[prop];
1893
- if (typeof prop === "string") return target.relay[prop];
1894
- return void 0;
1895
- }
1896
- });
1897
- }
1898
- async initialize() {
1899
- console.clear();
1900
- await displayBanner();
1901
- await makeWASocket.delay(1e3);
1902
- await this.spinner.start("Initializing database...");
1903
- const { db, state, store, saveCreds } = await CredsHandler(this.props);
1904
- await this.spinner.start("Fetching newest version...");
1905
- const { version } = await makeWASocket.fetchLatestBaileysVersion();
1906
- this.socket = makeWASocket__default.default({
1907
- version,
1908
- logger: this.logger,
1909
- markOnlineOnConnect: this.props.autoOnline,
1910
- syncFullHistory: true,
1911
- printQRInTerminal: false,
1912
- defaultQueryTimeoutMs: void 0,
1913
- msgRetryCounterCache: new NodeCache2__default.default(),
1914
- mediaCache: new NodeCache2__default.default({ stdTTL: 60 }),
1915
- userDevicesCache: new NodeCache2__default.default(),
1916
- cachedGroupMetadata: async (jid) => this.cache.get(jid),
1917
- auth: {
1918
- creds: state.creds,
1919
- keys: makeWASocket.makeCacheableSignalKeyStore(state.keys, this.logger)
1920
- },
1921
- getMessage: async (key) => {
1922
- if (!key?.id) return void 0;
1923
- const message = await db.store("messages").read(key.id);
1924
- return message;
1925
- }
1926
- });
1927
- await this.socket?.ev.on("creds.update", saveCreds);
1928
- if (this.props.authType === "pairing" && this.props.phoneNumber && !this.socket?.authState.creds.registered) {
1929
- this.spinner.start("Generating pairing code...");
1930
- setTimeout(async () => {
1931
- try {
1932
- if (this.props?.authType === "pairing") {
1933
- const code = await this.socket?.requestPairingCode(this.props.phoneNumber.toString(), shuffleString("Z4D3V0FC"));
1934
- this.spinner.info(`Pairing code: ${code}`);
1935
- }
1936
- } catch {
1937
- this.spinner.error(`Session "${this.props.session}" has not valid, please delete it`);
1938
- process.exit(0);
1939
- }
1940
- }, 5e3);
1941
- }
1942
- const listener = new Listener();
1943
- this.relay = new Relay();
1944
- this.spinner.success("Initialize Successfully");
1945
- await store.bind(this);
1946
- await listener.bind(this, db);
1947
- await this.relay.bind(this, db);
1948
- this.spinner.start("Connecting to WhatsApp...");
1949
- this.startConnectionTimeout();
1950
- }
1951
- startConnectionTimeout() {
1952
- if (this.connectionTimeout) {
1953
- clearTimeout(this.connectionTimeout);
1954
- }
1955
- this.connectionTimeout = setTimeout(() => {
1956
- this.handleConnectionTimeout();
1957
- }, 6e4);
1958
- }
1959
- handleConnectionTimeout() {
1960
- if (this.retryCount < this.maxRetries) {
1961
- this.retryCount++;
1962
- this.spinner.warn(`Connection timeout. Retrying... (${this.retryCount}/${this.maxRetries})`);
1963
- this.autoReload();
1964
- } else {
1965
- this.spinner.error(`Max retries reached (${this.maxRetries}). Connection failed.`);
1966
- process.exit(1);
1967
- }
1968
- }
1969
- async autoReload() {
1970
- try {
1971
- if (this.connectionTimeout) {
1972
- clearTimeout(this.connectionTimeout);
1973
- }
1974
- if (this.socket) {
1975
- this.socket.end?.(void 0);
1976
- this.socket = void 0;
1977
- }
1978
- await makeWASocket.delay(2e3);
1979
- await this.initialize();
1980
- } catch (error) {
1981
- this.spinner.error(`Auto-reload failed: ${error.message}`);
1982
- this.handleConnectionTimeout();
1983
- }
1984
- }
1985
- resetRetryCount() {
1986
- this.retryCount = 0;
1987
- if (this.connectionTimeout) {
1988
- clearTimeout(this.connectionTimeout);
1989
- }
1990
- }
1991
- on(event, handler) {
1992
- this.events.on(event, handler);
1993
- }
1994
- emit(event, ...args) {
1995
- this.events.emit(event, ...args);
1996
- }
1997
- };
1998
- var ExtractorConnectionType = z2.z.object({
1999
- status: z2.z.enum(["connecting", "open", "close"])
2000
- });
2001
-
2002
- exports.AdsReplyType = AdsReplyType;
2003
- exports.CitationType = CitationType;
2004
- exports.Client = Client;
2005
- exports.ClientAuthPairingType = ClientAuthPairingType;
2006
- exports.ClientAuthQRType = ClientAuthQRType;
2007
- exports.ClientBaseType = ClientBaseType;
2008
- exports.ClientOptionsType = ClientOptionsType;
2009
- exports.EventEnumType = EventEnumType;
2010
- exports.ExtractorCallsType = ExtractorCallsType;
2011
- exports.ExtractorConnectionType = ExtractorConnectionType;
2012
- exports.ExtractorMessagesType = ExtractorMessagesType;
2013
- exports.FakeReplyType = FakeReplyType;
2014
- exports.JsonDB = JsonDB;
2015
- exports.LimiterType = LimiterType;
2016
- exports.MessagesDeviceEnumType = MessagesDeviceEnumType;
2017
- exports.MessagesEnumType = MessagesEnumType;
2018
- exports.MessagesMediaType = MessagesMediaType;
2019
- exports.MessagesVerifiedPlatformType = MessagesVerifiedPlatformType;
2020
- exports.PluginsType = PluginsType;
2021
- exports.defaultBoolean = defaultBoolean;
2022
- exports.defaultString = defaultString;
2023
- exports.delay = delay;
2024
- exports.extractJids = extractJids;
2025
- exports.extractUrls = extractUrls;
2026
- exports.findWord = findWord;
2027
- exports.getMentions = getMentions;
2028
- exports.normalizeText = normalizeText;
2029
- exports.randomize = randomize;
2030
- exports.shuffleString = shuffleString;
2031
- exports.toJson = toJson;
2032
- exports.toString = toString;
2033
- exports.tryAgain = tryAgain;
1
+ 'use strict';var Yt=require('baileys'),We=require('fs/promises'),asyncMutex=require('async-mutex'),Be=require('path'),nanospinner=require('nanospinner'),ze=require('node-cache'),events=require('events'),Rt=require('pino'),Xe=require('gradient-string'),v=require('lodash'),fileType=require('file-type'),G=require('fluent-ffmpeg'),Ft=require('node-webpmux'),os=require('os'),Le=require('sharp'),es=require('figlet'),ss=require('qrcode-terminal'),rateLimiterFlexible=require('rate-limiter-flexible'),u=require('zod'),ve=require('fs'),url=require('url');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Yt__default=/*#__PURE__*/_interopDefault(Yt);var We__default=/*#__PURE__*/_interopDefault(We);var Be__namespace=/*#__PURE__*/_interopNamespace(Be);var ze__default=/*#__PURE__*/_interopDefault(ze);var Rt__default=/*#__PURE__*/_interopDefault(Rt);var Xe__default=/*#__PURE__*/_interopDefault(Xe);var v__default=/*#__PURE__*/_interopDefault(v);var G__default=/*#__PURE__*/_interopDefault(G);var Ft__default=/*#__PURE__*/_interopDefault(Ft);var Le__default=/*#__PURE__*/_interopDefault(Le);var es__default=/*#__PURE__*/_interopDefault(es);var ss__default=/*#__PURE__*/_interopDefault(ss);var u__default=/*#__PURE__*/_interopDefault(u);var ve__namespace=/*#__PURE__*/_interopNamespace(ve);var Ze=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Pe=class{data=new Map;cache=new Map;set(e,t){this.data.set(e,{...this.data.get(e),...t});}get(e){return this.data.get(e)||{}}update(e,t){let s=this.get(e);this.set(e,t(s));}delete(e){this.data.delete(e);}has(e){return this.data.has(e)}lowdb(e,t){let s=`.session/${e}/${t}`;if(this.cache.has(s))return this.cache.get(s);let r=q(s);return this.cache.set(s,r),r}spinner=nanospinner.createSpinner("",{color:"green"});logger=Rt__default.default({level:"silent",enabled:false});events=new events.EventEmitter;groupCache=new ze__default.default({stdTTL:300,useClones:false});collectors=new Map},a=new Pe;var g=o=>o,Qe=async()=>{try{return (await(await fetch("https://registry.npmjs.org/zaileys")).json())["dist-tags"].latest}catch(o){throw o}},Ye=async o=>{try{let e=`.session/${o}/creds.json`;await We__default.default.unlink(e);}catch(e){throw a.spinner.error(`Failed to remove auth creds for session "${o}"!`),e}},R=(o="")=>o?.length?o.normalize("NFKD").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\uFFF9-\uFFFB]/gu,"").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u20D0-\u20FF\uFE20-\uFE2F]/gu,"").replace(/[\u202A-\u202E\u2066-\u2069]/gu,"").replace(/\u202E([\s\S]*?)\u202C?/gu,(t,s)=>[...s].reverse().join("")):null;var M=(o,e="lime")=>Array.isArray(e)?Xe__default.default(e)(o):Xe__default.default([e,e])(o),Re=o=>{try{return JSON.parse(o)}catch{return v__default.default.attempt(()=>JSON.parse(JSON.stringify(o)||"{}"))}},X=o=>{try{return JSON.stringify(o)}catch{let e=v__default.default.attempt(()=>JSON.stringify(Re(o)||"{}"));return v__default.default.isError(e)?"{}":e}},Zs=(o="")=>v__default.default.shuffle(o).join(""),ee=(o="",e="")=>o?v__default.default.includes(o.toLowerCase(),e.toLowerCase()):null,et=(o="")=>o?v__default.default.castArray(o.match(Yt.URL_REGEX)||[]):[],Qs=o=>o[Math.floor(Math.random()*o.length)],C=(o,e)=>{for(let t of o||[])if(t&&typeof t=="object"){for(let s of e)if(s in t&&t[s]!==void 0&&t[s]!==null)return t[s]}},tt=(o,e)=>{let t=v__default.default.castArray(e),s=(n,c)=>v__default.default.every(c,(p,l)=>n?.[l]===p),r=(n,c)=>v__default.default.some(c,(p,l)=>n?.[l]===p),i=n=>v__default.default.isArray(n)?v__default.default.find(n,i)??n:v__default.default.isObject(n)?v__default.default.find(t,l=>s(n,l))||v__default.default.find(t,l=>r(n,l))?n:v__default.default.find(v__default.default.values(n),i)??n:null;return i(o)},Ys=(o,e,t)=>new Proxy(o,{apply(s,r,i){e?.(i);let n=Reflect.apply(s,r,i);return t?t(n,i):n}});var B=o=>{let e;Array.isArray(o)?e=o.join("|"):typeof o=="string"?e=o:e=String(o);let t=2166136261,s=e.length;for(let r=0;r<s;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return "Z4D3FC"+(t>>>0).toString(16).padStart(8,"0").toUpperCase()},st=(o="")=>{if(!o)return [];let e=new Set;for(let t of o.matchAll(/@(\d+)/g))e.add(t[1]);return v__default.default.toArray(e)},Ee=(o="")=>{if(!o)return [];let e=new Set;for(let t of o.matchAll(/@(\d+)/g))t[1].length<=15&&e.add(t[1]);return v__default.default.flatMap([...e],t=>[`${t}@s.whatsapp.net`,`${t}@g.us`,`${t}@lid`])},ri=o=>v__default.default.isEmpty(o)?[]:v__default.default.map([...o],e=>`${e}@s.whatsapp.net`),it=o=>v__default.default.omit(o,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","message","key","midQualityFileSha256","historySyncNotification","appStateSyncKeyShare","appStateSyncKeyRequest","initialSecurityNotificationSettingSync","appStateFatalExceptionNotification","disappearingMode","peerDataOperationRequestMessage","peerDataOperationRequestResponseMessage","botFeedbackMessage"]),J=o=>{if(!o)return {leaf:void 0,chain:[]};let e=Yt.extractMessageContent(o)||o,t=[];for(;e&&typeof e=="object";){let s=Yt.getContentType(e);if(!s)break;t.push(s);let r=e[s];if(!r||typeof r!="object"){e=r;break}e=r;}return {leaf:e,chain:t}},E=o=>Number(o?.split("@")[0]);var zt=Ze("@ffmpeg-installer/ffmpeg").path,jt=Ze("@ffprobe-installer/ffprobe").path;G__default.default.setFfmpegPath(zt);G__default.default.setFfprobePath(jt);var y={OPUS:{CODEC:"libopus",CHANNELS:1,FREQUENCY:48e3,BITRATE:"48k",FORMAT:"ogg"},THUMBNAIL:{SIZE:100,QUALITY:50,TIMESTAMP:"10%"},STICKER:{SIZE:512,MAX_DURATION:10,FPS:15,DEFAULT_QUALITY:80,COMPRESSION_LEVEL:6},MIME:{AUDIO:"audio/",VIDEO:"video/",IMAGE:"image/",GIF:"image/gif",MP4:"video/mp4"}},w=class{static generateUniqueId(){return `${Date.now()}_${Math.random().toString(36).slice(2,11)}`}static createTempPath(e,t){return Be__namespace.default.join(os.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>We__default.default.unlink(t)));}static async safeReadFile(e){try{return await We__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await We__default.default.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},A=class{static async toBuffer(e){if(v.isBuffer(e))return e;if(v.isArrayBuffer(e))return Buffer.from(e);if(v.isString(e))return this.fromString(e);throw new Error("Invalid input type: expected string, Buffer, or ArrayBuffer")}static async fromString(e){return e.startsWith("http://")||e.startsWith("https://")?this.fromUrl(e):Buffer.from(e,"base64")}static async fromUrl(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let s=await t.arrayBuffer();return Buffer.from(s)}catch(t){throw new Error(`Failed to fetch URL: ${t.message}`)}}},N=class{static validate(e,t){if(!e?.mime?.startsWith(t))throw new Error(`Invalid file type: expected ${t}*, got ${e?.mime||"unknown"}`)}static isMedia(e){return e.startsWith(y.MIME.IMAGE)||e.startsWith(y.MIME.VIDEO)}static isAnimated(e){return e===y.MIME.GIF||e.startsWith(y.MIME.VIDEO)}},K=class{static async process(e){return new Promise((t,s)=>{let r=G__default.default(e.input).output(e.output);for(let i=0;i<e.options.length;i++){let n=e.options[i];n.startsWith("-")&&i+1<e.options.length&&!e.options[i+1].startsWith("-")?(r.outputOptions(n,e.options[i+1]),i++):r.outputOptions(n);}r.on("end",async()=>{try{await e.onEnd(),t();}catch(i){s(i);}}).on("error",async i=>{try{await e.onError(i);}finally{s(i);}}).run();})}static async getDuration(e){return new Promise((t,s)=>{G__default.default.ffprobe(e,(r,i)=>{if(r)return s(r);t(i.format.duration||0);});})}},te=class{static async getWaAudio(e,t="opus"){let s=await A.toBuffer(e),r=await fileType.fileTypeFromBuffer(s);N.validate(r,y.MIME.AUDIO);let i=w.createTempPath("audio_in","wav"),n=t==="opus"?"ogg":"mp3",c=w.createTempPath("audio_out",n);await w.safeWriteFile(i,s);let p;try{let l=t==="opus"?["-vn","-c:a","libopus","-b:a","48k","-ac","1","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","opus"]:["-vn","-c:a","libmp3lame","-b:a","128k","-ac","2","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","mp3"];return await K.process({input:i,output:c,options:l,onEnd:async()=>{p=await w.safeReadFile(c);},onError:async()=>{await w.cleanup([i,c]);}}),await w.cleanup([i,c]),p}catch(l){throw await w.cleanup([i,c]),new Error(`${t.toUpperCase()} conversion failed: ${l.message}`)}}},W=class{static async getThumbnail(e){let t=await A.toBuffer(e),s=await fileType.fileTypeFromBuffer(t);N.validate(s,y.MIME.VIDEO);let r=w.createTempPath("video","mp4"),i=w.createTempPath("thumb","jpg");await w.safeWriteFile(r,t);let n;try{return await new Promise((c,p)=>{G__default.default(r).screenshots({timestamps:[y.THUMBNAIL.TIMESTAMP],filename:Be__namespace.default.basename(i),folder:Be__namespace.default.dirname(i),size:`${y.THUMBNAIL.SIZE}x${y.THUMBNAIL.SIZE}`,quality:y.THUMBNAIL.QUALITY}).on("end",async()=>{try{n=(await w.safeReadFile(i)).toString("base64"),c();}catch(l){p(l);}}).on("error",p);}),await w.cleanup([r,i]),n}catch(c){throw await w.cleanup([r,i]),new Error(`Thumbnail generation failed: ${c.message}`)}}static async getDuration(e){return K.getDuration(e)}},se=class{static async getThumbnail(e){return (await((await fileType.fileTypeFromBuffer(e)).mime===y.MIME.GIF?Le__default.default(e,{animated:false}):Le__default.default(e)).resize(y.THUMBNAIL.SIZE,y.THUMBNAIL.SIZE,{fit:"cover"}).jpeg({quality:y.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}static async resizeForSticker(e,t){return Le__default.default(e).resize(y.STICKER.SIZE,y.STICKER.SIZE,{fit:"cover",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:t}).toBuffer()}},H=class{static async getThumbnail(e){let t=await A.toBuffer(e),s=await fileType.fileTypeFromBuffer(t);if(!s||!N.isMedia(s.mime))throw new Error("Invalid media type: expected image or video");return s.mime.startsWith(y.MIME.VIDEO)?W.getThumbnail(e):se.getThumbnail(t)}},ie=class{static createExifMetadata(e){let t={"sticker-pack-id":B(Date.now().toString()),"sticker-pack-name":e?.packageName||"Zaileys Library","sticker-pack-publisher":e?.authorName||"https://github.com/zeative/zaileys",emojis:["\u{1F913}"],"android-app-store-link":"https://play.google.com/store/apps/details?id=com.marsvard.stickermakerforwhatsapp","ios-app-store-link":"https://itunes.apple.com/app/sticker-maker-studio/id1443326857"},s=Buffer.from([73,73,42,0,8,0,0,0,1,0,65,87,7,0,0,0,0,0,22,0,0,0]),r=Buffer.from(JSON.stringify(t),"utf8"),i=Buffer.concat([s,r]);return i.writeUIntLE(r.length,14,4),i}static async processAnimated(e,t,s){let r=this.getExtension(t),i=w.createTempPath("sticker_in",r),n=w.createTempPath("sticker_out","webp");await w.safeWriteFile(i,e);let c=y.STICKER.MAX_DURATION;try{let T=await W.getDuration(i);c=g(Math.min(T,y.STICKER.MAX_DURATION));}catch{console.warn("Using default duration:",y.STICKER.MAX_DURATION);}let p=`scale=${y.STICKER.SIZE}:${y.STICKER.SIZE}:force_original_aspect_ratio=increase,crop=${y.STICKER.SIZE}:${y.STICKER.SIZE},fps=${y.STICKER.FPS},format=rgba`,l=Math.max(1,Math.min(100,100-s)),h;try{return await K.process({input:i,output:n,options:["-vcodec libwebp",`-vf ${p}`,`-q:v ${l}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${c}`,`-compression_level ${y.STICKER.COMPRESSION_LEVEL}`],onEnd:async()=>{h=await w.safeReadFile(n);},onError:async()=>{await w.cleanup([i,n]);}}),await w.cleanup([i,n]),h}catch(T){throw await w.cleanup([i,n]),new Error(`Animated sticker processing failed: ${T.message}`)}}static getExtension(e){return e===y.MIME.GIF?"gif":e.startsWith(y.MIME.VIDEO)?"mp4":"tmp"}static async create(e,t){try{let s=await A.toBuffer(e),r=await fileType.fileTypeFromBuffer(s);if(!r)throw new Error("Unable to detect file type");let i=t?.quality||y.STICKER.DEFAULT_QUALITY,c=N.isAnimated(r.mime)?await this.processAnimated(s,r.mime,i):await se.resizeForSticker(s,i),p=this.createExifMetadata(t),l=new Ft__default.default.Image;await l.load(c),l.exif=p;let h=await l.save(null);return Buffer.isBuffer(h)?h:Buffer.from(h)}catch(s){throw new Error(`Sticker creation failed: ${s.message||s}`)}}},re=class{static async create(e){try{let t=await A.toBuffer(e),s=await fileType.fileTypeFromBuffer(t);if(!s)throw new Error("Unable to detect file type");return {document:t,mimetype:s.mime,fileName:B(Date.now().toString()),jpegThumbnail:await H.getThumbnail(t)}}catch(t){throw new Error(`Document creation failed: ${t.message||t}`)}}},ne=A.toBuffer.bind(A),rt=te.getWaAudio.bind(te),hi=W.getThumbnail.bind(W),ki=W.getDuration.bind(W),Ne=H.getThumbnail.bind(H),nt=ie.create.bind(ie),ot=re.create.bind(re);var Fe=class o{static inst;fLocks=new Map;kLocks=new Map;maxSize=100;static get(){return this.inst||(this.inst=new o)}getFile(e){let t=this.fLocks.get(e);if(!t){if(this.fLocks.size>=this.maxSize){let s=this.fLocks.keys().next().value;this.fLocks.delete(s);}t=new asyncMutex.Mutex,this.fLocks.set(e,t);}return t}getKey(e){let t=this.kLocks.get(e);if(!t){if(this.kLocks.size>=this.maxSize){let s=this.kLocks.keys().next().value;this.kLocks.delete(s);}t=new asyncMutex.Mutex,this.kLocks.set(e,t);}return t}},$e=class{data;path;pool;size;chunkDir;replacer;reviver;loaded=false;flushMode;debounceMs;flushTimer=null;dirty=false;constructor(e,t,s=2*1024*1024,r="debounce",i=200){this.data=new Map,this.path=e,this.pool=Fe.get(),this.size=s,this.chunkDir=`${e}.c`,this.replacer=t?.replacer||null,this.reviver=t?.reviver||null,this.flushMode=r,this.debounceMs=i;}async ensureLoaded(){this.loaded||(await this.read(),this.loaded=true);}scheduleFlush(){if(this.flushMode!=="manual"){if(this.flushMode==="sync"){this.write();return}this.dirty=true,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.dirty&&(this.dirty=false,this.write());},this.debounceMs));}}async read(){return this.pool.getFile(this.path).runExclusive(async()=>{try{let t=await We.readFile(this.path,"utf-8"),s=JSON.parse(t,this.reviver);this.data.clear();let r=[];for(let[i,n]of Object.entries(s))this.isMeta(n)?r.push(this.loadChunk(i,n)):this.data.set(i,n);return await Promise.all(r),this.loaded=!0,this.data}catch{return await We.mkdir(Be.dirname(this.path),{recursive:true}),this.data.clear(),this.loaded=true,this.data}})}async write(){return this.pool.getFile(this.path).runExclusive(async()=>{let t={},s=[];for(let[i,n]of this.data){if(this.isMeta(n)){t[i]=n;continue}JSON.stringify(n,this.replacer).length>this.size?s.push(this.saveChunk(i,n).then(p=>{t[i]=p;})):t[i]=n;}await Promise.all(s);let r=JSON.stringify(t,this.replacer,2);await We.writeFile(this.path,r,"utf-8");})}async set(e,t){await this.ensureLoaded(),await this.pool.getKey(e).runExclusive(async()=>{this.data.set(e,t),this.scheduleFlush();});}async push(e,t){await this.ensureLoaded(),await this.pool.getKey(e).runExclusive(async()=>{let r=this.data.get(e),i;Array.isArray(r)?i=r:r===void 0?i=[]:i=[r],i.push(t),this.data.set(e,i),this.scheduleFlush();});}async get(e){if(await this.ensureLoaded(),typeof e=="string")return this.data.get(e);let t=Array.from(this.data.values()).flat();return tt(t,e)}async all(){return await this.ensureLoaded(),Array.from(this.data.entries())}async delete(e){return await this.ensureLoaded(),this.pool.getKey(e).runExclusive(async()=>{let s=this.data.get(e);this.isMeta(s)&&await this.delChunk(e,s);let r=this.data.delete(e);return this.scheduleFlush(),r})}async saveChunk(e,t){let s=JSON.stringify(t,this.replacer),r=Buffer.from(s,"utf-8"),i=Math.ceil(r.length/this.size);await We.mkdir(this.chunkDir,{recursive:true});let n={v:1,k:e,t:i,s:this.size,c:r.length,m:Date.now().toString(36)},c=[];for(let p=0;p<i;p++){let l=p*this.size,h=Math.min(l+this.size,r.length),T=r.subarray(l,h);c.push(We.writeFile(Be.join(this.chunkDir,`${e}.${p}.json`),JSON.stringify({i:p,d:T.toString("base64")})));}return c.push(We.writeFile(Be.join(this.chunkDir,`${e}.manifest.json`),JSON.stringify(n))),await Promise.all(c),{t:i,s:this.size,k:e}}async loadChunk(e,t){let s=Be.join(this.chunkDir,`${e}.manifest.json`),r=JSON.parse(await We.readFile(s,"utf-8")),i=[];for(let l=0;l<r.t;l++)i.push(We.readFile(Be.join(this.chunkDir,`${e}.${l}.json`),"utf-8").then(h=>Buffer.from(JSON.parse(h).d,"base64")));let n=await Promise.all(i),c=Buffer.concat(n),p=JSON.parse(c.toString("utf-8"),this.reviver);this.data.set(e,p);}async delChunk(e,t){let s=[];for(let r=0;r<t.t;r++)s.push(We.unlink(Be.join(this.chunkDir,`${e}.${r}.json`)).catch(()=>{}));s.push(We.unlink(Be.join(this.chunkDir,`${e}.manifest.json`)).catch(()=>{})),await Promise.all(s);try{(await We.readdir(this.chunkDir)).length===0&&await We.rmdir(this.chunkDir);}catch{}}isMeta(e){return e?.t&&e?.s&&e?.k}},q=(o,e)=>new $e(o,e?.BufferJSON,e?.size,e?.flushMode,e?.debounceMs);var ut=async o=>{a.spinner.start(" Initializing auth state...");let e=await We.stat(o).catch(()=>{});if(e){if(!e.isDirectory())throw a.spinner.error(` Failed to open credentials
2
+ `),`found something that is not a directory at ${o}, either delete it or specify a different location`}else await We.mkdir(o,{recursive:true});let t=q(`${o}/auth/creds.json`,{BufferJSON:Yt.BufferJSON}),s=q(`${o}/auth/keys.json`,{BufferJSON:Yt.BufferJSON,size:512*1024});await Promise.all([t.read(),s.read()]);let r=await t.get("creds")||Yt.initAuthCreds();return a.spinner.success(" Generate auth successfully"),{state:{creds:r,keys:{get:async(i,n)=>{let c={};return await Promise.all(n.map(async p=>{let l=`${i}:${p}`,h=await s.get(l);i==="app-state-sync-key"&&h&&(h=Yt.proto.Message.AppStateSyncKeyData.fromObject(h)),c[p]=h;})),c},set:async i=>{let n=[];for(let c in i)for(let p in i[c]){let l=i[c][p],h=`${c}:${p}`;l?n.push(s.set(h,l)):n.push(s.delete(h).then(()=>{}));}await Promise.all(n),await s.write();}}},saveCreds:async()=>{await t.set("creds",r),await t.write();}}};var Qt=new ze__default.default,mt=(o,e)=>({logger:a.logger,printQRInTerminal:false,defaultQueryTimeoutMs:void 0,markOnlineOnConnect:o.options.autoOnline,syncFullHistory:o.options.syncFullHistory,msgRetryCounterCache:new ze__default.default,mediaCache:new ze__default.default({stdTTL:60}),cachedGroupMetadata:async t=>Qt.get(t),shouldIgnoreJid:t=>Yt.isJidBroadcast(t),auth:{creds:e.creds,keys:Yt.makeCacheableSignalKeyStore(e.keys,a.logger)},getMessage:async t=>{if(t?.id)return await o.db("messages").get(t.id)}});var dt=async o=>{let e=`.session/${o.options.session}`;console.info=()=>{};let{state:t,saveCreds:s}=await ut(e),r=mt(o,t),i=Yt__default.default(r);i.ev.on("creds.update",s),a.set("socket",i);};var oe=class{constructor(e){this.client=e;this.initialize();}async initialize(){let e=a.get("socket");e.ev.on("call",async t=>{for(let s of t){let r=await this.parse(s);r&&(await this.client.middleware.run({calls:r}),await this.client.plugins.execute(this.client,{messages:r}),a.events.emit("calls",r),this.client.options?.autoRejectCall&&await e.rejectCall(r.callId,r.callerId));}});}async parse(e){let t=a.get("socket"),s={};return s.callId=e.id,s.callerId=Yt.jidNormalizedUser(e.from),s.callerName=await this.client.getRoomName(s.callerId),s.roomId=Yt.jidNormalizedUser(e.chatId),s.roomName=R(t?.user?.name||t?.user?.verifiedName),s.date=e.date,s.offline=e.offline,s.status=e.status,s.isVideo=!!e.isVideo,s.isGroup=!!e.isGroup,this.client.logs.call(s),s}};var ae={version:"1.1.40-tx.9",author:"zaadevofc"};var gt=o=>{ss__default.default.generate(o,{small:true},e=>{console.log(e);});},yt=async()=>{console.clear(),a.spinner.start(" Checking for updates...");let o=await Qe(),e=ae.version===o;a.spinner.stop();let t="Zaileys",s=`
3
+ by ${ae.author} \xB7 v${ae.version}`,r=`${e?"Already using latest version!":`Update available! (v${o})`}
4
+ `,i=e?"lime":"orange",n=await es__default.default.text(t),c=Xe.cristal(n);console.log(c),console.log(M(s,"#383838ff")),console.log(M(r,i));};var pe=class{constructor(e){this.client=e;this.initialize();}async initialize(){a.spinner.start(" Initializing connection...");let e=a.get("socket"),t={},s=async()=>{t.status="reload",a.spinner.warn(" Connection lost. Attempting auto-reload..."),await this.client.initialize();},r=async()=>{await Yt.delay(3e3),a.spinner.warn(" Invalid session. Attempting auto cleaning creds..."),await Yt.delay(3e3),await Ye(this.client.options.session),await s();};if(this.client.options.authType==="pairing"&&this.client.options.phoneNumber&&!e.authState.creds.registered){a.spinner.update(" Generating pairing code..."),await Yt.delay(3500);try{t.authTimeout=Date.now()+6e4;let i=new Date(t.authTimeout).toLocaleTimeString(),n=await e.requestPairingCode(this.client.options.phoneNumber.toString());a.spinner.warn(` Pairing expired at ${Xe.cristal(i)}`),a.spinner.warn(` Pairing code: ${n}`),t.code=n;}catch{await r();}}e.ev.on("connection.update",async i=>{let{connection:n,lastDisconnect:c,qr:p}=i;if(t.status=n||"connecting",t.authType=this.client.options.authType,a.spinner.update(" Connection status: "+Xe.cristal(t.status)),this.client.options.authType==="qr"&&p){t.authTimeout=Date.now()+6e4;let l=new Date(t.authTimeout).toLocaleTimeString();a.spinner.warn(" Please scan the QR code..."),a.spinner.warn(` Qr code expired at ${Xe.cristal(l)}`),gt(p),t.qr=p;return}if(n==="close"){let l=g(c?.error)?.output?.statusCode,h=c?.error?.message||"",T=typeof l=="number"&&l!==Yt.DisconnectReason.loggedOut;a.spinner.error(`[${l} - Closed] ${h}`),(l===401||l===405||l===500)&&(a.spinner.error(" Invalid session, please delete manually!"),a.spinner.error(` Session "${this.client.options.session}" has not valid, please delete it!
5
+ `),await r()),T&&await s();}if(n==="open")if(e.user?.id){let l=Yt.jidNormalizedUser(e.user.id).split("@")[0],h=e.user.name||e.user.verifiedName;a.spinner.success(` Connected as ${Xe.cristal(h||l)}`);}else a.spinner.success(" Connected!");a.events.emit("connection",t);}),e.ev.on("messaging-history.set",({progress:i})=>{t.status="syncing",t.syncProgress=i,a.spinner.start(" Syncing messages history..."),i&&a.spinner.update(` Syncing messages history ${i+"%"}`),i==100&&(a.spinner.success(" Syncing messages history completed!"),t.syncCompleted=true),a.events.emit("connection",t);});}};var ht={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contacts",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"location",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"buttons",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"lists",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"lists",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttons",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",questionMessage:"question",nativeFlowResponseMessage:"lists",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollCreationMessageKey:"pollUpdate",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},_e={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"};var le=class{constructor(e){this.client=e;this.limiter=new rateLimiterFlexible.RateLimiterMemory({points:this.client.options.limiter?.maxMessages,duration:this.client.options.limiter?.durationMs/1e3});}limiter;async isSpam(e){try{return await this.limiter.consume(e),!1}catch{return true}}};var me=class{constructor(e){this.client=e;this.limiter=new le(e),this.initialize();}limiter;maxReplies=3;async initialize(){let e=a.get("socket");e.ev.on("messages.upsert",async({messages:t,type:s})=>{if(s==="notify")for(let r of t){let i=await this.parse(r);i&&(this.client.collector.push(i)||(await this.client.middleware.run({messages:i}),await this.client.plugins.execute(this.client,{messages:i}),a.set("message",i),a.events.emit("messages",i)),this.client.options.autoRead&&await e.readMessages([i.message().key]));}});}async parse(e,t){if(e?.category==="peer"||!e?.message||!e?.key?.id||e?.messageStubType||e?.messageStubParameters?.length||e.message?.protocolMessage?.peerDataOperationRequestResponseMessage||e.message?.groupStatusMentionMessage)return;let s=e,r=a.get("socket"),i={},n=J(e.message),c=n.chain.at(-1),p=n.leaf;p?.message&&(n=J(p.message),c=n.chain.at(-1),p=n.leaf),i.uniqueId=null,i.channelId=null,i.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id||null,i.chatType=ht[c],i.receiverId=Yt.jidNormalizedUser(r?.user?.id||""),i.receiverName=R(r?.user?.name||r?.user?.verifiedName),i.roomId=Yt.jidNormalizedUser(e?.key?.remoteJid);let l=p?.type===0,h=p?.type===1,T=p?.type===2,Y=i.roomId?.includes("@newsletter"),Ce=!!e?.message?.questionMessage,F=e?.key?.fromMe||false;if(F&&this.client.options.ignoreMe&&t!=="replied")return;let Ae=p?.key?.id;if(l||h||T){let x=(await this.client.db("messages").get(i.roomId))?.find(L=>L.key.id===Ae);if(!x)return;e=x,n=J(e.message),c=n.chain.at(-1),p=n.leaf;}if(i.roomName=await this.client.getRoomName(i.roomId),i.senderLid=C([e?.key],["remoteJidAlt","participant"])||null,i.senderId=Yt.jidNormalizedUser(e?.participant||e?.key?.participant||e?.key?.remoteJid),i.senderName=R(e?.pushName||e?.verifiedBizName),i.senderDevice=Yt.getDevice(i.chatId),i.channelId=B([i.roomId,i.senderId]),i.uniqueId=B([i.channelId,i.chatId]),i.timestamp=Number(e?.messageTimestamp)*1e3,Y){let S=await r.newsletterMetadata("jid",i.roomId);i.roomName=g(S.thread_metadata.name)?.text,i.senderId=null,i.senderLid=null;}if(F&&(i.senderLid=Yt.jidNormalizedUser(r.user.lid),i.senderId=i.receiverId,i.senderName=i.receiverName),i.text=p?.text||p?.caption||p?.name||p?.displayName||p?.conversation||p?.contentText||p?.selectedDisplayText||p||null,p?.name=="menu_options"&&(i.text=Re(p?.paramsJson)?.id),i.text=R(i.text),i.mentions=st(i.text),i.links=et(i.text||""),i.isBot=i.chatId.startsWith("BAE5")||i.chatId.startsWith("3EB0")||i.chatId.startsWith("Z4D3FC"),i.isFromMe=F,i.isTagMe=i.mentions?.includes(i.receiverId.split("@")[0]),i.isPrefix=i.text?.startsWith(this.client.options?.prefix)||false,i.isSpam=await this.limiter.isSpam(i.channelId),i.isGroup=i.roomId?.includes("@g.us"),i.isNewsletter=Y,i.isQuestion=Ce,i.isStory=i.roomId?.includes("@broadcast"),i.isViewOnce=false,i.isEdited=!!ee(X(n),"editedMessage"),i.isDeleted=l,i.isPinned=h,i.isUnPinned=T,i.isBroadcast=!!e?.broadcast,i.isEphemeral=!!ee(X(p?.contextInfo),"ephemeralSettingTimestamp"),i.isForwarded=!!ee(X(p?.contextInfo),"forwardingScore"),i.citation=null,this.client.options.citation){i.citation=i.citation||{};let S=this.client.options.citation;for(let x of Object.keys(S)){let L=S[x];i.citation[x]=async()=>{let _=await L(),Ie=[E(i.roomId),E(i.senderLid),E(i.senderId)];return !!v__default.default.intersection(Ie,_).length};}}i.chatType!=="text"&&(i.media={...it(p),buffer:()=>Yt.downloadMediaMessage(e,"buffer",{}),stream:()=>Yt.downloadMediaMessage(e,"stream",{})}),i.message=()=>s,i.replied=null;let $=p?.contextInfo?.quotedMessage,z=C([$],["viewOnceMessageV2Extension","viewOnceMessage"]),j=p?.contextInfo?.stanzaId;if($&&!this.maxReplies){this.maxReplies--;let x=(await this.client.db("messages").get(i.roomId))?.find(_=>_.key.id===j),L={...x,...J(z).leaf};z?(i.replied=await this.parse(L,"replied"),i.replied.isViewOnce=true):i.replied=await this.parse(x,"replied"),this.maxReplies=3;}return this.client.logs.message(i),i}};var de=class{constructor(e){this.client=e;this.connection=new pe(e),this.messages=new me(e),this.calls=new oe(e),this.initialize();}connection;messages;calls;async initialize(){let e=a.get("socket");e.ev.on("groups.update",async([t])=>{let s=await e.groupMetadata(t.id);a.groupCache.set(t.id,s);}),e.ev.on("group-participants.update",async t=>{let s=await e.groupMetadata(t.id);a.groupCache.set(t.id,s);}),e?.ev.on("messaging-history.set",async t=>{let{chats:s,contacts:r,messages:i}=t;for(let n of s)await this.client.db("chats").push(n.id,n);for(let n of r)await this.client.db("contacts").push(n.id,n);for(let n of i){if(!n.message&&!n.key.isViewOnce||n?.category==="peer"||n.message?.protocolMessage||n.message?.groupStatusMentionMessage)return;await this.client.db("messages").push(n.key.remoteJid,n);}}),e?.ev.on("messages.upsert",async({messages:t})=>{for(let s of t){if(!s.message&&!s.key.isViewOnce||s?.category==="peer"||s.message?.protocolMessage||s.message?.groupStatusMentionMessage)return;await this.client.db("messages").push(s.key.remoteJid,s);}}),e?.ev.on("chats.upsert",async t=>{for(let s of t)await this.client.db("chats").push(s.id,s);}),e?.ev.on("contacts.upsert",async t=>{for(let s of t)await this.client.db("contacts").push(s.id,s);});}};var Z=(o,e)=>{let t=o.safeParse(e);if(t.success)return t.data;throw console.error(t.error),"Invalid data"};var cs=u__default.default.object({type:u__default.default.literal("quick_reply"),text:u__default.default.string()}),ps=u__default.default.object({type:u__default.default.literal("cta_url"),url:u__default.default.url(),text:u__default.default.string()}),ls=u__default.default.object({type:u__default.default.literal("cta_copy"),copy:u__default.default.string(),text:u__default.default.string()}),us=u__default.default.object({type:u__default.default.literal("cta_call"),text:u__default.default.string(),phoneNumber:u__default.default.string()}),ms=u__default.default.object({type:u__default.default.literal("single_select"),text:u__default.default.string(),section:u__default.default.object({title:u__default.default.string(),highlight_label:u__default.default.string().optional(),rows:u__default.default.object({id:u__default.default.string(),title:u__default.default.string(),header:u__default.default.string().optional(),description:u__default.default.string().optional()}).array()}).array()}),ds=u__default.default.object({type:u__default.default.literal("interactive"),footer:u__default.default.string().optional(),data:u__default.default.union([cs,ps,ls,us,ms]).array()}),fs=u__default.default.object({type:u__default.default.literal("simple"),footer:u__default.default.string().optional(),data:u__default.default.object({id:u__default.default.string(),text:u__default.default.string()}).array()}),wt=u__default.default.union([fs,ds]);var Q=u__default.default.url().or(u__default.default.base64()).or(u__default.default.instanceof(Buffer)),Mt=u__default.default.object({text:u__default.default.string()}).passthrough(),gs=u__default.default.object({image:Q,caption:u__default.default.string().optional()}).passthrough(),ys=u__default.default.object({audio:Q,caption:u__default.default.string().optional(),ptt:u__default.default.boolean().optional()}).passthrough(),hs=u__default.default.object({video:Q,caption:u__default.default.string().optional(),ptv:u__default.default.boolean().optional()}).passthrough(),ks=u__default.default.object({sticker:Q,caption:u__default.default.string().optional()}).passthrough(),ws=u__default.default.object({document:Q,caption:u__default.default.string().optional(),fileName:u__default.default.string().optional()}).passthrough(),Ms=u__default.default.object({location:u__default.default.object({latitude:u__default.default.number(),longitude:u__default.default.number(),url:u__default.default.url().optional(),title:u__default.default.string().optional(),footer:u__default.default.string().optional()}).optional()}).passthrough(),vs=u__default.default.object({title:u__default.default.string().optional(),contacts:u__default.default.object({fullname:u__default.default.string(),phoneNumber:u__default.default.number(),organization:u__default.default.string().optional()}).array()}),bs=u__default.default.object({poll:u__default.default.object({name:u__default.default.string(),answers:u__default.default.string().array(),isMultiple:u__default.default.boolean().default(false).optional()})}),vt=u__default.default.object({replied:u__default.default.custom().optional(),isForwardedMany:u__default.default.boolean().optional(),isViewOnce:u__default.default.boolean().optional(),banner:u__default.default.custom().optional(),buttons:wt.optional()});u__default.default.enum(["forward","button","edit","delete"]);var Ts=u__default.default.union([Mt,gs,ys,hs,ks,ws,Ms,vs,bs]),bt=u__default.default.string().or(u__default.default.intersection(Ts,vt.omit({buttons:true}))),Tt=u__default.default.intersection(Mt,vt.omit({banner:true}));var fe=class{toNativeSimple(e){return e.map(({id:t,text:s})=>({name:"quick_reply",buttonParamsJson:JSON.stringify({display_text:s,id:t})}))}toNativeInteractive(e){let t={quick_reply:s=>({display_text:s.text,id:s.id}),cta_url:s=>({display_text:s.text,url:s.url,merchant_url:s.url}),cta_copy:s=>({display_text:s.text,id:s.id,copy_code:s.copy}),cta_call:s=>({display_text:s.text,phone_number:s.phoneNumber}),single_select:s=>({title:s.text,sections:s.section})};return e.map(s=>({name:s.type,buttonParamsJson:JSON.stringify(t[s.type](s))}))}build(e){let t=g(e).buttons,s=t?.data||[],i=t?.type=="simple"?this.toNativeSimple(s):this.toNativeInteractive(s);return {body:{text:g(e).text},footer:t.footer?{text:t.footer}:void 0,nativeFlowMessage:{buttons:i}}}async send(e,t,s){let r=a.get("socket"),i=r.authState?.creds?.me?.id||r.user?.id,n=this.build(t),c=Yt.generateWAMessageFromContent(e,{interactiveMessage:n},{userJid:i,messageId:Yt.generateMessageIDV2(i),...s});return await r.relayMessage(e,c.message,{messageId:c.key.id,...s,additionalNodes:[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}]}),r.config?.emitOwnEvents&&!Yt.isJidGroup(e)&&process.nextTick(()=>r.upsertMessage?.(c,"append")),c}};var ge=class{constructor(e){this.client=e;}async signal(e,t,s,r){s!="delete"&&(s=="button"?t=Z(Tt,t):t=Z(bt,t));let i=a.get("socket"),n={},c={},p=v__default.default.isString(t),l=this.client.options?.fakeReply?.provider,h=this.client.options?.autoMentions,T=this.client.options?.autoPresence,Y=v__default.default.has(t,"replied"),Ce=v__default.default.has(t,"banner"),F=v__default.default.has(t,"isViewOnce"),Ae=s=="button",$=v__default.default.has(t,"image"),z=v__default.default.has(t,"video"),j=v__default.default.has(t,"audio"),S=v__default.default.has(t,"sticker"),x=v__default.default.has(t,"document"),L=v__default.default.has(t,"location"),_=v__default.default.has(t,"contacts"),Ie=v__default.default.has(t,"poll"),Ke=$||z||j||S||x,U=p?t:C([t],["text","caption"]);if(T&&(j?await i.sendPresenceUpdate("recording",e):await i.sendPresenceUpdate("composing",e)),h&&(n={...n,mentions:Ee(U),contextInfo:{mentionedJid:Ee(U)}}),Y&&(c.quoted=g(t).replied,l&&(c.quoted.key.remoteJid=_e[l],c.quoted.key.participant=_e[l])),Ce&&(n={...n,contextInfo:{externalAdReply:g(t).banner}},n.contextInfo.externalAdReply.mediaType=1),F&&(n={...n,viewOnce:g(t)?.isViewOnce}),U&&(n={...n,text:U,caption:U},Ke&&delete g(n).text),Ke){let k=C([t],["image","video","audio","sticker","document"]),I=v__default.default.isString(k)?{url:k}:k;if($&&(n={...n,image:I,jpegThumbnail:await Ne(k)}),z){let P=g(t)?.ptv;n={...n,video:I,ptv:P,jpegThumbnail:await Ne(k)};}if(j){let P=g(t)?.ptt;n={...n,audio:await rt(k),ptt:P,mimetype:P?"audio/ogg; codecs=opus":"audio/mpeg"};}if(S&&(n={...n,sticker:await nt(k,this.client.options?.sticker)}),x){let P=await ot(k);n={...n,fileName:g(t).fileName,...P};}}if(L){let k=g(t).location;n={...n,location:{degreesLatitude:k.latitude,degreesLongitude:k.longitude,url:k.url,address:k.footer,name:k.title}};}if(_){let k=g(t)?.contacts,He=k?.contacts.map(I=>{let P=["BEGIN:VCARD","VERSION:3.0",`FN:${I.fullname}`,`ORG:${I.organization||""}`,`TEL;type=CELL;type=VOICE;waid=${I.phoneNumber}:${I.phoneNumber}`,"END:VCARD"].join(`
6
+ `);return {displayName:I.fullname,vcard:P}});n={...n,contacts:{displayName:k?.title,contacts:He}};}if(Ie){let k=g(t)?.poll;n={...n,poll:{name:k.name,values:k.answers,selectableCount:k.isMultiple?1:0,toAnnouncementGroup:true}};}return s=="forward"&&(n={...n,contextInfo:{...g(n).contextInfo,isForwarded:true,forwardingScore:g(t).isForwardedMany?9999:1}}),s=="edit"&&(n={...n,edit:r?.key},await i.sendPresenceUpdate("paused",e)),s=="delete"&&(n={...n,delete:r?.key},await i.sendPresenceUpdate("paused",e)),Ae?await new fe().send(e,t,c):await i.sendMessage(e,g(n),c)}async send(e,t){return await this.signal(e,t)}async forward(e,t){return await this.signal(e,t,"forward")}async button(e,t){return await this.signal(e,t,"button")}async edit(e,t){return await this.signal(e.key.remoteJid,t,"edit",e)}async delete(e){return v__default.default.isArray(e)?Promise.all(e.map(t=>this.signal(t.key.remoteJid,{},"delete",t))):await this.signal(e.key.remoteJid,{},"delete",e)}async presence(e,t){let s=a.get("socket"),r={typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"};return await s.sendPresenceUpdate(r[t],e)}async reaction(e,t){return await a.get("socket").sendMessage(e.key.remoteJid,{react:{text:t,key:e?.key}})}};var Ue=class{constructor(e){this.client=e;}async create(e,t){return await a.get("socket").groupCreate(e,t)}async participant(e,t,s){return await a.get("socket").groupParticipantsUpdate(e,t,s)}async profile(e,t,s){let r=a.get("socket"),i=Buffer.isBuffer(t);switch(s){case "subject":if(!i)return await r.groupUpdateSubject(e,t);case "description":if(!i)return await r.groupUpdateDescription(e,t);case "picture":return await r.updateProfilePicture(e,ne(t))}}async setting(e,t){let s=a.get("socket");switch(t){case "open":return await s.groupSettingUpdate(e,"not_announcement");case "close":return await s.groupSettingUpdate(e,"announcement");case "locked":return await s.groupSettingUpdate(e,t);case "unlocked":return await s.groupSettingUpdate(e,t);case "all_member_add":return await s.groupMemberAddMode(e,t);case "admin_add":return await s.groupMemberAddMode(e,t)}}async leave(e){return await a.get("socket").groupLeave(e)}async inviteCode(e,t){let s=a.get("socket");switch(t){case "code":return await s.groupInviteCode(e);case "revoke":return await s.groupRevokeInvite(e);case "accept":return await s.groupAcceptInvite(e);case "info":return await s.groupGetInviteInfo(e)}}async metadata(e){return await a.get("socket").groupMetadata(e)}async requestJoin(e,t,s){let r=a.get("socket");switch(s){case "approve":return await r.groupRequestParticipantsUpdate(e,t,s);case "reject":return await r.groupRequestParticipantsUpdate(e,t,s)}}async requestJoinList(e){return await a.get("socket").groupRequestParticipantsList(e)}async fetchAllGroups(){return await a.get("socket").groupFetchAllParticipating()}async ephemeral(e,t){let s=a.get("socket"),r={off:0,"24h":86400,"7d":604800,"90d":7776e3};return await s.groupToggleEphemeral(e,r[t])}},ye=class{constructor(e){this.glient=e;this.group=new Ue(e);}group};var As=u.z.object({maxMessages:u.z.number().default(20),durationMs:u.z.number().default(1e4)}).optional(),Is=u.z.record(u.z.string(),u.z.function({output:u.z.promise(u.z.array(u.z.number()))})).optional(),Ps=u.z.object({provider:u.z.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).or(u.z.number())}).optional(),Rs=u.z.object({packageName:u.z.string(),authorName:u.z.string(),quality:u.z.number()}).optional(),xt=u.z.object({session:u.z.string().default("zaileys").optional(),prefix:u.z.string().optional(),ignoreMe:u.z.boolean().default(true).optional(),showLogs:u.z.boolean().default(true).optional(),syncFullHistory:u.z.boolean().default(true).optional(),autoMarkAI:u.z.boolean().default(true).optional(),autoMentions:u.z.boolean().default(true).optional(),autoOnline:u.z.boolean().default(true).optional(),autoRead:u.z.boolean().default(true).optional(),autoPresence:u.z.boolean().default(true).optional(),autoRejectCall:u.z.boolean().default(true).optional(),limiter:As,citation:Is,fakeReply:Ps,sticker:Rs}),Es=u.z.object({authType:u.z.literal("pairing"),phoneNumber:u.z.number()}),Ws=u.z.object({authType:u.z.literal("qr")}),St=u.z.union([Es.extend(xt.shape),Ws.extend(xt.shape)]);u.z.enum(["connection","messages","calls"]);var he=class{collect(e,t,s){let r=t.max??1/0;if(r<=0){s([]);return}let i=a.collectors.get(e);i&&(clearTimeout(i.timeoutId),i.callback(i.messages),a.collectors.delete(e));let n=setTimeout(()=>{let c=a.collectors.get(e);c&&(c.callback(c.messages),a.collectors.delete(e));},t.timeout);a.collectors.set(e,{messages:[],max:r,filter:t.filter,callback:s,timeoutId:n});}push(e){let t=a.collectors.get(e.channelId);return !t||t.filter&&!t.filter(e)?false:(t.messages.push(e),t.messages.length>=t.max&&(clearTimeout(t.timeoutId),t.callback(t.messages),a.collectors.delete(e.channelId)),true)}has(e){return a.collectors.has(e)}cancel(e){let t=a.collectors.get(e);return t?(clearTimeout(t.timeoutId),t.callback(t.messages),a.collectors.delete(e),t.messages):[]}};var ke=class{constructor(e){this.client=e;this.initialize();}ready=false;getRoomColor(e){return e?.isNewsletter?"blue":e?.isGroup?e?.isGroup?"lime":"#383838ff":"orange"}initialize(){this.client.options.showLogs&&a.events.on("connection",e=>{e?.status==="open"&&(this.ready=true),this.ready&&(console.log(),a.spinner.info("Logs Indicator:"),console.log(M(" \u2022","orange")+" Private Chat"),console.log(M(" \u2022","lime")+" Group Chat"),console.log(M(" \u2022","blue")+" Newsletter Chat"),console.log());});}message(e){if(!this.ready)return;let t=g(this.getRoomColor(e)),s=e?.text?.toLowerCase()?.match("zaileys"),r=M(`[${new Date(e?.timestamp).toTimeString().split(" ")[0]}]`,"#383838ff"),i=M(`${e?.roomName}`,t),n=e?.text?.slice(0,300)||"",c=n?.length>=300?"...":"",p=`${r} \u2192 ${i}
7
+ `;e?.isNewsletter?p+=`${M("[room]","#383838ff")} \u2192 ${M(`${e?.roomName} (${E(e?.roomId)})`,t)}
8
+ `:p+=`${M("[sender]","#383838ff")} \u2192 ${M(`${e?.senderName} (${E(e?.senderId)})`,t)}
9
+ `,p+=`${M(`[${e?.chatType}]`,"#383838ff")} \u2192 ${M(n+c,s?["#ff5f6d","#ffc371"]:"brown")}
10
+ `,p+="\u2014",console.log(p);}call(e){if(!this.ready)return;let t=g(this.getRoomColor(e)),s=M(`[${new Date(e?.date).toTimeString().split(" ")[0]}]`,"#383838ff"),r=M(`${e?.roomName}`,t),i=`${s} \u2192 ${r}
11
+ `;i+=`${M("[caller]","#383838ff")} \u2192 ${M(`${e?.callerName} (${E(e?.callerId)})`,t)}
12
+ `,i+=`${M(`[${e?.status}]`,"#383838ff")} \u2192 ${M(e?.isVideo?"Video Call":"Voice Call","brown")}
13
+ `,i+="\u2014",console.log(i);}};var we=class{stack=[];use(e){return this.stack.push(e),this}async run(e){let t=-1,s=async r=>{if(r<=t)throw "next() called multiple times";t=r;let i=this.stack[r];if(i)try{await i(e,()=>s(r+1));}catch(n){throw console.error("Middleware error:",n),n}};await s(0);}};var Me=class{plugins=[];pluginsDir;constructor(e=Be__namespace.join(process.cwd(),"plugins")){this.pluginsDir=e;}async load(){if(!ve__namespace.existsSync(this.pluginsDir))return;let e=ve__namespace.readdirSync(this.pluginsDir).filter(t=>(t.endsWith(".ts")||t.endsWith(".js"))&&!t.endsWith(".d.ts"));for(let t of e){let s=Be__namespace.join(this.pluginsDir,t);try{let i=(await import(url.pathToFileURL(s).href)).default;i?.handler&&i?.config&&this.plugins.push(i);}catch{}}}async execute(e,t){let s=t.messages.text||"";for(let r of this.plugins)try{this.match(s,r.config.matcher)&&await r.handler(e,t);}catch{}}match(e,t){return t.some(s=>e===s||e.startsWith(s+" "))}getLoadedPlugins(){return this.plugins}getPluginsInfo(){return this.plugins.map(e=>({matcher:e.config.matcher,metadata:e.config.metadata}))}async reload(){this.plugins=[],await this.load();}},Qn=(o,e)=>({handler:o,config:e});var be=class{classInjection(e,t){let s=t.length;return new Proxy(e,{get(r,i,n){if(i in r){let c=Reflect.get(r,i,n);return typeof c=="function"?c.bind(r):c}for(let c=0;c<s;c++){let p=t[c];if(i in p){let l=Reflect.get(p,i,n);return typeof l=="function"?l.bind(p):l}}},set(r,i,n,c){if(i in r)return Reflect.set(r,i,n,c);for(let p=0;p<s;p++){let l=t[p];if(i in l)return Reflect.set(l,i,n,c)}return Reflect.set(r,i,n,c)},has(r,i){if(i in e)return true;for(let n=0;n<s;n++)if(i in t[n])return true;return false},ownKeys(){let r=[];for(let i of Reflect.ownKeys(e))r.push(i);for(let i=0;i<s;i++)for(let n of Reflect.ownKeys(t[i]))r.includes(n)||r.push(n);return r},getOwnPropertyDescriptor(r,i){let n=Object.getOwnPropertyDescriptor(e,i);if(n)return n;for(let c=0;c<s;c++)if(n=Object.getOwnPropertyDescriptor(t[c],i),n)return n}})}};var Ve=class{constructor(e){this.client=e;}async block(e){return await a.get("socket").updateBlockStatus(e,"block")}async unblock(e){return await a.get("socket").updateBlockStatus(e,"unblock")}async lastSeen(e){return await a.get("socket").updateLastSeenPrivacy(e)}async online(e){return await a.get("socket").updateOnlinePrivacy(e)}async picture(e){return await a.get("socket").updateProfilePicturePrivacy(e)}async status(e){return await a.get("socket").updateStatusPrivacy(e)}async readReceipt(e){return await a.get("socket").updateReadReceiptsPrivacy(e)}async groupsAdd(e){return await a.get("socket").updateGroupsAddPrivacy(e)}async ephemeral(e){let t=a.get("socket"),s={off:0,"24h":86400,"7d":604800,"90d":7776e3};return await t.updateDefaultDisappearingMode(s[e])}async blocklist(){return await a.get("socket").fetchBlocklist()}async getSettings(){return await a.get("socket").fetchPrivacySettings(true)}},Te=class{constructor(e){this.plient=e;this.privacy=new Ve(e);}privacy};var Je=class{constructor(e){this.client=e;}async create(e,t){return await a.get("socket").newsletterCreate(e,t)}async action(e,t){let s=a.get("socket");switch(t){case "follow":return await s.newsletterFollow(e);case "unfollow":return await s.newsletterUnfollow(e);case "mute":return await s.newsletterMute(e);case "unmute":return await s.newsletterUnmute(e);}}async update(e,t,s){let r=a.get("socket"),i=Buffer.isBuffer(t);switch(s){case "name":if(!i)return await r.newsletterUpdateName(e,t);case "description":if(!i)return await r.newsletterUpdateDescription(e,t);case "picture":return await r.newsletterUpdatePicture(e,ne(t))}}async metadata(e,t){return await a.get("socket").newsletterMetadata(t,e)}async subscribers(e){return await a.get("socket").newsletterSubscribers(e)}async reaction(e,t,s){return await a.get("socket").newsletterReactMessage(e,t,s)}async fetchMessages(e,t,s,r){let i=a.get("socket"),n=s.getTime()/1e3,c=r.getTime()/1e3;return await i.newsletterFetchMessages(e,t,n,c)}async adminCount(e){return await a.get("socket").newsletterAdminCount(e)}async changeOwner(e,t){return await a.get("socket").newsletterChangeOwner(e,t)}async demote(e,t){return await a.get("socket").newsletterDemote(e,t)}async delete(e){return await a.get("socket").newsletterDelete(e)}async removePicture(e){return await a.get("socket").newsletterRemovePicture(e)}},xe=class{constructor(e){this.nlient=e;this.newsletter=new Je(e);}newsletter};var Ge=class{constructor(e){this.client=e;}async create(e,t){return await a.get("socket").communityCreate(e,t)}async createGroup(e,t,s){return await a.get("socket").communityCreateGroup(e,t,s)}async leave(e){return await a.get("socket").communityLeave(e)}async metadata(e){return await a.get("socket").communityMetadata(e)}async update(e,t,s){let r=a.get("socket");switch(t){case "subject":return await r.communityUpdateSubject(e,s);case "description":return await r.communityUpdateDescription(e,s)}}async group(e,t,s){let r=a.get("socket");switch(t){case "link":if(!s)throw "Group JID is required for linking";return await r.communityLinkGroup(e,s);case "unlink":if(!s)throw "Group JID is required for unlinking";return await r.communityUnlinkGroup(e,s);case "linked":return await r.communityFetchLinkedGroups(e)}}async participants(e,t,s,r){let i=a.get("socket");switch(t){case "list":return await i.communityRequestParticipantsList(e);case "request-update":return await i.communityRequestParticipantsUpdate(e,r,g(s));case "update":if(!s||!r)throw "Action and participants are required for update";return await i.communityParticipantsUpdate(e,r,g(s));case "all":return await i.communityFetchAllParticipating()}}async invite(e,t,...s){let r=a.get("socket");switch(t){case "code":return await r.communityInviteCode(e);case "revoke":return await r.communityRevokeInvite(e);case "accept":return await r.communityAcceptInvite(e);case "info":return await r.communityGetInviteInfo(e);case "revokeV4":return await r.communityRevokeInviteV4(e,s[0]);case "acceptV4":return await r.communityAcceptInviteV4(e,s[0])}}async settings(e,t,s){let r=a.get("socket");switch(t){case "ephemeral":return await r.communityToggleEphemeral(e,s);case "update":return await r.communitySettingUpdate(e,s);case "memberAdd":return await r.communityMemberAddMode(e,s);case "approval":return await r.communityJoinApprovalMode(e,s)}}},Se=class{constructor(e){this.mlient=e;this.community=new Ge(e);}community};var Ct=class{constructor(e){this.options=e;return this.options=Z(St,e),this._ready=this.initialize(),new be().classInjection(this,[new ge(this),new ye(this),new Te(this),new xe(this),new Se(this)])}listener;_ready;logs;collector=new he;middleware=new we;plugins=new Me;async initialize(){await yt(),await dt(this),await this.plugins.load(),this.listener=new de(this),this.logs=new ke(this);}ready(){return this._ready}db(e){return a.lowdb(this.options.session,`stores/${e}.json`)}on(e,t){a.events.on(e,t);}use(e){return this.middleware.use(e),this}async getMessageByChatId(e){let s=(await this.db("messages").all())?.flat()?.filter(r=>typeof r=="object")?.flat()?.find(r=>r?.key?.id===e);return await this.listener.messages.parse(s)}async getRoomName(e){let t=await this.db("chats").get(e),s=await this.db("contacts").get(e),r=C(t,["name","verifiedName"]),i=C(s,["notify","name"]);return R(r||i)||null}};
14
+ /*
15
+ * Copyright (c) 2025 zaadevofc.
16
+ * All rights reserved.
17
+ * Licensed under the MIT License.
18
+ * See LICENSE file for details.
19
+
20
+ * Author: zaadevofc
21
+ * Last build time: 12/9/2025 12:00:50 PM
22
+ *
23
+ * Repository: git+https://github.com/zeative/zaileys.git
24
+ */exports.AudioProcessor=te;exports.Client=Ct;exports.DocumentProcessor=re;exports.ImageProcessor=se;exports.Lowdb=$e;exports.MediaProcessor=H;exports.Plugins=Me;exports.StickerProcessor=ie;exports.VideoProcessor=W;exports.cleanJid=E;exports.cleanMediaObject=it;exports.createLowdb=q;exports.definePlugins=Qn;exports.extractJids=Ee;exports.extractUrls=et;exports.findGlobalWord=ee;exports.findNestedByKeys=tt;exports.generateId=B;exports.getDeepContent=J;exports.getLatestLibVersion=Qe;exports.getMediaThumbnail=Ne;exports.getUsersMentions=st;exports.getVideoDuration=ki;exports.getVideoThumbnail=hi;exports.getWaAudio=rt;exports.getWaDocument=ot;exports.getWaSticker=nt;exports.ignoreLint=g;exports.logColor=M;exports.modifyFn=Ys;exports.normalizeText=R;exports.numbersToJids=ri;exports.pickKeysFromArray=C;exports.randomize=Qs;exports.registerAuthCreds=dt;exports.removeAuthCreds=Ye;exports.shuffleString=Zs;exports.toBuffer=ne;exports.toJson=Re;exports.toString=X;exports.useAuthState=ut;