zaileys 2.0.16 → 2.1.1
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/README.MD +103 -24
- package/dist/index.d.mts +96 -79
- package/dist/index.d.ts +96 -79
- package/dist/index.js +15 -15
- package/dist/index.mjs +15 -15
- package/package.json +77 -77
- package/tsconfig.json +1 -1
- package/.github/workflows/gsearch.yml +0 -56
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import ps,{URL_REGEX,extractMessageContent,getContentType,BufferJSON,initAuthCreds,proto,makeCacheableSignalKeyStore,generateWAMessageFromContent,generateMessageIDV2,isJidGroup,delay,DisconnectReason,jidNormalizedUser,getDevice,downloadMediaMessage}from'baileys';import _e,{readFile,mkdir,writeFile,unlink,readdir,rmdir,stat}from'fs/promises';import {Mutex}from'async-mutex';import*as ze from'path';import ze__default,{dirname,join}from'path';import {createSpinner}from'nanospinner';import He from'node-cache';import {EventEmitter}from'events';import qt from'pino';import rt,{cristal}from'gradient-string';import x from'lodash';import {fileTypeFromBuffer}from'file-type';import ee from'fluent-ffmpeg';import Ht from'node-webpmux';import {tmpdir}from'os';import $e from'sharp';import*as j from'fs';import {promises}from'fs';import ms from'figlet';import fs from'qrcode-terminal';import {RateLimiterMemory}from'rate-limiter-flexible';import u,{z as z$1}from'zod';import Vs from'stream';import {pathToFileURL}from'url';var Oe=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 o=Z(s);return this.cache.set(s,o),o}spinner=createSpinner("",{color:"green"});logger=qt({level:"silent",enabled:false});events=new EventEmitter;groupCache=new He({stdTTL:300,useClones:false});collectors=new Map},r=new Oe;var k=a=>a,ot=async()=>{try{return (await(await fetch("https://registry.npmjs.org/zaileys")).json())["dist-tags"].latest}catch(a){throw a}},it=async a=>{try{let e=`.session/${a}/auth/creds.json`;await _e.unlink(e);}catch(e){throw r.spinner.error(`Failed to remove auth creds for session "${a}"!`),e}},P=(a="")=>a?.length?a.normalize("NFKD").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\uFFF9-\uFFFB]/gu,"").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u20D0-\u20FF\uFE20-\uFE2F]/gu,"").replace(/[\u202A-\u202E\u2066-\u2069]/gu,"").replace(/\u202E([\s\S]*?)\u202C?/gu,(t,s)=>[...s].reverse().join("")):null;var M=(a,e="lime")=>Array.isArray(e)?rt(e)(a):rt([e,e])(a),Le=a=>{try{return JSON.parse(a)}catch{return x.attempt(()=>JSON.parse(JSON.stringify(a)||"{}"))}},Q=a=>{try{return JSON.stringify(a)}catch{let e=x.attempt(()=>JSON.stringify(Le(a)||"{}"));return x.isError(e)?"{}":e}},un=(a="")=>x.shuffle(a).join(""),Y=(a="",e="")=>a?x.includes(a.toLowerCase(),e.toLowerCase()):null,at=(a="")=>a?x.castArray(a.match(URL_REGEX)||[]):[],mn=a=>a[Math.floor(Math.random()*a.length)],I=(a,e)=>{let t=(s,o)=>{if(!s||typeof s!="object")return;let n=s;for(let i of o.split("."))if(n=n?.[i],n==null)return;return n};for(let s of a||[])if(s&&typeof s=="object")for(let o of e){let n=t(s,o);if(n!=null)return n}},ct=(a,e)=>{let t=x.castArray(e),s=(i,c)=>x.every(c,(l,p)=>i?.[p]===l),o=(i,c)=>x.some(c,(l,p)=>i?.[p]===l),n=i=>x.isArray(i)?x.find(i,n)??i:x.isObject(i)?x.find(t,p=>s(i,p))||x.find(t,p=>o(i,p))?i:x.find(x.values(i),n)??i:null;return n(a)},dn=(a,e,t)=>new Proxy(a,{apply(s,o,n){e?.(n);let i=Reflect.apply(s,o,n);return t?t(i,n):i}});var z=a=>{let e;Array.isArray(a)?e=a.join("|"):typeof a=="string"?e=a:e=String(a);let t=2166136261,s=e.length;for(let o=0;o<s;o++)t^=e.charCodeAt(o),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return "Z4D3FC"+(t>>>0).toString(16).padStart(8,"0").toUpperCase()},lt=(a="")=>{if(!a)return [];let e=new Set;for(let t of a.matchAll(/@(\d+)/g))e.add(t[1]);return x.toArray(e)},Be=(a="")=>{if(!a)return [];let e=new Set;for(let t of a.matchAll(/@(\d+)/g))t[1].length<=15&&e.add(t[1]);return x.flatMap([...e],t=>[`${t}@s.whatsapp.net`,`${t}@g.us`,`${t}@lid`])},wn=a=>x.isEmpty(a)?[]:x.map([...a],e=>`${e}@s.whatsapp.net`),pt=a=>x.omit(a,["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"]),re=a=>{if(!a)return {leaf:void 0,chain:[]};let e=extractMessageContent(a)||a,t=[];for(;e&&typeof e=="object";){let s=getContentType(e);if(!s)break;t.push(s);let o=e[s];if(!o||typeof o!="object"){e=o;break}e=o;}return {leaf:e,chain:t}},N=a=>Number(a?.split("@")[0]);var ut=async(a=false)=>{if(!a)try{let e=(await import('@ffmpeg-installer/ffmpeg')).default,t=(await import('@ffprobe-installer/ffprobe')).default;ee.setFfmpegPath(e.path),ee.setFfprobePath(t.path);}catch{}},w={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"}},b=class{static generateUniqueId(){return `${Date.now()}_${Math.random().toString(36).slice(2,11)}`}static createTempPath(e,t){return ze__default.join(tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>_e.unlink(t)));}static async safeReadFile(e){try{return await _e.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await _e.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},E=class{static async toBuffer(e){if(x.isBuffer(e))return e;if(x.isArrayBuffer(e))return Buffer.from(e);if(x.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}`)}}},U=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(w.MIME.IMAGE)||e.startsWith(w.MIME.VIDEO)}static isAnimated(e){return e===w.MIME.GIF||e.startsWith(w.MIME.VIDEO)}},te=class{static async process(e){return new Promise((t,s)=>{let o=ee(e.input).output(e.output);for(let n=0;n<e.options.length;n++){let i=e.options[n];i.startsWith("-")&&n+1<e.options.length&&!e.options[n+1].startsWith("-")?(o.outputOptions(i,e.options[n+1]),n++):o.outputOptions(i);}o.on("end",async()=>{try{await e.onEnd(),t();}catch(n){s(n);}}).on("error",async n=>{try{await e.onError(n);}finally{s(n);}}).run();})}static async getDuration(e){return new Promise((t,s)=>{ee.ffprobe(e,(o,n)=>{if(o)return s(o);t(n.format.duration||0);});})}},ae=class{static async getWaAudio(e,t="opus"){let s=await E.toBuffer(e),o=await fileTypeFromBuffer(s);U.validate(o,w.MIME.AUDIO);let n=b.createTempPath("audio_in","wav"),i=t==="opus"?"ogg":"mp3",c=b.createTempPath("audio_out",i);await b.safeWriteFile(n,s);let l;try{let p=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 te.process({input:n,output:c,options:p,onEnd:async()=>{l=await b.safeReadFile(c);},onError:async()=>{await b.cleanup([n,c]);}}),await b.cleanup([n,c]),l}catch(p){throw await b.cleanup([n,c]),new Error(`${t.toUpperCase()} conversion failed: ${p.message}`)}}},F=class{static async getThumbnail(e){let t=await E.toBuffer(e),s=await fileTypeFromBuffer(t);U.validate(s,w.MIME.VIDEO);let o=b.createTempPath("video","mp4"),n=b.createTempPath("thumb","jpg");await b.safeWriteFile(o,t);let i;try{return await new Promise((c,l)=>{ee(o).screenshots({timestamps:[w.THUMBNAIL.TIMESTAMP],filename:ze__default.basename(n),folder:ze__default.dirname(n),size:`${w.THUMBNAIL.SIZE}x${w.THUMBNAIL.SIZE}`,quality:w.THUMBNAIL.QUALITY}).on("end",async()=>{try{i=(await b.safeReadFile(n)).toString("base64"),c();}catch(p){l(p);}}).on("error",l);}),await b.cleanup([o,n]),i}catch(c){throw await b.cleanup([o,n]),new Error(`Thumbnail generation failed: ${c.message}`)}}static async getDuration(e){return te.getDuration(e)}},ce=class{static async getThumbnail(e){return (await((await fileTypeFromBuffer(e)).mime===w.MIME.GIF?$e(e,{animated:false}):$e(e)).resize(w.THUMBNAIL.SIZE,w.THUMBNAIL.SIZE,{fit:"cover"}).jpeg({quality:w.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}static async resizeForSticker(e,t){return $e(e).resize(w.STICKER.SIZE,w.STICKER.SIZE,{fit:"cover",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:t}).toBuffer()}},se=class{static async getThumbnail(e){let t=await E.toBuffer(e),s=await fileTypeFromBuffer(t);if(!s||!U.isMedia(s.mime))throw new Error("Invalid media type: expected image or video");return s.mime.startsWith(w.MIME.VIDEO)?F.getThumbnail(e):ce.getThumbnail(t)}},le=class{static createExifMetadata(e){let t={"sticker-pack-id":z(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]),o=Buffer.from(JSON.stringify(t),"utf8"),n=Buffer.concat([s,o]);return n.writeUIntLE(o.length,14,4),n}static async processAnimated(e,t,s){let o=this.getExtension(t),n=b.createTempPath("sticker_in",o),i=b.createTempPath("sticker_out","webp");await b.safeWriteFile(n,e);let c=w.STICKER.MAX_DURATION;try{let T=await F.getDuration(n);c=k(Math.min(T,w.STICKER.MAX_DURATION));}catch{console.warn("Using default duration:",w.STICKER.MAX_DURATION);}let l=`scale=${w.STICKER.SIZE}:${w.STICKER.SIZE}:force_original_aspect_ratio=increase,crop=${w.STICKER.SIZE}:${w.STICKER.SIZE},fps=${w.STICKER.FPS},format=rgba`,p=Math.max(1,Math.min(100,100-s)),h;try{return await te.process({input:n,output:i,options:["-vcodec libwebp",`-vf ${l}`,`-q:v ${p}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${c}`,`-compression_level ${w.STICKER.COMPRESSION_LEVEL}`],onEnd:async()=>{h=await b.safeReadFile(i);},onError:async()=>{await b.cleanup([n,i]);}}),await b.cleanup([n,i]),h}catch(T){throw await b.cleanup([n,i]),new Error(`Animated sticker processing failed: ${T.message}`)}}static getExtension(e){return e===w.MIME.GIF?"gif":e.startsWith(w.MIME.VIDEO)?"mp4":"tmp"}static async create(e,t){try{let s=await E.toBuffer(e),o=await fileTypeFromBuffer(s);if(!o)throw new Error("Unable to detect file type");let n=t?.quality||w.STICKER.DEFAULT_QUALITY,c=U.isAnimated(o.mime)?await this.processAnimated(s,o.mime,n):await ce.resizeForSticker(s,n),l=this.createExifMetadata(t),p=new Ht.Image;await p.load(c),p.exif=l;let h=await p.save(null);return Buffer.isBuffer(h)?h:Buffer.from(h)}catch(s){throw new Error(`Sticker creation failed: ${s.message||s}`)}}},pe=class{static async create(e){try{let t=await E.toBuffer(e),s=await fileTypeFromBuffer(t);if(!s)throw new Error("Unable to detect file type");return {document:t,mimetype:s.mime,fileName:z(Date.now().toString()),jpegThumbnail:await se.getThumbnail(t)}}catch(t){throw new Error(`Document creation failed: ${t.message||t}`)}}},ue=E.toBuffer.bind(E),mt=ae.getWaAudio.bind(ae),Wn=F.getThumbnail.bind(F),Dn=F.getDuration.bind(F),Ue=se.getThumbnail.bind(se),dt=le.create.bind(le),ft=pe.create.bind(pe);var yt=a=>{if(a)try{a.ev?.removeAllListeners(),a.end?.(new Error("Cleanup"));}catch{}},me=async a=>{let e=`.session/${a}/auth/keys.json`;try{let t=await promises.readFile(e,"utf-8"),s=JSON.parse(t),o=["sender-key:","session:"],n={},i=!1;for(let[c,l]of Object.entries(s))o.some(h=>c.startsWith(h))?i=!0:n[c]=l;i&&(await promises.writeFile(e,JSON.stringify(n,null,2)),r.spinner.success(" Session keys repaired successfully"));}catch{r.spinner.warn(" Could not repair session keys, will re-negotiate");}},ht=()=>{let a=r.get("socket");return a?.end?a:null};var Qt=6e4,Yt=12e4,Xt=6e4,es=3,qe=class{lastActivityTime=Date.now();lastRecoveryTime=0;checkInterval=null;isRecovering=false;retryCount=0;options;constructor(e){this.options={checkIntervalMs:Qt,staleThresholdMs:Yt,cooldownMs:Xt,maxRetries:es,onRecovery:async()=>{},...e};}start(){this.checkInterval||(this.lastActivityTime=Date.now(),this.setupActivityListeners(),this.checkInterval=setInterval(()=>this.check(),this.options.checkIntervalMs),r.spinner.success(" Session watchdog started"));}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null);}touch(){this.lastActivityTime=Date.now(),this.retryCount=0;}setupActivityListeners(){let e=r.get("socket");if(!e?.ev)return;let t=["messages.upsert","message-receipt.update","presence.update","chats.update"];for(let s of t)e.ev.on(s,()=>this.touch());}async check(){if(this.isRecovering)return;Date.now()-this.lastActivityTime>this.options.staleThresholdMs&&await this.recover();}isInCooldown(){return Date.now()-this.lastRecoveryTime<this.options.cooldownMs}async recover(){if(!this.isRecovering){if(this.isInCooldown()){r.spinner.warn(" Recovery in cooldown, skipping...");return}if(this.retryCount>=this.options.maxRetries){r.spinner.error(` Max recovery retries (${this.options.maxRetries}) reached. Manual restart required.`);return}this.isRecovering=true,this.lastRecoveryTime=Date.now(),this.retryCount++;try{r.spinner.warn(` Session recovery attempt ${this.retryCount}/${this.options.maxRetries}...`);let e=r.get("socket");if(e?.ws?.readyState===1)try{await e.fetchStatus(e.user?.id||""),this.touch(),r.spinner.success(" Session health check passed");return}catch{}await me(this.options.session),r.spinner.warn(" Forcing reconnection..."),await this.options.onRecovery(),this.touch();}catch{r.spinner.error(" Recovery failed");}finally{this.isRecovering=false;}}}async forceRecovery(){if(this.isInCooldown()){r.spinner.warn(" Recovery blocked by cooldown");return}await this.recover();}},ne=null,kt=a=>(ne&&ne.stop(),ne=new qe(a),ne),zn=()=>ne;var Ge=class a{static inst;fLocks=new Map;kLocks=new Map;maxSize=100;static get(){return this.inst||(this.inst=new a)}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}},Ke=class{data;path;pool;size;chunkDir;replacer;reviver;loaded=false;flushMode;debounceMs;flushTimer=null;dirty=false;constructor(e,t,s=2*1024*1024,o="debounce",n=200){this.data=new Map,this.path=e,this.pool=Ge.get(),this.size=s,this.chunkDir=`${e}.c`,this.replacer=t?.replacer||null,this.reviver=t?.reviver||null,this.flushMode=o,this.debounceMs=n;}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 o=[];for(let[n,i]of Object.entries(s))this.isMeta(i)?o.push(this.loadChunk(n,i)):this.data.set(n,i);return await Promise.all(o),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[n,i]of this.data){if(this.isMeta(i)){t[n]=i;continue}JSON.stringify(i,this.replacer).length>this.size?s.push(this.saveChunk(n,i).then(l=>{t[n]=l;})):t[n]=i;}await Promise.all(s);let o=JSON.stringify(t,this.replacer,2);await writeFile(this.path,o,"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 o=this.data.get(e),n;Array.isArray(o)?n=o:o===void 0?n=[]:n=[o],n.push(t),this.data.set(e,n),this.scheduleFlush();});}async upsert(e,t,s="key.id"){await this.ensureLoaded(),await this.pool.getKey(e).runExclusive(async()=>{let n=this.data.get(e),i;Array.isArray(n)?i=n:n===void 0?i=[]:i=[n];let c=x.get(t,s);if(c){let l=i.findIndex(p=>x.get(p,s)===c);l>=0?i[l]=t:i.push(t);}else 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 ct(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 o=this.data.delete(e);return this.scheduleFlush(),o})}async saveChunk(e,t){let s=JSON.stringify(t,this.replacer),o=Buffer.from(s,"utf-8"),n=Math.ceil(o.length/this.size);await mkdir(this.chunkDir,{recursive:true});let i={v:1,k:e,t:n,s:this.size,c:o.length,m:Date.now().toString(36)},c=[];for(let l=0;l<n;l++){let p=l*this.size,h=Math.min(p+this.size,o.length),T=o.subarray(p,h);c.push(writeFile(join(this.chunkDir,`${e}.${l}.json`),JSON.stringify({i:l,d:T.toString("base64")})));}return c.push(writeFile(join(this.chunkDir,`${e}.manifest.json`),JSON.stringify(i))),await Promise.all(c),{t:n,s:this.size,k:e}}async loadChunk(e,t){let s=join(this.chunkDir,`${e}.manifest.json`),o=JSON.parse(await readFile(s,"utf-8")),n=[];for(let p=0;p<o.t;p++)n.push(readFile(join(this.chunkDir,`${e}.${p}.json`),"utf-8").then(h=>Buffer.from(JSON.parse(h).d,"base64")));let i=await Promise.all(n),c=Buffer.concat(i),l=JSON.parse(c.toString("utf-8"),this.reviver);this.data.set(e,l);}async delChunk(e,t){let s=[];for(let o=0;o<t.t;o++)s.push(unlink(join(this.chunkDir,`${e}.${o}.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}},Z=(a,e)=>new Ke(a,e?.BufferJSON,e?.size,e?.flushMode,e?.debounceMs);var St=async a=>{r.spinner.start(" Initializing auth state...");let e=await stat(a).catch(()=>{});if(e){if(!e.isDirectory())throw r.spinner.error(` Failed to open credentials
|
|
2
|
-
`),`found something that is not a directory at ${a}, either delete it or specify a different location`}else await mkdir(a,{recursive:true});let t=Z(`${a}/auth/creds.json`,{BufferJSON:BufferJSON}),s=Z(`${a}/auth/keys.json`,{BufferJSON:BufferJSON,size:512*1024});await Promise.all([t.read(),s.read()]);let o=await t.get("creds")||initAuthCreds();return r.spinner.success(" Generate auth successfully"),{state:{creds:o,keys:{get:async(n,i)=>{let c={};return await Promise.all(i.map(async l=>{let p=`${n}:${l}`,h=await s.get(p);n==="app-state-sync-key"&&h&&(h=proto.Message.AppStateSyncKeyData.fromObject(h)),c[l]=h;})),c},set:async n=>{let i=[];for(let c in n)for(let l in n[c]){let p=n[c][l],h=`${c}:${l}`;p?i.push(s.set(h,p)):i.push(s.delete(h).then(()=>{}));}await Promise.all(i),await s.write();}}},saveCreds:async()=>{await t.set("creds",o),await t.write();}}};var ls=new He,Tt=(a,e)=>({logger:r.logger,printQRInTerminal:false,defaultQueryTimeoutMs:void 0,markOnlineOnConnect:a.options.autoOnline,syncFullHistory:a.options.syncFullHistory,msgRetryCounterCache:new He,mediaCache:new He({stdTTL:60}),cachedGroupMetadata:async t=>ls.get(t),auth:{creds:e.creds,keys:makeCacheableSignalKeyStore(e.keys,r.logger)},getMessage:async t=>t?.remoteJid?(await a.db("messages").get(t.remoteJid))?.find(n=>n?.key?.id===t.id):void 0});var Ct=async a=>{let e=ht();e&&yt(e);let t=`.session/${a.options.session}`;console.info=()=>{};let{state:s,saveCreds:o}=await St(t),n=Tt(a,s),i=ps(n);i.ev.on("creds.update",o),r.set("socket",i);};var de=class{constructor(e){this.client=e;this.initialize();}async initialize(){let e=r.get("socket");e.ev.on("call",async t=>{for(let s of t){let o=await this.parse(s);o&&(await this.client.middleware.run({calls:o}),await this.client.plugins.execute(this.client,{messages:o}),r.events.emit("calls",o),this.client.options?.autoRejectCall&&await e.rejectCall(o.callId,o.callerId));}});}async parse(e){let t=r.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=P(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 fe={version:"2.0.15",author:"zaadevofc"};var It=a=>{fs.generate(a,{small:true},e=>{console.log(e);});},Rt=async()=>{console.clear(),r.spinner.start(" Checking for updates...");let a=await ot(),e=fe.version===a;r.spinner.stop();let t="Zaileys",s=`
|
|
3
|
-
by ${
|
|
4
|
-
`,
|
|
5
|
-
`);return}if(p===500){r.spinner.error(" Server error occurred, attempting reconnect..."),await s();return}T&&await s();}if(i==="open")if(e.user?.id){let p=jidNormalizedUser(e.user.id).split("@")[0],h=e.user.name||e.user.verifiedName;r.spinner.success(` Connected as ${cristal(h||p)}`);}else r.spinner.success(" Connected!");r.events.emit("connection",t);}),e.ev.on("messaging-history.set",({progress:n})=>{t.status="syncing",t.syncProgress=n,r.spinner.start(" Syncing messages history..."),n&&r.spinner.update(` Syncing messages history ${n+"%"}`),n==100&&(r.spinner.success(" Syncing messages history completed!"),t.syncCompleted=true),r.events.emit("connection",t);});}};var Pt={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"},Ze={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 ke=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 ve=class{constructor(e){this.client=e;this.limiter=new ke(e),this.initialize();}limiter;maxReplies=3;async initialize(){let e=r.get("socket");e.ev.on("messages.upsert",async({messages:t,type:s})=>{if(s==="notify")for(let o of t){let n=await this.parse(o);n&&(this.client.collector.push(n)||(await this.client.middleware.run({messages:n}),await this.client.plugins.execute(this.client,{messages:n}),r.set("message",n),r.events.emit("messages",n)),this.client.options.autoRead&&await e.readMessages([n.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,o=r.get("socket"),n={},i=re(e.message),c=i.chain.at(-1),l=i.leaf;l?.message&&(i=re(l.message),c=i.chain.at(-1),l=i.leaf),n.uniqueId=null,n.channelId=null,n.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id||null,n.chatType=Pt[c],n.receiverId=jidNormalizedUser(o?.user?.id||""),n.receiverName=P(o?.user?.name||o?.user?.verifiedName),n.roomId=jidNormalizedUser(e?.key?.remoteJid);let p=l?.type===0,h=l?.type===1,T=l?.type===2,$=n.roomId?.includes("@newsletter"),De=!!e?.message?.questionMessage,J=e?.key?.fromMe||false;if(J&&this.client.options.ignoreMe&&t!=="replied")return;let Ne=l?.key?.id;if(p||h||T){let C=(await this.client.db("messages").get(n.roomId))?.find(_=>_.key.id===Ne);if(!C)return;e=C,i=re(e.message),c=i.chain.at(-1),l=i.leaf;}if(n.roomName=await this.client.getRoomName(n.roomId),n.senderLid=I([e?.key],["remoteJidAlt","participant"])||null,n.senderId=jidNormalizedUser(e?.participant||e?.key?.participant||e?.key?.remoteJid),n.senderName=P(e?.pushName||e?.verifiedBizName),n.senderDevice=getDevice(n.chatId),n.channelId=z([n.roomId,n.senderId]),n.uniqueId=z([n.channelId,n.chatId]),n.timestamp=Number(e?.messageTimestamp)*1e3,$){let R=await o.newsletterMetadata("jid",n.roomId);n.roomName=k(R.thread_metadata.name)?.text,n.senderId=null,n.senderLid=null;}if(J&&(n.senderLid=jidNormalizedUser(o.user.lid),n.senderId=n.receiverId,n.senderName=n.receiverName),n.text=l?.text||l?.caption||l?.name||l?.displayName||l?.conversation||l?.contentText||l?.selectedDisplayText||l||null,l?.name=="menu_options"&&(n.text=Le(l?.paramsJson)?.id),n.text=P(n.text),n.mentions=lt(n.text),n.links=at(n.text||""),n.isBot=n.chatId.startsWith("BAE5")||n.chatId.startsWith("3EB0")||n.chatId.startsWith("Z4D3FC"),n.isFromMe=J,n.isTagMe=n.mentions?.includes(n.receiverId.split("@")[0]),n.isPrefix=n.text?.startsWith(this.client.options?.prefix)||false,n.isSpam=await this.limiter.isSpam(n.channelId),n.isPrefix&&(n.text=n.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),n.isGroup=n.roomId?.includes("@g.us"),n.isNewsletter=$,n.isQuestion=De,n.isStory=n.roomId?.includes("@broadcast"),!n.isGroup&&!n.roomName&&(n.roomName=n.senderName),n.isViewOnce=false,n.isEdited=!!Y(Q(i),"editedMessage"),n.isDeleted=p,n.isPinned=h,n.isUnPinned=T,n.isBroadcast=!!e?.broadcast,n.isEphemeral=!!Y(Q(l?.contextInfo),"ephemeralSettingTimestamp"),n.isForwarded=!!Y(Q(l?.contextInfo),"forwardingScore"),n.citation=null,this.client.options.citation){n.citation=n.citation||{};let R=this.client.options.citation;for(let C of Object.keys(R)){let _=R[C];n.citation[C]=async()=>{let K=await _(),Fe=[N(n.roomId),N(n.senderLid),N(n.senderId)];return !!x.intersection(Fe,K).length};}}n.chatType!=="text"&&(n.media={...pt(l),buffer:()=>downloadMediaMessage(e,"buffer",{}),stream:()=>downloadMediaMessage(e,"stream",{})}),n.message=()=>s,n.replied=null;let L=l?.contextInfo?.quotedMessage,B=I([L],["viewOnceMessageV2Extension","viewOnceMessage"]);B=Y(Q(L),"viewOnce")?L:B;let G=l?.contextInfo?.stanzaId;if(L&&this.maxReplies){this.maxReplies--;let C=(await this.client.db("messages").get(n.roomId))?.find(K=>K.key.id===G),_={...C,message:B};B?(n.replied=await this.parse(_,"replied"),n.replied.isViewOnce=true):n.replied=await this.parse(C,"replied"),this.maxReplies=3;}return t!="replied"&&this.client.logs.message(n),n}};var be=class{constructor(e){this.client=e;this.connection=new he(e),this.messages=new ve(e),this.calls=new de(e),this.initialize();}connection;messages;calls;async initialize(){let e=r.get("socket");e.ev.on("groups.update",async([t])=>{let s=await e.groupMetadata(t.id);r.groupCache.set(t.id,s);}),e.ev.on("group-participants.update",async t=>{let s=await e.groupMetadata(t.id);r.groupCache.set(t.id,s);}),e?.ev.on("messaging-history.set",async t=>{let{chats:s,contacts:o,messages:n}=t;for(let i of s)await this.client.db("chats").upsert(i.id,i,"id");for(let i of o)await this.client.db("contacts").upsert(i.id,i,"id");for(let i of n){if(!i.message&&!i.key.isViewOnce||i?.category==="peer"||i.message?.protocolMessage&&!i.message?.protocolMessage?.memberLabel||i.message?.groupStatusMentionMessage)return;await this.client.db("messages").upsert(i.key.remoteJid,i,"key.id");}}),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?.protocolMessage?.memberLabel||s.message?.groupStatusMentionMessage)return;await this.client.db("messages").upsert(s.key.remoteJid,s,"key.id");}}),e?.ev.on("chats.upsert",async t=>{for(let s of t)await this.client.db("chats").upsert(s.id,s,"id");}),e?.ev.on("contacts.upsert",async t=>{for(let s of t)await this.client.db("contacts").upsert(s.id,s,"id");});}};var oe=(a,e)=>{let t=a.safeParse(e);if(t.success)return t.data;throw console.error(t.error),"Invalid data"};var vs=u.object({type:u.literal("quick_reply"),text:u.string()}),bs=u.object({type:u.literal("cta_url"),url:u.url(),text:u.string()}),Ms=u.object({type:u.literal("cta_copy"),copy:u.string(),text:u.string()}),xs=u.object({type:u.literal("cta_call"),text:u.string(),phoneNumber:u.string()}),Ss=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()}),Ts=u.object({type:u.literal("interactive"),footer:u.string().optional(),data:u.union([vs,bs,Ms,xs,Ss]).array()}),Cs=u.object({type:u.literal("simple"),footer:u.string().optional(),data:u.object({id:u.string(),text:u.string()}).array()}),Wt=u.union([Cs,Ts]);var ie=u.url().or(u.base64()).or(u.instanceof(Buffer)),Dt=u.object({text:u.string()}).passthrough(),As=u.object({image:ie,caption:u.string().optional()}).passthrough(),Is=u.object({audio:ie,caption:u.string().optional(),ptt:u.boolean().optional()}).passthrough(),Rs=u.object({video:ie,caption:u.string().optional(),ptv:u.boolean().optional()}).passthrough(),Ps=u.object({sticker:ie,caption:u.string().optional()}).passthrough(),Es=u.object({document:ie,caption:u.string().optional(),fileName:u.string().optional()}).passthrough(),Ws=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(),Ds=u.object({title:u.string().optional(),contacts:u.object({fullname:u.string(),phoneNumber:u.number(),organization:u.string().optional()}).array()}),Ns=u.object({poll:u.object({name:u.string(),answers:u.string().array(),isMultiple:u.boolean().default(false).optional()})}),Nt=u.object({replied:u.custom().optional(),isForwardedMany:u.boolean().optional(),isViewOnce:u.boolean().optional(),banner:u.custom().optional(),buttons:Wt.optional()});u.enum(["forward","button","edit","delete"]);var Fs=u.union([Dt,As,Is,Rs,Ps,Es,Ws,Ds,Ns]),Ft=u.string().or(u.intersection(Fs,Nt.omit({buttons:true}))),Ot=u.intersection(Dt,Nt.omit({banner:true}));var Me=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=k(e).buttons,s=t?.data||[],n=t?.type=="simple"?this.toNativeSimple(s):this.toNativeInteractive(s);return {body:{text:k(e).text},footer:t.footer?{text:t.footer}:void 0,nativeFlowMessage:{buttons:n}}}async send(e,t,s){let o=r.get("socket"),n=o.authState?.creds?.me?.id||o.user?.id,i=this.build(t),c=generateWAMessageFromContent(e,{interactiveMessage:i},{userJid:n,messageId:generateMessageIDV2(n),...s});return await o.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"}}]}]}]}),o.config?.emitOwnEvents&&!isJidGroup(e)&&process.nextTick(()=>o.upsertMessage?.(c,"append")),c}};var xe=class{constructor(e){this.client=e;}async signal(e,t,s,o){s!="delete"&&(s=="button"?t=oe(Ot,t):t=oe(Ft,t));let n=r.get("socket"),i={},c={},l=x.isString(t),p=this.client.options?.fakeReply?.provider,h=this.client.options?.autoMentions,T=this.client.options?.autoPresence,$=x.has(t,"replied"),De=x.has(t,"banner"),J=x.has(t,"isViewOnce"),Ne=s=="button",L=x.has(t,"image"),B=x.has(t,"video"),G=x.has(t,"audio"),R=x.has(t,"sticker"),C=x.has(t,"document"),_=x.has(t,"location"),K=x.has(t,"contacts"),Fe=x.has(t,"poll"),st=L||B||G||R||C,H=l?t:I([t],["text","caption"]);if(T&&(G?await n.sendPresenceUpdate("recording",e):await n.sendPresenceUpdate("composing",e)),h&&(i={...i,mentions:Be(H),contextInfo:{mentionedJid:Be(H)}}),$&&(c.quoted=k(t).replied,p&&(c.quoted.key.remoteJid=Ze[p],c.quoted.key.participant=Ze[p])),De&&(i={...i,contextInfo:{externalAdReply:k(t).banner}},i.contextInfo.externalAdReply.mediaType=1),J&&(i={...i,viewOnce:k(t)?.isViewOnce}),H&&(i={...i,text:H,caption:H},st&&delete k(i).text),st){let v=I([t],["image","video","audio","sticker","document"]),W=x.isString(v)?{url:v}:v;if(L&&(i={...i,image:W,jpegThumbnail:await Ue(v)}),B){let D=k(t)?.ptv;i={...i,video:W,ptv:D,jpegThumbnail:await Ue(v)};}if(G){let D=k(t)?.ptt;i={...i,audio:await mt(v),ptt:D,mimetype:D?"audio/ogg; codecs=opus":"audio/mpeg"};}if(R&&(i={...i,sticker:await dt(v,this.client.options?.sticker)}),C){let D=await ft(v);i={...i,fileName:k(t).fileName,...D};}}if(_){let v=k(t).location;i={...i,location:{degreesLatitude:v.latitude,degreesLongitude:v.longitude,url:v.url,address:v.footer,name:v.title}};}if(K){let v=k(t)?.contacts,nt=v?.contacts.map(W=>{let D=["BEGIN:VCARD","VERSION:3.0",`FN:${W.fullname}`,`ORG:${W.organization||""}`,`TEL;type=CELL;type=VOICE;waid=${W.phoneNumber}:${W.phoneNumber}`,"END:VCARD"].join(`
|
|
6
|
-
`);return {displayName:W.fullname,vcard:D}});i={...i,contacts:{displayName:v?.title,contacts:nt}};}if(Fe){let v=k(t)?.poll;i={...i,poll:{name:v.name,values:v.answers,selectableCount:v.isMultiple?1:0,toAnnouncementGroup:true}};}return s=="forward"&&(i={...i,contextInfo:{...k(i).contextInfo,isForwarded:true,forwardingScore:k(t).isForwardedMany?9999:1}}),s=="edit"&&(i={...i,edit:o?.key},await n.sendPresenceUpdate("paused",e)),s=="delete"&&(i={...i,delete:o?.key},await n.sendPresenceUpdate("paused",e)),Ne?await new Me().send(e,t,c):await n.sendMessage(e,k(i),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 x.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=r.get("socket"),o={typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"};return await s.sendPresenceUpdate(o[t],e)}async reaction(e,t){return await r.get("socket").sendMessage(e.key.remoteJid,{react:{text:t,key:e?.key}})}async memberLabel(e,t){return await r.get("socket").relayMessage(e,{protocolMessage:{type:30,memberLabel:{label:t,labelTimestamp:Date.now()}}},{})}};var Qe=class{constructor(e){this.client=e;}async create(e,t){return await r.get("socket").communityCreate(e,t)}async createGroup(e,t,s){return await r.get("socket").communityCreateGroup(e,t,s)}async leave(e){return await r.get("socket").communityLeave(e)}async metadata(e){return await r.get("socket").communityMetadata(e)}async update(e,t,s){let o=r.get("socket");switch(t){case "subject":return await o.communityUpdateSubject(e,s);case "description":return await o.communityUpdateDescription(e,s)}}async group(e,t,s){let o=r.get("socket");switch(t){case "link":if(!s)throw "Group JID is required for linking";return await o.communityLinkGroup(e,s);case "unlink":if(!s)throw "Group JID is required for unlinking";return await o.communityUnlinkGroup(e,s);case "linked":return await o.communityFetchLinkedGroups(e)}}async participants(e,t,s,o){let n=r.get("socket");switch(t){case "list":return await n.communityRequestParticipantsList(e);case "request-update":return await n.communityRequestParticipantsUpdate(e,o,k(s));case "update":if(!s||!o)throw "Action and participants are required for update";return await n.communityParticipantsUpdate(e,o,k(s));case "all":return await n.communityFetchAllParticipating()}}async invite(e,t,...s){let o=r.get("socket");switch(t){case "code":return await o.communityInviteCode(e);case "revoke":return await o.communityRevokeInvite(e);case "accept":return await o.communityAcceptInvite(e);case "info":return await o.communityGetInviteInfo(e);case "revokeV4":return await o.communityRevokeInviteV4(e,s[0]);case "acceptV4":return await o.communityAcceptInviteV4(e,s[0])}}async settings(e,t,s){let o=r.get("socket");switch(t){case "ephemeral":return await o.communityToggleEphemeral(e,s);case "update":return await o.communitySettingUpdate(e,s);case "memberAdd":return await o.communityMemberAddMode(e,s);case "approval":return await o.communityJoinApprovalMode(e,s)}}},Se=class{constructor(e){this.mlient=e;this.community=new Qe(e);}community};var Ye=class{constructor(e){this.client=e;}async create(e,t){return await r.get("socket").groupCreate(e,t)}async participant(e,t,s){return await r.get("socket").groupParticipantsUpdate(e,t,s)}async profile(e,t,s){let o=r.get("socket"),n=Buffer.isBuffer(t);switch(s){case "subject":if(!n)return await o.groupUpdateSubject(e,t);case "description":if(!n)return await o.groupUpdateDescription(e,t);case "picture":return await o.updateProfilePicture(e,ue(t))}}async setting(e,t){let s=r.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 r.get("socket").groupLeave(e)}async inviteCode(e,t){let s=r.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 r.get("socket").groupMetadata(e)}async requestJoin(e,t,s){let o=r.get("socket");switch(s){case "approve":return await o.groupRequestParticipantsUpdate(e,t,s);case "reject":return await o.groupRequestParticipantsUpdate(e,t,s)}}async requestJoinList(e){return await r.get("socket").groupRequestParticipantsList(e)}async fetchAllGroups(){return await r.get("socket").groupFetchAllParticipating()}async ephemeral(e,t){let s=r.get("socket"),o={off:0,"24h":86400,"7d":604800,"90d":7776e3};return await s.groupToggleEphemeral(e,o[t])}},Te=class{constructor(e){this.glient=e;this.group=new Ye(e);}group};var Xe=class{constructor(e){this.client=e;}async create(e,t){return await r.get("socket").newsletterCreate(e,t)}async action(e,t){let s=r.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 o=r.get("socket"),n=Buffer.isBuffer(t);switch(s){case "name":if(!n)return await o.newsletterUpdateName(e,t);case "description":if(!n)return await o.newsletterUpdateDescription(e,t);case "picture":return await o.newsletterUpdatePicture(e,ue(t))}}async metadata(e,t){return await r.get("socket").newsletterMetadata(t,e)}async subscribers(e){return await r.get("socket").newsletterSubscribers(e)}async reaction(e,t,s){return await r.get("socket").newsletterReactMessage(e,t,s)}async fetchMessages(e,t,s,o){let n=r.get("socket"),i=s.getTime()/1e3,c=o.getTime()/1e3;return await n.newsletterFetchMessages(e,t,i,c)}async adminCount(e){return await r.get("socket").newsletterAdminCount(e)}async changeOwner(e,t){return await r.get("socket").newsletterChangeOwner(e,t)}async demote(e,t){return await r.get("socket").newsletterDemote(e,t)}async delete(e){return await r.get("socket").newsletterDelete(e)}async removePicture(e){return await r.get("socket").newsletterRemovePicture(e)}},Ce=class{constructor(e){this.nlient=e;this.newsletter=new Xe(e);}newsletter};var et=class{constructor(e){this.client=e;}async block(e){return await r.get("socket").updateBlockStatus(e,"block")}async unblock(e){return await r.get("socket").updateBlockStatus(e,"unblock")}async lastSeen(e){return await r.get("socket").updateLastSeenPrivacy(e)}async online(e){return await r.get("socket").updateOnlinePrivacy(e)}async picture(e){return await r.get("socket").updateProfilePicturePrivacy(e)}async status(e){return await r.get("socket").updateStatusPrivacy(e)}async readReceipt(e){return await r.get("socket").updateReadReceiptsPrivacy(e)}async groupsAdd(e){return await r.get("socket").updateGroupsAddPrivacy(e)}async ephemeral(e){let t=r.get("socket"),s={off:0,"24h":86400,"7d":604800,"90d":7776e3};return await t.updateDefaultDisappearingMode(s[e])}async blocklist(){return await r.get("socket").fetchBlocklist()}async getSettings(){return await r.get("socket").fetchPrivacySettings(true)}},Ae=class{constructor(e){this.plient=e;this.privacy=new et(e);}privacy};var _s=z$1.object({maxMessages:z$1.number().default(20),durationMs:z$1.number().default(1e4)}).optional(),js=z$1.record(z$1.string(),z$1.function({output:z$1.promise(z$1.array(z$1.number()))})).optional(),$s=z$1.object({provider:z$1.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).or(z$1.number())}).optional(),zs=z$1.object({packageName:z$1.string(),authorName:z$1.string(),quality:z$1.number()}).optional(),Lt=z$1.object({session:z$1.string().default("zaileys").optional(),prefix:z$1.string().optional(),ignoreMe:z$1.boolean().default(true).optional(),showLogs:z$1.boolean().default(true).optional(),syncFullHistory:z$1.boolean().default(true).optional(),disableFFmpeg:z$1.boolean().default(false).optional(),autoMarkAI:z$1.boolean().default(true).optional(),autoMentions:z$1.boolean().default(true).optional(),autoOnline:z$1.boolean().default(true).optional(),autoRead:z$1.boolean().default(true).optional(),autoPresence:z$1.boolean().default(true).optional(),autoRejectCall:z$1.boolean().default(true).optional(),limiter:_s,citation:js,fakeReply:$s,sticker:zs}),Us=z$1.object({authType:z$1.literal("pairing"),phoneNumber:z$1.number()}),qs=z$1.object({authType:z$1.literal("qr")}),Bt=z$1.union([Us.extend(Lt.shape),qs.extend(Lt.shape)]),yr=z$1.enum(["connection","messages","calls"]);var vr=u.object({status:u.enum(["connecting","open","close","reload","syncing"]),authType:u.enum(["pairing","qr"]),authTimeout:u.number().optional(),syncProgress:u.number().optional(),syncCompleted:u.boolean().default(false).optional(),qr:u.string().optional(),code:u.string().optional()});var Js=u.enum(["unknown","android","ios","desktop","web"]),Gs=u.enum(["text","image","contact","location","document","audio","video","protocol","contacts","highlyStructured","sendPayment","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","product","deviceSent","lists","viewOnce","order","ephemeral","invoice","buttons","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","placeholder","encEventUpdate"]),_t=u.object({channelId:u.string(),uniqueId:u.string(),chatId:u.string(),chatType:Gs,receiverId:u.string(),receiverName:u.string(),roomId:u.string(),roomName:u.string(),senderLid:u.string(),senderId:u.string(),senderName:u.string(),senderDevice:Js,timestamp:u.number(),text:u.string().nullable(),mentions:u.string().array(),links:u.string().array(),isBot:u.boolean(),isFromMe:u.boolean(),isPrefix:u.boolean(),isSpam:u.boolean(),isTagMe:u.boolean(),isGroup:u.boolean(),isNewsletter:u.boolean(),isQuestion:u.boolean(),isStory:u.boolean(),isViewOnce:u.boolean(),isEdited:u.boolean(),isDeleted:u.boolean(),isPinned:u.boolean(),isUnPinned:u.boolean(),isBroadcast:u.boolean(),isEphemeral:u.boolean(),isForwarded:u.boolean(),citation:u.record(u.string(),u.function({output:u.promise(u.boolean())})).nullable(),media:u.object({buffer:u.function({output:u.promise(u.instanceof(Buffer))}),stream:u.function({output:u.promise(u.instanceof(Vs))})}).loose().nullable(),message:u.function({input:[],output:u.custom()})}),Tr=_t.extend({replied:_t.nullable()});var Rr=u.object({callId:u.string(),callerId:u.string(),callerName:u.string(),roomId:u.string(),roomName:u.string(),date:u.date(),offline:u.boolean(),status:u.enum(["accept","offer","reject","ringing","terminate","timeout"]),isVideo:u.boolean(),isGroup:u.boolean()});var Ie=class{collect(e,t,s){let o=t.max??1/0;if(o<=0){s([]);return}let n=r.collectors.get(e);n&&(clearTimeout(n.timeoutId),n.callback(n.messages),r.collectors.delete(e));let i=setTimeout(()=>{let c=r.collectors.get(e);c&&(c.callback(c.messages),r.collectors.delete(e));},t.timeout);r.collectors.set(e,{messages:[],max:o,filter:t.filter,callback:s,timeoutId:i});}push(e){let t=r.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),r.collectors.delete(e.channelId)),true)}has(e){return r.collectors.has(e)}cancel(e){let t=r.collectors.get(e);return t?(clearTimeout(t.timeoutId),t.callback(t.messages),r.collectors.delete(e),t.messages):[]}};var Re=class{constructor(e){this.client=e;this.initialize();}logsInitialized=false;logsDisplayed=false;isReady=false;getRoomColor(e){return e?.isNewsletter?"blue":e?.isGroup?e?.isGroup?"lime":"dimgray":"orange"}initialize(){if(!this.client.options.showLogs||this.logsInitialized)return;this.logsInitialized=true,r.get("socket").ev.on("connection.update",({connection:t})=>{this.logsDisplayed||t==="open"&&(this.logsDisplayed=true,this.isReady=true,console.log(),r.spinner.info("Logs Indicator:"),console.log(M(" \u2022","orange")+" Private Chat"),console.log(M(" \u2022","lime")+" Group Chat"),console.log(M(" \u2022","blue")+" Newsletter Chat"),console.log());});}message(e){if(!this.isReady)return;let t=k(this.getRoomColor(e)),s=e?.text?.toLowerCase()?.match("zaileys"),o=M(`[${new Date(e?.timestamp).toTimeString().split(" ")[0]}]`,"dimgray"),n=M(`${e?.roomName}`,t),i=e?.text?.slice(0,300)||"",c=i?.length>=300?"...":"",l=`${o} \u2192 ${n}
|
|
7
|
-
`;e?.isNewsletter?l+=`${
|
|
8
|
-
`:l+=`${
|
|
9
|
-
`,l+=`${
|
|
10
|
-
`,l+="\u2014",console.log(l);}call(e){if(!
|
|
11
|
-
`;
|
|
12
|
-
`,
|
|
13
|
-
`,
|
|
1
|
+
import zt,{BufferJSON,initAuthCreds,proto,makeCacheableSignalKeyStore,URL_REGEX,extractMessageContent,getContentType,generateWAMessageFromContent,generateMessageIDV2,isJidGroup,delay,DisconnectReason,jidNormalizedUser,getDevice,downloadMediaMessage}from'baileys';import $e,{stat,mkdir}from'fs/promises';import {createJetDB}from'jetdb';export{JetDB,createJetDB}from'jetdb';import {createSpinner}from'nanospinner';import Fe from'node-cache';import {EventEmitter}from'events';import Bt from'pino';import*as N from'fs';import {promises}from'fs';import ct,{cristal}from'gradient-string';import S from'lodash';import {fileTypeFromBuffer}from'file-type';import H from'fluent-ffmpeg';import Gt from'node-webpmux';import {tmpdir}from'os';import*as je from'path';import je__default from'path';import Le from'sharp';import Zt from'figlet';import Yt from'qrcode-terminal';import {RateLimiterMemory}from'rate-limiter-flexible';import u,{z}from'zod';import Is from'stream';import {pathToFileURL}from'url';var Be=class{data=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 n=this.get(e);this.set(e,t(n));}delete(e){this.data.delete(e);}has(e){return this.data.has(e)}db(e,t){let n=`.session/${e}/store/${t}.json`;return createJetDB(n,{cacheSize:5e3,flushMode:"debounce",debounceMs:300,compression:"deflate",serialization:"json",enableIndexing:true,hotThreshold:5})}spinner=createSpinner("",{color:"green"});logger=Bt({level:"silent",enabled:false});events=new EventEmitter;groupCache=new Fe({stdTTL:300,useClones:false});collectors=new Map},i=new Be;var et=async a=>{i.spinner.start(" Initializing auth state...");let e=await stat(a).catch(()=>{});if(e){if(!e.isDirectory())throw i.spinner.error(` Failed to open credentials
|
|
2
|
+
`),`found something that is not a directory at ${a}, either delete it or specify a different location`}else await mkdir(a,{recursive:true});let t=createJetDB(`${a}/auth/creds.json`,{BufferJSON:BufferJSON,cacheSize:100,flushMode:"sync",compression:"none",enableIndexing:false}),n=createJetDB(`${a}/auth/keys.json`,{BufferJSON:BufferJSON,size:512*1024,cacheSize:1e3,flushMode:"debounce",debounceMs:500,compression:"deflate",enableIndexing:false,hotThreshold:3});await Promise.all([t.read(),n.read()]);let o=await t.get("creds")||initAuthCreds();return i.spinner.success(" Generate auth successfully"),{state:{creds:o,keys:{get:async(s,r)=>{let c={};return await Promise.all(r.map(async l=>{let p=`${s}:${l}`,w=await n.get(p);s==="app-state-sync-key"&&w&&(w=proto.Message.AppStateSyncKeyData.fromObject(w)),c[l]=w;})),c},set:async s=>{let r=[],c=[];for(let l in s)for(let p in s[l]){let w=s[l][p],x=`${l}:${p}`;w?r.push({key:x,value:w}):c.push(x);}r.length&&await n.batchSet(r),c.length&&await n.batchDelete(c),await n.flush();}}},saveCreds:async()=>{await t.set("creds",o),await t.write();}}};var jt=new Fe,tt=(a,e)=>({logger:i.logger,printQRInTerminal:false,markOnlineOnConnect:a.options.autoOnline,syncFullHistory:a.options.syncFullHistory,msgRetryCounterCache:new Fe,mediaCache:new Fe({stdTTL:60}),cachedGroupMetadata:async t=>jt.get(t),auth:{creds:e.creds,keys:makeCacheableSignalKeyStore(e.keys,i.logger)},shouldIgnoreJid:()=>false,patchMessageBeforeSending:t=>t,getMessage:async t=>t?.remoteJid?await a.db("messages").query(t.remoteJid).where("key.id","=",t.id).first():void 0});var nt=a=>{if(a)try{a.ev?.removeAllListeners(),a.end?.(new Error("Cleanup"));}catch{}},te=async a=>{let e=`.session/${a}/auth/keys.json`;try{let t=await promises.readFile(e,"utf-8"),n=JSON.parse(t),o=["sender-key:","session:"],s={},r=!1;for(let[c,l]of Object.entries(n))o.some(w=>c.startsWith(w))?r=!0:s[c]=l;r&&(await promises.writeFile(e,JSON.stringify(s,null,2)),i.spinner.success(" Session keys repaired successfully"));}catch{i.spinner.warn(" Could not repair session keys, will re-negotiate");}},ot=()=>{let a=i.get("socket");return a?.end?a:null};var rt=async a=>{let e=ot();e&&nt(e);let t=`.session/${a.options.session}`;console.info=()=>{};let{state:n,saveCreds:o}=await et(t),s=tt(a,n),r=zt(s);r.ev.on("creds.update",o),i.set("socket",r);};var h=a=>a,it=async()=>{try{return (await(await fetch("https://registry.npmjs.org/zaileys")).json())["dist-tags"].latest}catch(a){throw a}},at=async a=>{try{let e=`.session/${a}/auth/creds.json`;await $e.unlink(e);}catch(e){throw i.spinner.error(`Failed to remove auth creds for session "${a}"!`),e}},R=(a="")=>{if(!a?.length)return null;let e=a.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,n)=>[...n].reverse().join("")).replace(/[\uFE00-\uFE0F]/gu,"").replace(/[\u200C\u200D]/gu,"").replace(/[\u2800\u180E]/gu,"").replace(/[\s\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/gu," ").replace(/[\p{Cc}\p{Cf}\p{Co}\p{Cn}]/gu,"").trim().replace(/\s+/g," ");return e.length?e:null};var v=(a,e="lime")=>Array.isArray(e)?ct(e)(a):ct([e,e])(a),Ne=a=>{try{return JSON.parse(a)}catch{return S.attempt(()=>JSON.parse(JSON.stringify(a)||"{}"))}},J=a=>{try{return JSON.stringify(a)}catch{let e=S.attempt(()=>JSON.stringify(Ne(a)||"{}"));return S.isError(e)?"{}":e}},Cn=(a="")=>S.shuffle(a).join(""),G=(a="",e="")=>a?S.includes(a.toLowerCase(),e.toLowerCase()):null,lt=(a="")=>a?S.castArray(a.match(URL_REGEX)||[]):[],An=a=>a[Math.floor(Math.random()*a.length)],F=(a,e)=>{let t=o=>!!(o==null||typeof o=="string"&&o.trim()===""||Array.isArray(o)&&o.length===0||typeof o=="object"&&Object.keys(o).length===0),n=(o,s)=>{if(!o||typeof o!="object")return;let r=o,c=s.split(".");for(let l of c){let p=l.match(/^(.+?)\[(\d+)\]$/);if(p){let[,w,x]=p;r=r?.[w]?.[parseInt(x,10)];}else r=r?.[l];if(t(r))return}return r};if(!(!Array.isArray(a)||a.length===0)&&!(!Array.isArray(e)||e.length===0)){for(let o of a)if(!(!o||typeof o!="object"))for(let s of e){let r=n(o,s);if(!t(r))return r}}},In=(a,e)=>{let t=S.castArray(e),n=(r,c)=>S.every(c,(l,p)=>r?.[p]===l),o=(r,c)=>S.some(c,(l,p)=>r?.[p]===l),s=r=>S.isArray(r)?S.find(r,s)??r:S.isObject(r)?S.find(t,p=>n(r,p))||S.find(t,p=>o(r,p))?r:S.find(S.values(r),s)??r:null;return s(a)},Rn=(a,e,t)=>new Proxy(a,{apply(n,o,s){e?.(s);let r=Reflect.apply(n,o,s);return t?t(r,s):r}});var _=a=>{let e;Array.isArray(a)?e=a.join("|"):typeof a=="string"?e=a:e=String(a);let t=2166136261,n=e.length;for(let o=0;o<n;o++)t^=e.charCodeAt(o),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return "Z4D3FC"+(t>>>0).toString(16).padStart(8,"0").toUpperCase()},pt=(a="")=>{if(!a)return [];let e=new Set;for(let t of a.matchAll(/@(\d+)/g))e.add(t[1]);return S.toArray(e)},Oe=(a="")=>{if(!a)return [];let e=new Set;for(let t of a.matchAll(/@(\d+)/g))t[1].length<=15&&e.add(t[1]);return S.flatMap([...e],t=>[`${t}@s.whatsapp.net`,`${t}@g.us`,`${t}@lid`])},Fn=a=>S.isEmpty(a)?[]:S.map([...a],e=>`${e}@s.whatsapp.net`),ut=a=>S.omit(a,["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"]),se=a=>{if(!a)return {leaf:void 0,chain:[]};let e=extractMessageContent(a)||a,t=[];for(;e&&typeof e=="object";){let n=getContentType(e);if(!n)break;t.push(n);let o=e[n];if(!o||typeof o!="object"){e=o;break}e=o;}return {leaf:e,chain:t}},W=a=>Number(a?.split("@")[0]);var mt=async(a=false)=>{if(!a)try{let e=(await import('@ffmpeg-installer/ffmpeg')).default,t=(await import('@ffprobe-installer/ffprobe')).default;H.setFfmpegPath(e.path),H.setFfprobePath(t.path);}catch{}},k={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 je__default.join(tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>$e.unlink(t)));}static async safeReadFile(e){try{return await $e.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await $e.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},E=class{static async toBuffer(e){if(S.isBuffer(e))return e;if(S.isArrayBuffer(e))return Buffer.from(e);if(S.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 n=await t.arrayBuffer();return Buffer.from(n)}catch(t){throw new Error(`Failed to fetch URL: ${t.message}`)}}},L=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(k.MIME.IMAGE)||e.startsWith(k.MIME.VIDEO)}static isAnimated(e){return e===k.MIME.GIF||e.startsWith(k.MIME.VIDEO)}},Z=class{static async process(e){return new Promise((t,n)=>{let o=H(e.input).output(e.output);for(let s=0;s<e.options.length;s++){let r=e.options[s];r.startsWith("-")&&s+1<e.options.length&&!e.options[s+1].startsWith("-")?(o.outputOptions(r,e.options[s+1]),s++):o.outputOptions(r);}o.on("end",async()=>{try{await e.onEnd(),t();}catch(s){n(s);}}).on("error",async s=>{try{await e.onError(s);}finally{n(s);}}).run();})}static async getDuration(e){return new Promise((t,n)=>{H.ffprobe(e,(o,s)=>{if(o)return n(o);t(s.format.duration||0);});})}},ne=class{static async getWaAudio(e,t="opus"){let n=await E.toBuffer(e),o=await fileTypeFromBuffer(n);L.validate(o,k.MIME.AUDIO);let s=M.createTempPath("audio_in","wav"),r=t==="opus"?"ogg":"mp3",c=M.createTempPath("audio_out",r);await M.safeWriteFile(s,n);let l;try{let p=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 Z.process({input:s,output:c,options:p,onEnd:async()=>{l=await M.safeReadFile(c);},onError:async()=>{await M.cleanup([s,c]);}}),await M.cleanup([s,c]),l}catch(p){throw await M.cleanup([s,c]),new Error(`${t.toUpperCase()} conversion failed: ${p.message}`)}}},D=class{static async getThumbnail(e){let t=await E.toBuffer(e),n=await fileTypeFromBuffer(t);L.validate(n,k.MIME.VIDEO);let o=M.createTempPath("video","mp4"),s=M.createTempPath("thumb","jpg");await M.safeWriteFile(o,t);let r;try{return await new Promise((c,l)=>{H(o).screenshots({timestamps:[k.THUMBNAIL.TIMESTAMP],filename:je__default.basename(s),folder:je__default.dirname(s),size:`${k.THUMBNAIL.SIZE}x${k.THUMBNAIL.SIZE}`,quality:k.THUMBNAIL.QUALITY}).on("end",async()=>{try{r=(await M.safeReadFile(s)).toString("base64"),c();}catch(p){l(p);}}).on("error",l);}),await M.cleanup([o,s]),r}catch(c){throw await M.cleanup([o,s]),new Error(`Thumbnail generation failed: ${c.message}`)}}static async getDuration(e){return Z.getDuration(e)}},oe=class{static async getThumbnail(e){return (await((await fileTypeFromBuffer(e)).mime===k.MIME.GIF?Le(e,{animated:false}):Le(e)).resize(k.THUMBNAIL.SIZE,k.THUMBNAIL.SIZE,{fit:"cover"}).jpeg({quality:k.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}static async resizeForSticker(e,t,n="default"){let o=Le(e).resize(k.STICKER.SIZE,k.STICKER.SIZE,{fit:"cover",background:{r:0,g:0,b:0,alpha:0}});if(n!=="default"){let s=k.STICKER.SIZE,r;switch(n){case "rounded":r=`<svg width="${s}" height="${s}"><rect x="0" y="0" width="${s}" height="${s}" rx="${s/10}" ry="${s/10}" fill="white"/></svg>`;break;case "circle":r=`<svg width="${s}" height="${s}"><circle cx="${s/2}" cy="${s/2}" r="${s/2}" fill="white"/></svg>`;break;case "oval":r=`<svg width="${s}" height="${s}"><ellipse cx="${s/2}" cy="${s/2}" rx="${s/2}" ry="${s/3}" fill="white"/></svg>`;break;default:r="";}r&&(o=o.composite([{input:Buffer.from(r),blend:"dest-in"}]));}return o.webp({quality:t}).toBuffer()}},Q=class{static async getThumbnail(e){let t=await E.toBuffer(e),n=await fileTypeFromBuffer(t);if(!n||!L.isMedia(n.mime))throw new Error("Invalid media type: expected image or video");return n.mime.startsWith(k.MIME.VIDEO)?D.getThumbnail(e):oe.getThumbnail(t)}},re=class{static createExifMetadata(e){let t={"sticker-pack-id":_(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"},n=Buffer.from([73,73,42,0,8,0,0,0,1,0,65,87,7,0,0,0,0,0,22,0,0,0]),o=Buffer.from(JSON.stringify(t),"utf8"),s=Buffer.concat([n,o]);return s.writeUIntLE(o.length,14,4),s}static async processAnimated(e,t,n){let o=this.getExtension(t),s=M.createTempPath("sticker_in",o),r=M.createTempPath("sticker_out","webp");await M.safeWriteFile(s,e);let c=k.STICKER.MAX_DURATION;try{let x=await D.getDuration(s);c=h(Math.min(x,k.STICKER.MAX_DURATION));}catch{console.warn("Using default duration:",k.STICKER.MAX_DURATION);}let l=`scale=${k.STICKER.SIZE}:${k.STICKER.SIZE}:force_original_aspect_ratio=increase,crop=${k.STICKER.SIZE}:${k.STICKER.SIZE},fps=${k.STICKER.FPS},format=rgba`,p=Math.max(1,Math.min(100,100-n)),w;try{return await Z.process({input:s,output:r,options:["-vcodec libwebp",`-vf ${l}`,`-q:v ${p}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${c}`,`-compression_level ${k.STICKER.COMPRESSION_LEVEL}`],onEnd:async()=>{w=await M.safeReadFile(r);},onError:async()=>{await M.cleanup([s,r]);}}),await M.cleanup([s,r]),w}catch(x){throw await M.cleanup([s,r]),new Error(`Animated sticker processing failed: ${x.message}`)}}static getExtension(e){return e===k.MIME.GIF?"gif":e.startsWith(k.MIME.VIDEO)?"mp4":"tmp"}static async create(e,t){try{let n=await E.toBuffer(e),o=await fileTypeFromBuffer(n);if(!o)throw new Error("Unable to detect file type");let s=t?.quality||k.STICKER.DEFAULT_QUALITY,r=L.isAnimated(o.mime),c=t?.shape||"default",l=r?await this.processAnimated(n,o.mime,s):await oe.resizeForSticker(n,s,c),p=this.createExifMetadata(t),w=new Gt.Image;await w.load(l),w.exif=p;let x=await w.save(null);return Buffer.isBuffer(x)?x:Buffer.from(x)}catch(n){throw new Error(`Sticker creation failed: ${n.message||n}`)}}},ie=class{static async create(e){try{let t=await E.toBuffer(e),n=await fileTypeFromBuffer(t);if(!n)throw new Error("Unable to detect file type");return {document:t,mimetype:n.mime,fileName:_(Date.now().toString()),jpegThumbnail:await Q.getThumbnail(t)}}catch(t){throw new Error(`Document creation failed: ${t.message||t}`)}}},ae=E.toBuffer.bind(E),dt=ne.getWaAudio.bind(ne),Kn=D.getThumbnail.bind(D),Hn=D.getDuration.bind(D),ze=Q.getThumbnail.bind(Q),ft=re.create.bind(re),gt=ie.create.bind(ie);var ce=class{constructor(e){this.client=e;this.initialize();}async initialize(){let e=i.get("socket");e.ev.on("call",async t=>{for(let n of t){let o=await this.parse(n);o&&(await this.client.middleware.run({calls:o}),await this.client.plugins.execute(this.client,{messages:o}),i.events.emit("calls",o),this.client.options?.autoRejectCall&&await e.rejectCall(o.callId,o.callerId));}});}async parse(e){let t=i.get("socket"),n={};return n.callId=e.id,n.callerId=jidNormalizedUser(e.from),n.callerName=await this.client.getRoomName(n.callerId),n.roomId=jidNormalizedUser(e.chatId),n.roomName=R(t?.user?.name||t?.user?.verifiedName),n.date=e.date,n.offline=e.offline,n.status=e.status,n.isVideo=!!e.isVideo,n.isGroup=!!e.isGroup,this.client.logs.call(n),n}};var le={version:"2.1.0",author:"zaadevofc"};var ht=a=>{Yt.generate(a,{small:true},e=>{console.log(e);});},kt=async()=>{console.clear(),i.spinner.start(" Checking for updates...");let a=await it(),e=le.version===a;i.spinner.stop();let t="Zaileys",n=`
|
|
3
|
+
by ${le.author} \xB7 v${le.version}`,o=`${e?"Already using latest version!":`Update available! (v${a})`}
|
|
4
|
+
`,s=e?"lime":"orange",r=await Zt.text(t),c=cristal(r);console.log(c),console.log(v(n,"dimgray")),console.log(v(o,s));};var me=class{constructor(e){this.client=e;this.initialize();}async initialize(){i.spinner.start(" Initializing connection...");let e=i.get("socket"),t={},n=async()=>{t.status="reload",i.spinner.warn(" Connection lost. Attempting auto-reload..."),await this.client.initialize();},o=async()=>{await delay(3e3),i.spinner.warn(" Invalid session. Attempting auto cleaning creds..."),await delay(3e3),await at(this.client.options.session),await n();};if(this.client.options.authType==="pairing"&&this.client.options.phoneNumber&&!e.authState.creds.registered){i.spinner.update(" Generating pairing code..."),await delay(3500);try{t.authTimeout=Date.now()+6e4;let s=new Date(t.authTimeout).toLocaleTimeString(),r=await e.requestPairingCode(this.client.options.phoneNumber.toString());i.spinner.warn(` Pairing expired at ${cristal(s)}`),i.spinner.warn(` Pairing code: ${r}`),t.code=r;}catch{await o();}}e.ev.on("connection.update",async s=>{let{connection:r,lastDisconnect:c,qr:l}=s;if(t.status=r||"connecting",t.authType=this.client.options.authType,i.spinner.update(" Connection status: "+cristal(t.status)),this.client.options.authType==="qr"&&l){t.authTimeout=Date.now()+6e4;let p=new Date(t.authTimeout).toLocaleTimeString();i.spinner.warn(" Please scan the QR code..."),i.spinner.warn(` Qr code expired at ${cristal(p)}`),ht(l),t.qr=l;return}if(r==="close"){let p=h(c?.error)?.output?.statusCode,w=c?.error?.message||"",x=typeof p=="number"&&p!==DisconnectReason.loggedOut,O=p===515||w.toLowerCase().includes("prekey");if(i.spinner.error(` [${p} - Closed] ${w}`),O){i.spinner.warn(" Session key mismatch detected, attempting repair..."),await te(this.client.options.session),await delay(1e3),await n();return}if(p===401||p===405){i.spinner.warn(" Session may be used by another device/instance."),i.spinner.warn(" If you want to connect here, close the other connection first."),i.spinner.warn(` Or use a different session name in your Client options.
|
|
5
|
+
`);return}if(p===500){i.spinner.error(" Server error occurred, attempting reconnect..."),await n();return}x&&await n();}if(r==="open")if(e.user?.id){let p=jidNormalizedUser(e.user.id).split("@")[0],w=e.user.name||e.user.verifiedName;i.spinner.success(` Connected as ${cristal(w||p)}`);}else i.spinner.success(" Connected!");i.events.emit("connection",t);}),e.ev.on("messaging-history.set",({progress:s})=>{t.status="syncing",t.syncProgress=s,i.spinner.start(" Syncing messages history..."),s&&i.spinner.update(` Syncing messages history ${s+"%"}`),s==100&&(i.spinner.success(" Syncing messages history completed!"),t.syncCompleted=true),i.events.emit("connection",t);});}};var wt={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",groupStatusMentionMessage:"groupStatusMention",statusMentionMessage:"statusMention",albumMessage:"album",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 de=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 ge=class{constructor(e){this.client=e;this.limiter=new de(e),this.initialize();}limiter;maxReplies=3;async initialize(){let e=i.get("socket");e.ev.on("messages.upsert",async({messages:t,type:n})=>{if(n==="notify")for(let o of t){let s=await this.parse(o);s&&(this.client.collector.push(s)||(await this.client.middleware.run({messages:s}),await this.client.plugins.execute(this.client,{messages:s}),i.set("message",s),i.events.emit("messages",s)),this.client.options.autoRead&&await e.readMessages([s.message().key]));}});}async parse(e,t){if(e?.category==="peer"||!e?.message||!e?.key?.id||e?.messageStubType||e?.messageStubParameters?.length||e.message?.protocolMessage?.peerDataOperationRequestResponseMessage)return;let n=e,o=i.get("socket"),s={},r=se(e.message),c=r.chain.at(-1),l=r.leaf;if(l?.message&&(r=se(l.message),c=r.chain.at(-1),l=r.leaf),s.uniqueId=null,s.channelId=null,s.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id||null,s.chatType=wt[c],!s.chatType)return;s.receiverId=jidNormalizedUser(o?.user?.id||""),s.receiverName=R(o?.user?.name||o?.user?.verifiedName),s.roomId=jidNormalizedUser(e?.key?.remoteJid);let p=l?.type===0,w=l?.type===1,x=l?.type===2,O=s.roomId?.includes("@newsletter"),Re=!!e?.message?.questionMessage,z=e?.key?.fromMe||false;if(z&&this.client.options.ignoreMe&&t!=="replied")return;let Ee=l?.key?.id;if(p||w||x){let C=await this.client.db("messages").query(s.roomId).where("key.id","=",Ee).first();if(!C)return;e=C,r=se(e.message),c=r.chain.at(-1),l=r.leaf;}if(s.roomName=await this.client.getRoomName(s.roomId),s.senderLid=F([e?.key],["participant","remoteJid","remoteJidAlt"])||null,s.senderId=jidNormalizedUser(e?.key?.participantAlt||e?.key?.remoteJidAlt),s.senderName=R(e?.pushName||e?.verifiedBizName),s.senderDevice=getDevice(s.chatId),s.channelId=_([s.roomId,s.senderId]),s.uniqueId=_([s.channelId,s.chatId]),s.timestamp=Number(e?.messageTimestamp)*1e3,O){let C=await o.newsletterMetadata("jid",s.roomId);s.roomName=h(C.thread_metadata.name)?.text,s.senderId=null,s.senderLid=null;}if(z&&(s.senderLid=jidNormalizedUser(o.user.lid),s.senderId=s.receiverId,s.senderName=s.receiverName),s.text=l?.text||l?.caption||l?.name||l?.displayName||l?.conversation||l?.contentText||l?.selectedDisplayText||l||null,l?.name=="menu_options"&&(s.text=Ne(l?.paramsJson)?.id),s.text=R(s.text),s.mentions=pt(s.text),s.links=lt(s.text||""),s.isBot=s.chatId.startsWith("BAE5")||s.chatId.startsWith("3EB0")||s.chatId.startsWith("Z4D3FC"),s.isFromMe=z,s.isPrefix=s.text?.startsWith(this.client.options?.prefix)||false,s.isTagMe=s.mentions?.includes(s.receiverId.split("@")[0]),s.isStatusMention=!!e?.message?.statusMentionMessage,s.isGroupStatusMention=!!e?.message?.groupStatusMentionMessage,s.isHideTags=false,S.isEmpty(s.text)&&l?.contextInfo?.mentionedJid?.length&&(s.isHideTags=true),s.isSpam=await this.limiter.isSpam(s.channelId),s.isPrefix&&(s.text=s.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),s.isGroup=s.roomId?.includes("@g.us"),s.isNewsletter=O,s.isQuestion=Re,s.isStory=s.roomId?.includes("@broadcast"),!s.isGroup&&!s.roomName&&(s.roomName=s.senderName),s.isViewOnce=false,s.isEdited=!!G(J(r),"editedMessage"),s.isDeleted=p,s.isPinned=w,s.isUnPinned=x,s.isBroadcast=!!e?.broadcast,s.isEphemeral=!!G(J(l?.contextInfo),"ephemeralSettingTimestamp"),s.isForwarded=!!G(J(l?.contextInfo),"forwardingScore"),s.citation=null,this.client.options.citation){s.citation=s.citation||{};let C=this.client.options.citation;for(let q of Object.keys(C)){let Pe=C[q];s.citation[q]=async()=>{let We=await Pe(),De=[W(s.roomId),W(s.senderLid),W(s.senderId)];return !!S.intersection(De,We).length};}}s.chatType!=="text"&&(s.media={...ut(l),buffer:()=>downloadMediaMessage(e,"buffer",{}),stream:()=>downloadMediaMessage(e,"stream",{})}),s.isStatusMention&&(s.chatType="statusMention"),s.isGroupStatusMention&&(s.chatType="groupStatusMention"),s.message=()=>n,s.replied=null;let $=l?.contextInfo?.quotedMessage,ee=G(J($),"viewOnce"),U=l?.contextInfo?.stanzaId;if($&&this.maxReplies){this.maxReplies--;let C=await this.client.getMessageByChatId(U,$);C&&(s.replied=C,ee&&(s.replied.isViewOnce=true)),this.maxReplies=3;}return t!="replied"&&this.client.logs.message(s),s}};var ye=class{constructor(e){this.client=e;this.connection=new me(e),this.messages=new ge(e),this.calls=new ce(e),this.initialize();}connection;messages;calls;async initialize(){let e=i.get("socket");e.ev.on("groups.update",async([t])=>{let n=await e.groupMetadata(t.id);i.groupCache.set(t.id,n);}),e.ev.on("group-participants.update",async t=>{let n=await e.groupMetadata(t.id);i.groupCache.set(t.id,n);}),e?.ev.on("messaging-history.set",async t=>{let{chats:n,contacts:o,messages:s}=t;for(let r of n)await this.client.db("chats").set(r.id,r);for(let r of o)await this.client.db("contacts").set(r.id,r);for(let r of s){if(r?.category==="peer"||!r.message&&!r.key.isViewOnce&&(!r.message?.groupStatusMentionMessage||!r.message?.statusMentionMessage)||r.message?.protocolMessage&&!r.message?.protocolMessage?.memberLabel)return;await this.client.db("messages").upsert(r.key.remoteJid,r,"key.id");}}),e?.ev.on("messages.upsert",async({messages:t})=>{for(let n of t){if(n?.category==="peer"||!n.message&&!n.key.isViewOnce||n.message?.protocolMessage&&!n.message?.protocolMessage?.memberLabel)return;await this.client.db("messages").upsert(n.key.remoteJid,n,"key.id");}}),e?.ev.on("chats.upsert",async t=>{for(let n of t)await this.client.db("chats").upsert(n.id,n,"id");}),e?.ev.on("contacts.upsert",async t=>{for(let n of t)await this.client.db("contacts").upsert(n.id,n,"id");});}};var Y=(a,e)=>{let t=a.safeParse(e);if(t.success)return t.data;throw console.error(t.error),"Invalid data"};var ns=u.object({type:u.literal("quick_reply"),text:u.string()}),os=u.object({type:u.literal("cta_url"),url:u.url(),text:u.string()}),rs=u.object({type:u.literal("cta_copy"),copy:u.string(),text:u.string()}),is=u.object({type:u.literal("cta_call"),text:u.string(),phoneNumber:u.string()}),as=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()}),cs=u.object({type:u.literal("interactive"),footer:u.string().optional(),data:u.union([ns,os,rs,is,as]).array()}),ls=u.object({type:u.literal("simple"),footer:u.string().optional(),data:u.object({id:u.string(),text:u.string()}).array()}),vt=u.union([ls,cs]);var ps=z.object({maxMessages:z.number().default(20),durationMs:z.number().default(1e4)}).optional(),us=z.record(z.string(),z.function({output:z.promise(z.array(z.number()))})).optional(),ms=z.object({provider:z.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).or(z.number())}).optional(),qe=z.enum(["default","rounded","circle","oval"]).default("default"),ds=z.object({packageName:z.string(),authorName:z.string(),quality:z.number(),shape:qe.optional()}).optional(),xt=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(),disableFFmpeg:z.boolean().default(false).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:ps,citation:us,fakeReply:ms,sticker:ds}),fs=z.object({authType:z.literal("pairing"),phoneNumber:z.number()}),gs=z.object({authType:z.literal("qr")}),St=z.union([fs.extend(xt.shape),gs.extend(xt.shape)]),rr=z.enum(["connection","messages","calls"]);var X=u.url().or(u.base64()).or(u.instanceof(Buffer)),Tt=u.object({text:u.string()}).passthrough(),ys=u.object({image:X,caption:u.string().optional()}).passthrough(),hs=u.object({audio:X,caption:u.string().optional(),ptt:u.boolean().optional()}).passthrough(),ks=u.object({video:X,caption:u.string().optional(),ptv:u.boolean().optional()}).passthrough(),ws=u.object({sticker:X,shape:qe.optional(),caption:u.string().optional()}).passthrough(),bs=u.object({document:X,caption:u.string().optional(),fileName:u.string().optional()}).passthrough(),Ms=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(),vs=u.object({title:u.string().optional(),contacts:u.object({fullname:u.string(),phoneNumber:u.number(),organization:u.string().optional()}).array()}),xs=u.object({poll:u.object({name:u.string(),answers:u.string().array(),isMultiple:u.boolean().default(false).optional()})}),Ct=u.object({replied:u.custom().optional(),isForwardedMany:u.boolean().optional(),isViewOnce:u.boolean().optional(),banner:u.custom().optional(),buttons:vt.optional()});u.enum(["forward","button","edit","delete"]);var Ss=u.union([Tt,ys,hs,ks,ws,bs,Ms,vs,xs]),At=u.string().or(u.intersection(Ss,Ct.omit({buttons:true}))),It=u.intersection(Tt,Ct.omit({banner:true}));var he=class{toNativeSimple(e){return e.map(({id:t,text:n})=>({name:"quick_reply",buttonParamsJson:JSON.stringify({display_text:n,id:t})}))}toNativeInteractive(e){let t={quick_reply:n=>({display_text:n.text,id:n.id}),cta_url:n=>({display_text:n.text,url:n.url,merchant_url:n.url}),cta_copy:n=>({display_text:n.text,id:n.id,copy_code:n.copy}),cta_call:n=>({display_text:n.text,phone_number:n.phoneNumber}),single_select:n=>({title:n.text,sections:n.section})};return e.map(n=>({name:n.type,buttonParamsJson:JSON.stringify(t[n.type](n))}))}build(e){let t=h(e).buttons,n=t?.data||[],s=t?.type=="simple"?this.toNativeSimple(n):this.toNativeInteractive(n);return {body:{text:h(e).text},footer:t.footer?{text:t.footer}:void 0,nativeFlowMessage:{buttons:s}}}async send(e,t,n){let o=i.get("socket"),s=o.authState?.creds?.me?.id||o.user?.id,r=this.build(t),c=generateWAMessageFromContent(e,{interactiveMessage:r},{userJid:s,messageId:generateMessageIDV2(s),...n});return await o.relayMessage(e,c.message,{messageId:c.key.id,...n,additionalNodes:[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}]}),o.config?.emitOwnEvents&&!isJidGroup(e)&&process.nextTick(()=>o.upsertMessage?.(c,"append")),c}};var ke=class{constructor(e){this.client=e;}async signal(e,t,n,o){n!="delete"&&(n=="button"?t=Y(It,t):t=Y(At,t));let s=i.get("socket"),r={},c={},l=S.isString(t),p=this.client.options?.fakeReply?.provider,w=this.client.options?.autoMentions,x=this.client.options?.autoPresence,O=S.has(t,"replied"),Re=S.has(t,"banner"),z=S.has(t,"isViewOnce"),Ee=n=="button",$=S.has(t,"image"),ee=S.has(t,"video"),U=S.has(t,"audio"),C=S.has(t,"sticker"),q=S.has(t,"document"),Pe=S.has(t,"location"),We=S.has(t,"contacts"),De=S.has(t,"poll"),Ze=$||ee||U||C||q,V=l?t:F([t],["text","caption"]);if(x&&(U?await s.sendPresenceUpdate("recording",e):await s.sendPresenceUpdate("composing",e)),w&&(r={...r,mentions:Oe(V),contextInfo:{mentionedJid:Oe(V)}}),O&&(c.quoted=h(t).replied,p&&(c.quoted.key.remoteJid=Ue[p],c.quoted.key.participant=Ue[p])),Re&&(r={...r,contextInfo:{externalAdReply:h(t).banner}},r.contextInfo.externalAdReply.mediaType=1),z&&(r={...r,viewOnce:h(t)?.isViewOnce}),V&&(r={...r,text:V,caption:V},Ze&&delete h(r).text),Ze){let b=F([t],["image","video","audio","sticker","document"]),P=S.isString(b)?{url:b}:b;if($&&(r={...r,image:P,jpegThumbnail:await ze(b)}),ee){let I=h(t)?.ptv;r={...r,video:P,ptv:I,jpegThumbnail:await ze(b)};}if(U){let I=h(t)?.ptt;r={...r,audio:await dt(b),ptt:I,mimetype:I?"audio/ogg; codecs=opus":"audio/mpeg"};}if(C){let I=h(t)?.shape;r={...r,sticker:await ft(b,{...this.client.options?.sticker,shape:I})};}if(q){let I=await gt(b);r={...r,fileName:h(t).fileName,...I};}}if(Pe){let b=h(t).location;r={...r,location:{degreesLatitude:b.latitude,degreesLongitude:b.longitude,url:b.url,address:b.footer,name:b.title}};}if(We){let b=h(t)?.contacts,Qe=b?.contacts.map(P=>{let I=["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:I}});r={...r,contacts:{displayName:b?.title,contacts:Qe}};}if(De){let b=h(t)?.poll;r={...r,poll:{name:b.name,values:b.answers,selectableCount:b.isMultiple?1:0,toAnnouncementGroup:true}};}return n=="forward"&&(r={...r,contextInfo:{...h(r).contextInfo,isForwarded:true,forwardingScore:h(t).isForwardedMany?9999:1}}),n=="edit"&&(r={...r,edit:o?.key},await s.sendPresenceUpdate("paused",e)),n=="delete"&&(r={...r,delete:o?.key},await s.sendPresenceUpdate("paused",e)),Ee?await new he().send(e,t,c):await s.sendMessage(e,h(r),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 S.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 n=i.get("socket"),o={typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"};return await n.sendPresenceUpdate(o[t],e)}async reaction(e,t){return await i.get("socket").sendMessage(e.key.remoteJid,{react:{text:t,key:e?.key}})}async memberLabel(e,t){return await i.get("socket").relayMessage(e,{protocolMessage:{type:30,memberLabel:{label:t,labelTimestamp:Date.now()}}},{})}};var Ve=class{constructor(e){this.client=e;}async create(e,t){return await i.get("socket").communityCreate(e,t)}async createGroup(e,t,n){return await i.get("socket").communityCreateGroup(e,t,n)}async leave(e){return await i.get("socket").communityLeave(e)}async metadata(e){return await i.get("socket").communityMetadata(e)}async update(e,t,n){let o=i.get("socket");switch(t){case "subject":return await o.communityUpdateSubject(e,n);case "description":return await o.communityUpdateDescription(e,n)}}async group(e,t,n){let o=i.get("socket");switch(t){case "link":if(!n)throw "Group JID is required for linking";return await o.communityLinkGroup(e,n);case "unlink":if(!n)throw "Group JID is required for unlinking";return await o.communityUnlinkGroup(e,n);case "linked":return await o.communityFetchLinkedGroups(e)}}async participants(e,t,n,o){let s=i.get("socket");switch(t){case "list":return await s.communityRequestParticipantsList(e);case "request-update":return await s.communityRequestParticipantsUpdate(e,o,h(n));case "update":if(!n||!o)throw "Action and participants are required for update";return await s.communityParticipantsUpdate(e,o,h(n));case "all":return await s.communityFetchAllParticipating()}}async invite(e,t,...n){let o=i.get("socket");switch(t){case "code":return await o.communityInviteCode(e);case "revoke":return await o.communityRevokeInvite(e);case "accept":return await o.communityAcceptInvite(e);case "info":return await o.communityGetInviteInfo(e);case "revokeV4":return await o.communityRevokeInviteV4(e,n[0]);case "acceptV4":return await o.communityAcceptInviteV4(e,n[0])}}async settings(e,t,n){let o=i.get("socket");switch(t){case "ephemeral":return await o.communityToggleEphemeral(e,n);case "update":return await o.communitySettingUpdate(e,n);case "memberAdd":return await o.communityMemberAddMode(e,n);case "approval":return await o.communityJoinApprovalMode(e,n)}}},we=class{constructor(e){this.mlient=e;this.community=new Ve(e);}community};var Je=class{constructor(e){this.client=e;}async create(e,t){return await i.get("socket").groupCreate(e,t)}async participant(e,t,n){return await i.get("socket").groupParticipantsUpdate(e,t,n)}async profile(e,t,n){let o=i.get("socket"),s=Buffer.isBuffer(t);switch(n){case "subject":if(!s)return await o.groupUpdateSubject(e,t);case "description":if(!s)return await o.groupUpdateDescription(e,t);case "picture":return await o.updateProfilePicture(e,ae(t))}}async setting(e,t){let n=i.get("socket");switch(t){case "open":return await n.groupSettingUpdate(e,"not_announcement");case "close":return await n.groupSettingUpdate(e,"announcement");case "locked":return await n.groupSettingUpdate(e,t);case "unlocked":return await n.groupSettingUpdate(e,t);case "all_member_add":return await n.groupMemberAddMode(e,t);case "admin_add":return await n.groupMemberAddMode(e,t)}}async leave(e){return await i.get("socket").groupLeave(e)}async inviteCode(e,t){let n=i.get("socket");switch(t){case "code":return await n.groupInviteCode(e);case "revoke":return await n.groupRevokeInvite(e);case "accept":return await n.groupAcceptInvite(e);case "info":return await n.groupGetInviteInfo(e)}}async metadata(e){return await i.get("socket").groupMetadata(e)}async requestJoin(e,t,n){let o=i.get("socket");switch(n){case "approve":return await o.groupRequestParticipantsUpdate(e,t,n);case "reject":return await o.groupRequestParticipantsUpdate(e,t,n)}}async requestJoinList(e){return await i.get("socket").groupRequestParticipantsList(e)}async fetchAllGroups(){return await i.get("socket").groupFetchAllParticipating()}async ephemeral(e,t){let n=i.get("socket"),o={off:0,"24h":86400,"7d":604800,"90d":7776e3};return await n.groupToggleEphemeral(e,o[t])}},be=class{constructor(e){this.glient=e;this.group=new Je(e);}group};var Ge=class{constructor(e){this.client=e;}async create(e,t){return await i.get("socket").newsletterCreate(e,t)}async action(e,t){let n=i.get("socket");switch(t){case "follow":return await n.newsletterFollow(e);case "unfollow":return await n.newsletterUnfollow(e);case "mute":return await n.newsletterMute(e);case "unmute":return await n.newsletterUnmute(e);}}async update(e,t,n){let o=i.get("socket"),s=Buffer.isBuffer(t);switch(n){case "name":if(!s)return await o.newsletterUpdateName(e,t);case "description":if(!s)return await o.newsletterUpdateDescription(e,t);case "picture":return await o.newsletterUpdatePicture(e,ae(t))}}async metadata(e,t){return await i.get("socket").newsletterMetadata(t,e)}async subscribers(e){return await i.get("socket").newsletterSubscribers(e)}async reaction(e,t,n){return await i.get("socket").newsletterReactMessage(e,t,n)}async fetchMessages(e,t,n,o){let s=i.get("socket"),r=n.getTime()/1e3,c=o.getTime()/1e3;return await s.newsletterFetchMessages(e,t,r,c)}async adminCount(e){return await i.get("socket").newsletterAdminCount(e)}async changeOwner(e,t){return await i.get("socket").newsletterChangeOwner(e,t)}async demote(e,t){return await i.get("socket").newsletterDemote(e,t)}async delete(e){return await i.get("socket").newsletterDelete(e)}async removePicture(e){return await i.get("socket").newsletterRemovePicture(e)}},Me=class{constructor(e){this.nlient=e;this.newsletter=new Ge(e);}newsletter};var Ke=class{constructor(e){this.client=e;}async block(e){return await i.get("socket").updateBlockStatus(e,"block")}async unblock(e){return await i.get("socket").updateBlockStatus(e,"unblock")}async lastSeen(e){return await i.get("socket").updateLastSeenPrivacy(e)}async online(e){return await i.get("socket").updateOnlinePrivacy(e)}async picture(e){return await i.get("socket").updateProfilePicturePrivacy(e)}async status(e){return await i.get("socket").updateStatusPrivacy(e)}async readReceipt(e){return await i.get("socket").updateReadReceiptsPrivacy(e)}async groupsAdd(e){return await i.get("socket").updateGroupsAddPrivacy(e)}async ephemeral(e){let t=i.get("socket"),n={off:0,"24h":86400,"7d":604800,"90d":7776e3};return await t.updateDefaultDisappearingMode(n[e])}async blocklist(){return await i.get("socket").fetchBlocklist()}async getSettings(){return await i.get("socket").fetchPrivacySettings(true)}},ve=class{constructor(e){this.plient=e;this.privacy=new Ke(e);}privacy};var Gr=u.object({status:u.enum(["connecting","open","close","reload","syncing"]),authType:u.enum(["pairing","qr"]),authTimeout:u.number().optional(),syncProgress:u.number().optional(),syncCompleted:u.boolean().default(false).optional(),qr:u.string().optional(),code:u.string().optional()});var Rs=u.enum(["unknown","android","ios","desktop","web"]),Es=u.enum(["text","album","image","contact","location","document","audio","video","protocol","contacts","highlyStructured","sendPayment","requestPayment","groupStatusMention","statusMention","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","product","deviceSent","lists","viewOnce","order","ephemeral","invoice","buttons","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","placeholder","encEventUpdate"]),Rt=u.object({channelId:u.string(),uniqueId:u.string(),chatId:u.string(),chatType:Es,receiverId:u.string(),receiverName:u.string(),roomId:u.string(),roomName:u.string(),senderLid:u.string(),senderId:u.string(),senderName:u.string(),senderDevice:Rs,timestamp:u.number(),text:u.string().nullable(),mentions:u.string().array(),links:u.string().array(),isBot:u.boolean(),isFromMe:u.boolean(),isPrefix:u.boolean(),isSpam:u.boolean(),isTagMe:u.boolean(),isStatusMention:u.boolean(),isGroupStatusMention:u.boolean(),isHideTags:u.boolean(),isGroup:u.boolean(),isNewsletter:u.boolean(),isQuestion:u.boolean(),isStory:u.boolean(),isViewOnce:u.boolean(),isEdited:u.boolean(),isDeleted:u.boolean(),isPinned:u.boolean(),isUnPinned:u.boolean(),isBroadcast:u.boolean(),isEphemeral:u.boolean(),isForwarded:u.boolean(),citation:u.record(u.string(),u.function({output:u.promise(u.boolean())})).nullable(),media:u.object({buffer:u.function({output:u.promise(u.instanceof(Buffer))}),stream:u.function({output:u.promise(u.instanceof(Is))})}).loose().nullable(),message:u.function({input:[],output:u.custom()})}),Yr=Rt.extend({replied:Rt.nullable()});var si=u.object({callId:u.string(),callerId:u.string(),callerName:u.string(),roomId:u.string(),roomName:u.string(),date:u.date(),offline:u.boolean(),status:u.enum(["accept","offer","reject","ringing","terminate","timeout"]),isVideo:u.boolean(),isGroup:u.boolean()});var xe=class{collect(e,t,n){let o=t.max??1/0;if(o<=0){n([]);return}let s=i.collectors.get(e);s&&(clearTimeout(s.timeoutId),s.callback(s.messages),i.collectors.delete(e));let r=setTimeout(()=>{let c=i.collectors.get(e);c&&(c.callback(c.messages),i.collectors.delete(e));},t.timeout);i.collectors.set(e,{messages:[],max:o,filter:t.filter,callback:n,timeoutId:r});}push(e){let t=i.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),i.collectors.delete(e.channelId)),true)}has(e){return i.collectors.has(e)}cancel(e){let t=i.collectors.get(e);return t?(clearTimeout(t.timeoutId),t.callback(t.messages),i.collectors.delete(e),t.messages):[]}};var Ps={checkIntervalMs:6e4,staleThresholdMs:12e4,cooldownMs:6e4,maxRetries:3},Se=class{constructor(e,t={}){this.client=e;this.options={...Ps,...t};}lastActivityTime=Date.now();lastRecoveryTime=0;checkInterval=null;isRecovering=false;retryCount=0;options;start(){this.checkInterval||(this.lastActivityTime=Date.now(),this.setupActivityListeners(),this.checkInterval=setInterval(()=>this.check(),this.options.checkIntervalMs),i.spinner.success(" Health manager monitoring started"));}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null);}touch(){this.lastActivityTime=Date.now(),this.retryCount=0;}setupActivityListeners(){let e=this.client.socket;if(!e?.ev)return;let t=["messages.upsert","message-receipt.update","presence.update","chats.update","connection.update"];for(let n of t)e.ev.on(n,()=>this.touch());}async check(){if(this.isRecovering)return;let t=Date.now()-this.lastActivityTime;t>this.options.staleThresholdMs&&(i.spinner.warn(` Connection stale for ${Math.round(t/1e3)}s. Triggering recovery...`),await this.recover());}isInCooldown(){return Date.now()-this.lastRecoveryTime<this.options.cooldownMs}async recover(){if(!this.isRecovering){if(this.isInCooldown()){i.spinner.warn(" Recovery in cooldown, skipping...");return}if(this.retryCount>=this.options.maxRetries){i.spinner.error(` Max health recovery retries (${this.options.maxRetries}) reached.`);return}this.isRecovering=true,this.lastRecoveryTime=Date.now(),this.retryCount++;try{i.spinner.warn(` Health recovery attempt ${this.retryCount}/${this.options.maxRetries}...`);let e=this.client.socket;if(e?.ws?.readyState===1)try{await e.fetchStatus(e.user?.id||""),this.touch(),i.spinner.success(" Health check passed, session is alive");return}catch{i.spinner.warn(" Health check failed, session unresponsive");}await te(this.client.options.session),i.spinner.warn(" Re-initializing client connection..."),await this.client.initialize(),this.touch(),i.spinner.success(" Health recovery successful");}catch(e){i.spinner.error(` Health recovery failed: ${e instanceof Error?e.message:String(e)}`);}finally{this.isRecovering=false;}}}};var Te=class{constructor(e){this.client=e;this.initialize();}logsInitialized=false;logsDisplayed=false;isReady=false;getRoomColor(e){return e?.isNewsletter?"blue":e?.isGroup?e?.isGroup?"lime":"dimgray":"orange"}initialize(){if(!this.client.options.showLogs||this.logsInitialized)return;this.logsInitialized=true,i.get("socket").ev.on("connection.update",({connection:t})=>{this.logsDisplayed||t==="open"&&(this.logsDisplayed=true,this.isReady=true,console.log(),i.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.isReady)return;let t=h(this.getRoomColor(e)),n=e?.text?.toLowerCase()?.match("zaileys"),o=v(`[${new Date(e?.timestamp).toTimeString().split(" ")[0]}]`,"dimgray"),s=v(`${e?.roomName}`,t),r=e?.text?.slice(0,300)||"",c=r?.length>=300?"...":"",l=`${o} \u2192 ${s}
|
|
7
|
+
`;e?.isNewsletter?l+=`${v("[room]","dimgray")} \u2192 ${v(`${e?.roomName} (${W(e?.roomId)})`,t)}
|
|
8
|
+
`:l+=`${v("[sender]","dimgray")} \u2192 ${v(`${e?.senderName} (${W(e?.senderId)})`,t)}
|
|
9
|
+
`,l+=`${v(`[${e?.chatType||"unknown"}]`,"dimgray")} \u2192 ${v(r+c,n?["#ff5f6d","#ffc371"]:"brown")}
|
|
10
|
+
`,l+="\u2014",console.log(l);}call(e){if(!i.get("logs")?.ready)return;let t=h(this.getRoomColor(e)),n=v(`[${new Date(e?.date).toTimeString().split(" ")[0]}]`,"dimgray"),o=v(`${e?.roomName}`,t),s=`${n} \u2192 ${o}
|
|
11
|
+
`;s+=`${v("[caller]","dimgray")} \u2192 ${v(`${e?.callerName} (${W(e?.callerId)})`,t)}
|
|
12
|
+
`,s+=`${v(`[${e?.status}]`,"dimgray")} \u2192 ${v(e?.isVideo?"Video Call":"Voice Call","brown")}
|
|
13
|
+
`,s+="\u2014",console.log(s);}};var Ce=class{stack=[];use(e){return this.stack.push(e),this}async run(e){let t=-1,n=async o=>{if(o<=t)throw "next() called multiple times";t=o;let s=this.stack[o];if(s)try{await s(e,()=>n(o+1));}catch(r){throw console.error("Middleware error:",r),r}};await n(0);}};var Ae=class{plugins=[];pluginsDir;constructor(e=je.join(process.cwd(),"plugins")){this.pluginsDir=e;}getAllFiles(e,t=[]){if(!N.existsSync(e))return t;let n=N.readdirSync(e);for(let o of n){let s=je.join(e,o);N.statSync(s).isDirectory()?this.getAllFiles(s,t):(o.endsWith(".ts")||o.endsWith(".js"))&&!o.endsWith(".d.ts")&&t.push(s);}return t}async load(){if(!N.existsSync(this.pluginsDir))return;let e=this.getAllFiles(this.pluginsDir);for(let t of e)try{let o=(await import(pathToFileURL(t).href)).default;o?.default&&(o=o.default),o?.handler&&o?.config&&this.plugins.push(o);}catch{}}async execute(e,t){let n=t.messages.text||"";for(let o of this.plugins)try{this.match(n,o.config.matcher)&&await o.handler(e,t);}catch{}}match(e,t){return t.some(n=>e===n||e.startsWith(n+" "))}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();}},Ci=(a,e)=>({handler:a,config:e});var Ie=class{classInjection(e,t){let n=t.length;return new Proxy(e,{get(o,s,r){if(s in o){let c=Reflect.get(o,s,r);return typeof c=="function"?c.bind(o):c}for(let c=0;c<n;c++){let l=t[c];if(s in l){let p=Reflect.get(l,s,r);return typeof p=="function"?p.bind(l):p}}},set(o,s,r,c){if(s in o)return Reflect.set(o,s,r,c);for(let l=0;l<n;l++){let p=t[l];if(s in p)return Reflect.set(p,s,r,c)}return Reflect.set(o,s,r,c)},has(o,s){if(s in e)return true;for(let r=0;r<n;r++)if(s in t[r])return true;return false},ownKeys(){let o=[];for(let s of Reflect.ownKeys(e))o.push(s);for(let s=0;s<n;s++)for(let r of Reflect.ownKeys(t[s]))o.includes(r)||o.push(r);return o},getOwnPropertyDescriptor(o,s){let r=Object.getOwnPropertyDescriptor(e,s);if(r)return r;for(let c=0;c<n;c++)if(r=Object.getOwnPropertyDescriptor(t[c],s),r)return r}})}};var Et=class{constructor(e){this.options=e;this.options=Y(St,e);let t=new Ie().classInjection(this,[new ke(this),new be(this),new ve(this),new Me(this),new we(this)]);return this._ready=this.initialize(t),t}listener;_ready;health;logs;collector=new xe;middleware=new Ce;plugins=new Ae;async initialize(e){await kt(),await mt(this.options.disableFFmpeg),await rt(this),await this.plugins.load(),this.listener=new ye(e||this),this.logs=new Te(this),this.health=new Se(e||this),this.health.start();}ready(){return this._ready}db(e){return i.db(this.options.session,e)}on(e,t){i.events.on(e,t);}use(e){return this.middleware.use(e),this}get socket(){return i.get("socket")}async getMessageByChatId(e,t){let n=await this.db("messages").all();for(let[o]of n){let s=await this.db("messages").query(o).where("key.id","=",e).first();if(s)return s={...s,message:t},await this.listener.messages.parse(s)}return null}async getRoomName(e){let t=i.get("socket"),n=e.endsWith("@g.us"),o=null;return n&&(o=(await t.groupMetadata(e))?.subject||null),R(o)}async getLabelName(e){let t=await this.db("messages").get(e),n=F(t,["message.protocolMessage.memberLabel"]);return R(n?.label)||null}};
|
|
14
14
|
/*
|
|
15
15
|
* Copyright (c) 2025 zaadevofc.
|
|
16
16
|
* All rights reserved.
|
|
@@ -18,7 +18,7 @@ by ${fe.author} \xB7 v${fe.version}`,o=`${e?"Already using latest version!":`Upd
|
|
|
18
18
|
* See LICENSE file for details.
|
|
19
19
|
|
|
20
20
|
* Author: zaadevofc
|
|
21
|
-
* Last build time: 12/
|
|
21
|
+
* Last build time: 12/18/2025 3:30:20 PM
|
|
22
22
|
*
|
|
23
23
|
* Repository: git+https://github.com/zeative/zaileys.git
|
|
24
|
-
*/export{
|
|
24
|
+
*/export{ne as AudioProcessor,Rt as BaseMessagesType,is as ButtonInteractiveCallType,rs as ButtonInteractiveCopyType,ns as ButtonInteractiveReplyType,as as ButtonInteractiveSingleSelectType,cs as ButtonInteractiveType,os as ButtonInteractiveUrlType,ls as ButtonSimpleType,vt as ButtonType,us as CitationType,Et as Client,fs as ClientAuthPairingType,gs as ClientAuthQRType,xt as ClientBaseType,St as ClientOptionsType,Rs as DEVICE_ENUM_TYPES,ie as DocumentProcessor,rr as EventEnumType,ms as FakeReplyType,oe as ImageProcessor,ps as LimiterType,si as ListenerCallsType,Gr as ListenerConnectionType,Yr as ListenerMessagesType,Es as MESSAGE_ENUM_TYPES,Q as MediaProcessor,Ae as Plugins,ds as StickerMetadataType,re as StickerProcessor,qe as StickerShapeType,D as VideoProcessor,W as cleanJid,ut as cleanMediaObject,nt as cleanupSocket,mt as configureFFmpeg,Ci as definePlugins,Oe as extractJids,lt as extractUrls,G as findGlobalWord,In as findNestedByKeys,_ as generateId,se as getDeepContent,ot as getExistingSocket,it as getLatestLibVersion,ze as getMediaThumbnail,pt as getUsersMentions,Hn as getVideoDuration,Kn as getVideoThumbnail,dt as getWaAudio,gt as getWaDocument,ft as getWaSticker,h as ignoreLint,v as logColor,Rn as modifyFn,R as normalizeText,Fn as numbersToJids,F as pickKeysFromArray,An as randomize,rt as registerAuthCreds,at as removeAuthCreds,te as repairSessionKeys,Cn as shuffleString,ae as toBuffer,Ne as toJson,J as toString,et as useAuthState};
|
package/package.json
CHANGED
|
@@ -1,77 +1,77 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "zaileys",
|
|
3
|
-
"description": "Zaileys - Simplified WhatsApp Node.js TypeScript/JavaScript API",
|
|
4
|
-
"version": "2.
|
|
5
|
-
"license": "MIT",
|
|
6
|
-
"main": "dist/index.js",
|
|
7
|
-
"module": "dist/index.mjs",
|
|
8
|
-
"types": "dist/index.d.ts",
|
|
9
|
-
"exports": {
|
|
10
|
-
".": {
|
|
11
|
-
"types": "./dist/index.d.ts",
|
|
12
|
-
"require": "./dist/index.js",
|
|
13
|
-
"import": "./dist/index.mjs"
|
|
14
|
-
}
|
|
15
|
-
},
|
|
16
|
-
"author": "zaadevofc",
|
|
17
|
-
"repository": {
|
|
18
|
-
"url": "git+https://github.com/zeative/zaileys.git"
|
|
19
|
-
},
|
|
20
|
-
"keywords": [
|
|
21
|
-
"baileys",
|
|
22
|
-
"zaileys",
|
|
23
|
-
"whatsapp",
|
|
24
|
-
"whatsapp-api",
|
|
25
|
-
"whatsapp-web",
|
|
26
|
-
"whatsapp-bot",
|
|
27
|
-
"multi-device",
|
|
28
|
-
"simplified",
|
|
29
|
-
"automation",
|
|
30
|
-
"modern-library",
|
|
31
|
-
"nodejs",
|
|
32
|
-
"javascript-typescript"
|
|
33
|
-
],
|
|
34
|
-
"scripts": {
|
|
35
|
-
"test": "tsx --watch examples/test.ts",
|
|
36
|
-
"build": "tsup",
|
|
37
|
-
"r:patch": "npm run build && npm version patch && npm publish",
|
|
38
|
-
"r:minor": "npm run build && npm version minor && npm publish",
|
|
39
|
-
"r:major": "npm run build && npm version major && npm publish"
|
|
40
|
-
},
|
|
41
|
-
"devDependencies": {
|
|
42
|
-
"@types/lodash": "^4.17.21",
|
|
43
|
-
"@types/
|
|
44
|
-
"@types/
|
|
45
|
-
"
|
|
46
|
-
"rolldown
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
"@
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"node-
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"zod": "^4.1.13"
|
|
72
|
-
},
|
|
73
|
-
"packageManager": "pnpm@10.24.0",
|
|
74
|
-
"engines": {
|
|
75
|
-
"node": ">=20.0.0"
|
|
76
|
-
}
|
|
77
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "zaileys",
|
|
3
|
+
"description": "Zaileys - Simplified WhatsApp Node.js TypeScript/JavaScript API",
|
|
4
|
+
"version": "2.1.1",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"module": "dist/index.mjs",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"require": "./dist/index.js",
|
|
13
|
+
"import": "./dist/index.mjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"author": "zaadevofc",
|
|
17
|
+
"repository": {
|
|
18
|
+
"url": "git+https://github.com/zeative/zaileys.git"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"baileys",
|
|
22
|
+
"zaileys",
|
|
23
|
+
"whatsapp",
|
|
24
|
+
"whatsapp-api",
|
|
25
|
+
"whatsapp-web",
|
|
26
|
+
"whatsapp-bot",
|
|
27
|
+
"multi-device",
|
|
28
|
+
"simplified",
|
|
29
|
+
"automation",
|
|
30
|
+
"modern-library",
|
|
31
|
+
"nodejs",
|
|
32
|
+
"javascript-typescript"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"test": "tsx --watch examples/test.ts",
|
|
36
|
+
"build": "tsup",
|
|
37
|
+
"r:patch": "npm run build && npm version patch && npm publish",
|
|
38
|
+
"r:minor": "npm run build && npm version minor && npm publish",
|
|
39
|
+
"r:major": "npm run build && npm version major && npm publish"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/lodash": "^4.17.21",
|
|
43
|
+
"@types/lz4": "^0.6.4",
|
|
44
|
+
"@types/node": "^24.10.1",
|
|
45
|
+
"@types/qrcode-terminal": "^0.12.2",
|
|
46
|
+
"rolldown": "1.0.0-beta.52",
|
|
47
|
+
"rolldown-plugin-dts": "^0.18.1",
|
|
48
|
+
"tsup": "^8.5.1",
|
|
49
|
+
"tsx": "^4.21.0",
|
|
50
|
+
"typescript": "^5.9.3"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
|
54
|
+
"@ffprobe-installer/ffprobe": "^2.1.2",
|
|
55
|
+
"async-mutex": "^0.5.0",
|
|
56
|
+
"audio-decode": "^2.2.3",
|
|
57
|
+
"baileys": "7.0.0-rc.9",
|
|
58
|
+
"figlet": "^1.9.4",
|
|
59
|
+
"file-type": "^21.1.1",
|
|
60
|
+
"fluent-ffmpeg": "^2.1.3",
|
|
61
|
+
"gradient-string": "^3.0.0",
|
|
62
|
+
"jetdb": "^1.1.0",
|
|
63
|
+
"lodash": "^4.17.21",
|
|
64
|
+
"nanospinner": "^1.2.2",
|
|
65
|
+
"node-cache": "^5.1.2",
|
|
66
|
+
"node-webpmux": "^3.2.1",
|
|
67
|
+
"pino": "^10.1.0",
|
|
68
|
+
"qrcode-terminal": "^0.12.0",
|
|
69
|
+
"rate-limiter-flexible": "^9.0.0",
|
|
70
|
+
"sharp": "^0.34.5",
|
|
71
|
+
"zod": "^4.1.13"
|
|
72
|
+
},
|
|
73
|
+
"packageManager": "pnpm@10.24.0",
|
|
74
|
+
"engines": {
|
|
75
|
+
"node": ">=20.0.0"
|
|
76
|
+
}
|
|
77
|
+
}
|
package/tsconfig.json
CHANGED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
name: Deploy Jekyll with GitHub Pages dependencies preinstalled
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
# Runs on pushes targeting the default branch
|
|
5
|
-
push:
|
|
6
|
-
branches: ["main"]
|
|
7
|
-
|
|
8
|
-
# Allows you to run this workflow manually from the Actions tab
|
|
9
|
-
workflow_dispatch:
|
|
10
|
-
|
|
11
|
-
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
|
12
|
-
permissions:
|
|
13
|
-
contents: read
|
|
14
|
-
pages: write
|
|
15
|
-
id-token: write
|
|
16
|
-
|
|
17
|
-
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
|
18
|
-
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
|
19
|
-
concurrency:
|
|
20
|
-
group: "pages"
|
|
21
|
-
cancel-in-progress: false
|
|
22
|
-
|
|
23
|
-
jobs:
|
|
24
|
-
# Build job
|
|
25
|
-
build:
|
|
26
|
-
runs-on: ubuntu-latest
|
|
27
|
-
steps:
|
|
28
|
-
- name: Checkout
|
|
29
|
-
uses: actions/checkout@v4
|
|
30
|
-
- name: Setup Pages
|
|
31
|
-
uses: actions/configure-pages@v5
|
|
32
|
-
- name: Build with Jekyll
|
|
33
|
-
uses: actions/jekyll-build-pages@v1
|
|
34
|
-
with:
|
|
35
|
-
source: ./
|
|
36
|
-
destination: ./_site
|
|
37
|
-
|
|
38
|
-
- name: Inject Google Site Verification Meta Tag
|
|
39
|
-
run: |
|
|
40
|
-
META_TAG='<meta name="google-site-verification" content="D1yM0hOKOz3yT6N4uIb753KAWhGQ1m80hIyCkd8QrTg" />'
|
|
41
|
-
find ./_site -name "*.html" -exec sudo sed -i "s|</head>|$META_TAG\n</head>|g" {} +
|
|
42
|
-
|
|
43
|
-
- name: Upload artifact
|
|
44
|
-
uses: actions/upload-pages-artifact@v3
|
|
45
|
-
|
|
46
|
-
# Deployment job
|
|
47
|
-
deploy:
|
|
48
|
-
environment:
|
|
49
|
-
name: github-pages
|
|
50
|
-
url: ${{ steps.deployment.outputs.page_url }}
|
|
51
|
-
runs-on: ubuntu-latest
|
|
52
|
-
needs: build
|
|
53
|
-
steps:
|
|
54
|
-
- name: Deploy to GitHub Pages
|
|
55
|
-
id: deployment
|
|
56
|
-
uses: actions/deploy-pages@v4
|