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