zaileys 4.16.0 → 4.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builder/builder.d.ts +5 -0
- package/dist/builder/content/buttons.d.ts +2 -0
- package/dist/builder/content/html-app.d.ts +6 -0
- package/dist/index.cjs +16 -16
- package/dist/index.mjs +16 -16
- package/package.json +3 -1
package/dist/index.cjs
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
'use strict';var ou=require('baileys'),crypto=require('node:crypto'),Y=require('node:fs/promises'),url=require('node:url'),H=require('node:path'),fs$1=require('node:fs'),os$1=require('node:os'),child_process=require('node:child_process'),jimp=require('jimp'),ha=require('node-webpmux'),lruCache=require('lru-cache');require('node:stream');var Yc=require('qrcode-terminal'),Zc=require('pino'),events=require('node:events');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ou__default=/*#__PURE__*/_interopDefault(ou);var Y__default=/*#__PURE__*/_interopDefault(Y);var H__default=/*#__PURE__*/_interopDefault(H);var ha__default=/*#__PURE__*/_interopDefault(ha);var Yc__default=/*#__PURE__*/_interopDefault(Yc);var Zc__default=/*#__PURE__*/_interopDefault(Zc);var zo=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var p=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysBuilderError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var P={OPUS:{CODEC:"libopus",CHANNELS:1,FREQUENCY:48e3,BITRATE:"48k",FORMAT:"ogg"},THUMBNAIL:{SIZE:100,QUALITY:50,TIMESTAMP:"10%"},STICKER:{SIZE:512,MAX_DURATION:6,FPS:10,DEFAULT_QUALITY:60,COMPRESSION_LEVEL:6},MIME:{AUDIO:"audio/",VIDEO:"video/",IMAGE:"image/",GIF:"image/gif",MP4:"video/mp4"}},Vt="ffmpeg",xr="ffprobe",Ar=false,Cr=async(n,e)=>{if(n===void 0||n.length===0)return e;try{if(process.platform==="win32")return await Y__default.default.access(n),n;let t=()=>Y__default.default.access(n,fs$1.constants.X_OK).then(()=>!0,()=>!1);if(await t())return n;let{mode:r}=await Y__default.default.stat(n);return await Y__default.default.chmod(n,r|64),await t()?n:e}catch{return e}},Ht=async(n=false)=>{if(n||Ar)return;Ar=true;let e=process.env.FFMPEG_PATH,t=process.env.FFPROBE_PATH,r;try{r=(await import('@ffmpeg-installer/ffmpeg')).default?.path;}catch{}if(Vt=e??await Cr(r,"ffmpeg"),Vt!=="ffmpeg"){let i=H__default.default.dirname(Vt),o=process.platform==="win32"?";":":",a=process.env.PATH??"";a.split(o).includes(i)||(process.env.PATH=`${i}${o}${a}`);}let s;try{s=(await import('@ffprobe-installer/ffprobe')).default?.path;}catch{}xr=t??await Cr(s,"ffprobe");},Er=12e4,Pr=3e4,Xo=64*1024,Zo=3e4,kr=64*1024*1024,fe={maxConcurrent:4,maxQueued:64,queueTimeoutMs:12e4,maxImagePixels:5e7},Or=()=>({...fe}),Rr=n=>{let e=(t,r,s)=>{if(r!==void 0&&(!Number.isFinite(r)||!Number.isInteger(r)||r<s))throw new Error(`invalid media limit ${t}: ${r}`)};e("maxConcurrent",n.maxConcurrent,1),e("maxQueued",n.maxQueued,0),e("queueTimeoutMs",n.queueTimeoutMs,1),e("maxImagePixels",n.maxImagePixels,1),Object.assign(fe,Object.fromEntries(Object.entries(n).filter(([,t])=>t!==void 0)));},Nn=0,Xe=[],ea=async()=>{if(Nn<fe.maxConcurrent)Nn+=1;else {if(Xe.length>=fe.maxQueued)throw new Error(`ffmpeg queue is full (${fe.maxQueued} jobs waiting)`);await new Promise((e,t)=>{let r={grant:()=>{clearTimeout(s),e();}},s=setTimeout(()=>{let i=Xe.indexOf(r);i>=0&&Xe.splice(i,1),t(new Error(`ffmpeg job waited more than ${fe.queueTimeoutMs}ms for a slot`));},fe.queueTimeoutMs);Xe.push(r);});}let n=false;return ()=>{if(n)return;n=true;let e=Xe.shift();e?e.grant():Nn-=1;}},zt=()=>Date.now().toString(36)+crypto.randomBytes(4).toString("hex"),$=async n=>{let{fileTypeFromBuffer:e}=await import('file-type');return e(n)},se=class{static generateUniqueId(){return crypto.randomBytes(12).toString("hex")}static createTempPath(e,t){return H__default.default.join(os$1.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>Y__default.default.unlink(t)));}static async safeReadFile(e){try{return await Y__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await Y__default.default.writeFile(e,t,{flag:"wx",mode:384});}catch{throw new Error(`Failed to write file: ${e}`)}}},R=class{static async toBuffer(e){if(Buffer.isBuffer(e))return e;if(e instanceof ArrayBuffer)return Buffer.from(e);if(typeof e=="string")return this.fromString(e);throw new Error("Invalid input type: expected string, Buffer, or ArrayBuffer")}static async fromString(e){if(e.startsWith("http://")||e.startsWith("https://"))return this.fromUrl(e);try{if(await Y__default.default.stat(e).then(t=>t.isFile()).catch(()=>!1))return await Y__default.default.readFile(e)}catch{}return Buffer.from(e,"base64")}static async fromUrl(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Zo);try{let s=await fetch(e,{signal:t.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let i=await s.arrayBuffer(),o=Buffer.from(i);if(o.byteLength>kr)throw new Error(`Fetched body exceeds ${kr} bytes`);return o}catch(s){throw new Error(`Failed to fetch URL: ${s instanceof Error?s.message:String(s)}`)}finally{clearTimeout(r);}}static async getExtension(e){let{fileTypeFromBuffer:t}=await import('file-type'),r=await t(e);if(!r)return "tmp";let s=r.ext.toLowerCase();return ["wav","ogg","mp4","gif","jpg","webp","tmp","mp3","png"].includes(s)?s:"tmp"}},q=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(P.MIME.IMAGE)||e.startsWith(P.MIME.VIDEO)}static isAnimated(e){return e===P.MIME.GIF||e.startsWith(P.MIME.VIDEO)}},he=class{static async process(e){await Ht();let t=await ea();try{await new Promise((r,s)=>{let i=["-y","-i",e.input,...e.options,e.output],o=child_process.spawn(Vt,i,{stdio:"ignore"}),a=!1,d=l=>{a||(a=!0,clearTimeout(c),l());},c=setTimeout(()=>{o.kill("SIGKILL");let l=new Error(`FFmpeg timed out after ${Er}ms`);Promise.resolve(e.onError(l)).catch(()=>{}),d(()=>s(l));},Er);o.on("close",l=>{if(a)return;if(l===0){Promise.resolve(e.onEnd()).then(()=>d(r),f=>d(()=>s(f)));return}let u=new Error(`FFmpeg exited with code ${l}`);Promise.resolve(e.onError(u)).then(()=>d(()=>s(u)),f=>d(()=>s(f)));}),o.on("error",l=>{Promise.resolve(e.onError(l)).finally(()=>d(()=>s(l)));});});}finally{t();}}static async getDuration(e){if(await Ht(),typeof e!="string"||e.length===0||e.startsWith("-"))throw new Error("getDuration expects a local file path");if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))throw new Error("getDuration does not accept protocol inputs");let t=await Y__default.default.stat(e).catch(()=>{});if(t===void 0||!t.isFile())throw new Error(`getDuration: not a readable file: ${e}`);return new Promise((r,s)=>{let i=child_process.spawn(xr,["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),o="",a=false,d=l=>{a||(a=true,clearTimeout(c),l());},c=setTimeout(()=>{i.kill("SIGKILL"),d(()=>s(new Error(`ffprobe timed out after ${Pr}ms`)));},Pr);i.stdout.on("data",l=>{o.length>Xo||(o+=l.toString());}),i.on("close",l=>{d(l===0?()=>r(parseFloat(o.trim())||0):()=>s(new Error(`ffprobe exited with code ${l}`)));}),i.on("error",l=>d(()=>s(l)));})}};var ia=3e4,oa=64*1024*1024,Lr="application/octet-stream",Re=async n=>n.byteLength===0?Lr:(await $(n))?.mime??Lr,Ze=async n=>({buffer:n,mime:await Re(n),size:n.byteLength}),aa=async(n,e,t)=>{let r=Number(n.headers?.get?.("content-length")??"0");if(Number.isFinite(r)&&r>t)throw new p("MEDIA_LOAD_FAILED",`${e} exceeds ${t} bytes`);let s=n.body;if(s==null||typeof s.getReader!="function"){let d=Buffer.from(await n.arrayBuffer());if(d.byteLength>t)throw new p("MEDIA_LOAD_FAILED",`${e} exceeds ${t} bytes`);return d}let i=[],o=0,a=s.getReader();for(;;){let{done:d,value:c}=await a.read();if(d)break;if(c!==void 0){if(o+=c.byteLength,o>t)throw await a.cancel().catch(()=>{}),new p("MEDIA_LOAD_FAILED",`${e} exceeds ${t} bytes`);i.push(c);}}return Buffer.concat(i)},Nr=async(n,e,t)=>{let r=new AbortController,s=setTimeout(()=>r.abort(),e);try{let i=await fetch(n,{signal:r.signal});if(!i.ok)throw new p("MEDIA_LOAD_FAILED",`fetch ${n} failed with status ${i.status}`,{cause:i.status});return await aa(i,n,t)}catch(i){throw i instanceof p?i:new p("MEDIA_LOAD_FAILED",`fetch ${n} failed: ${i.message}`,{cause:i})}finally{clearTimeout(s);}},Dr=async(n,e)=>{try{if((await Y.stat(n)).size>e)throw new p("MEDIA_LOAD_FAILED",`${n} exceeds ${e} bytes`);return await Y.readFile(n)}catch(t){throw t instanceof p?t:new p("MEDIA_LOAD_FAILED",`read ${n} failed: ${t.message}`,{cause:t})}},da=n=>n.startsWith("http://")||n.startsWith("https://"),ca=[".zaileys"],Br=(n,e)=>{let t=H.resolve(n);for(let r of e){let s=H.resolve(r);if(t===s||t.startsWith(s+H.sep))throw new p("MEDIA_LOAD_FAILED",`refusing to read ${n}: it resolves inside the protected directory ${r}`)}return t},la=/^(?:0\.|10\.|127\.|169\.254\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.)/,ua=n=>{let e=n.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e.endsWith(".internal")||e==="::1"||e==="::"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe80:")?true:la.test(e)},Fr=(n,e)=>{let t;try{t=new URL(n);}catch{throw new p("MEDIA_LOAD_FAILED",`invalid url: ${n}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new p("MEDIA_LOAD_FAILED",`unsupported url scheme: ${t.protocol}`);if(!e&&ua(t.hostname))throw new p("MEDIA_LOAD_FAILED",`refusing to fetch a private address: ${t.hostname}`);return n},et={},Wr=n=>{if(n.maxBytes!==void 0&&(!Number.isInteger(n.maxBytes)||n.maxBytes<1))throw new p("INVALID_OPTIONS",`invalid maxBytes: ${n.maxBytes}`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<1))throw new p("INVALID_OPTIONS",`invalid timeoutMs: ${n.timeoutMs}`);et={...et,...Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0))};},Ur=()=>({...et}),B=async(n,e)=>{await Ht();let t={...et,...e,deniedDirs:[...et.deniedDirs??[],...e?.deniedDirs??[]]},r=t.timeoutMs??ia,s=t.maxBytes??oa,i=t.allowPrivateNetwork===true,o=[...ca,...t.deniedDirs??[]];if(Buffer.isBuffer(n))return Ze(n);if(n instanceof URL)return n.protocol==="file:"?Ze(await Dr(Br(url.fileURLToPath(n),o),s)):Ze(await Nr(Fr(n.toString(),i),r,s));if(da(n))return Ze(await Nr(Fr(n,i),r,s));if(t.allowLocalPaths===false)throw new p("MEDIA_LOAD_FAILED","local filesystem paths are disabled; pass a URL, a Buffer, or a file: URL");return Ze(await Dr(Br(n,o),s))};var _e=async(n,e)=>{let{buffer:t}=await B(n),r={image:t};return e?.caption!==void 0&&(r.caption=e.caption),e?.viewOnce!==void 0&&(r.viewOnce=e.viewOnce),r};var ye=async(n,e)=>{let{buffer:t,mime:r}=await B(n);if(!r.startsWith("video/"))throw new p("INVALID_OPTIONS",`video() expects a video source, got mime ${r}`);let s={video:t};return e?.caption!==void 0&&(s.caption=e.caption),e?.gifPlayback!==void 0&&(s.gifPlayback=e.gifPlayback),e?.viewOnce!==void 0&&(s.viewOnce=e.viewOnce),e?.ptv===true&&(s.ptv=true),s};var jr=2,qr=30,pa=async n=>{if(n.type==="image")return _e(n.src,n.caption!==void 0?{caption:n.caption}:void 0);if(n.type==="video")return ye(n.src,n.caption!==void 0?{caption:n.caption}:void 0);throw new p("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(n.type)}`)},$r=async(n,e,t,r)=>{if(!Array.isArray(t)||t.length<jr)throw new p("INVALID_OPTIONS",`album() requires a minimum of ${jr} items`);if(t.length>qr)throw new p("INVALID_OPTIONS",`album() accepts a maximum of ${qr} items`);let s=0,i=0;for(let u of t)if(u.type==="image")s+=1;else if(u.type==="video")i+=1;else throw new p("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(u.type)}`);let o={album:{expectedImageCount:s,expectedVideoCount:i}};r.mentions&&r.mentions.length>0&&(o.mentions=r.mentions),r.mentionAll&&(o.mentionAll=true);let a={};r.quoted&&(a.quoted=r.quoted),r.disappearingSeconds!==void 0&&(a.ephemeralExpiration=r.disappearingSeconds);let d;try{d=await n.sendMessage(e,o,a);}catch(u){throw new p("SEND_FAILED","album parent send rejected",{cause:u})}let c=d?.key;if(!c)throw new p("SEND_FAILED","album parent returned no message key");let l=0;for(let u of t){let f=await pa(u);f.albumParentKey=c;try{await n.sendMessage(e,f);}catch(v){throw new p("SEND_FAILED","album child send rejected",{cause:{parentKey:c,index:l,error:v}})}l+=1;}return c};var Q=async(n,e,t,r,s)=>{let i=r.replace(/[^a-z0-9]+/gi,"_").toLowerCase(),o=se.createTempPath(`${i}_in`,e),a=se.createTempPath(`${i}_out`,t);await se.safeWriteFile(o,n);try{let d=typeof s=="function"?await s(o):s;return await he.process({input:o,output:a,options:d,onEnd:async()=>{},onError:async()=>{}}),await se.safeReadFile(a)}catch(d){throw new Error(`${r} failed: ${d instanceof Error?d.message:String(d)}`)}finally{await se.cleanup([o,a]);}};var Yt=64,Kr=8e3,we=class{static async toOpus(e){return this.convert(e,"opus")}static async toMp3(e){return this.convert(e,"mp3")}static async convert(e,t="opus"){let r=await R.toBuffer(e);q.validate(await $(r),P.MIME.AUDIO);let s=await R.getExtension(r),i=t==="opus"?["-vn","-c:a","libopus","-b:a","48k","-ac","1","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","ogg"]:["-vn","-c:a","libmp3lame","-b:a","128k","-ac","2","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","mp3"];return Q(r,s,t==="opus"?"ogg":"mp3",`${t.toUpperCase()} conversion`,i)}static async waveform(e){let t=await R.toBuffer(e),r=await R.getExtension(t),s=await Q(t,r,"tmp","Waveform generation",["-vn","-ac","1","-ar",String(Kr),"-f","s16le"]),i=Math.floor(s.length/2);return {waveform:this.computeWaveform(s),seconds:Math.max(1,Math.round(i/Kr))}}static computeWaveform(e){let t=Math.floor(e.length/2),r=new Uint8Array(Yt);if(t===0)return r;let s=Math.max(1,Math.floor(t/Yt)),i=[];for(let a=0;a<Yt;a++){let d=0,c=0;for(let l=0;l<s;l++){let u=(a*s+l)*2;u+1<e.length&&(d+=Math.abs(e.readInt16LE(u)),c+=1);}i.push(c>0?d/c:0);}let o=Math.max(...i)||1;for(let a=0;a<Yt;a++)r[a]=Math.floor(i[a]/o*100);return r}};var ma=["-c:v","libx264","-preset","ultrafast","-crf","28","-c:a","aac","-b:a","128k","-movflags","+faststart","-vf","scale=trunc(iw/2)*2:trunc(ih/2)*2","-pix_fmt","yuv420p","-f","mp4"],X=class{static async toMp4(e){let t=await R.toBuffer(e);q.validate(await $(t),P.MIME.VIDEO);let r=await R.getExtension(t);return Q(t,r,"mp4","Video re-encoding",ma)}static async thumbnail(e){let t=await R.toBuffer(e);q.validate(await $(t),P.MIME.VIDEO);let r=await R.getExtension(t),s=P.THUMBNAIL.SIZE;return (await Q(t,r,"jpg","Thumbnail generation",async o=>{let a=await he.getDuration(o);return ["-ss",Math.max(0,a*.1).toString(),"-vframes","1","-s",`${s}x${s}`]})).toString("base64")}static async duration(e){return he.getDuration(e)}};var Le=null,Gr=false;async function ga(){if(Gr)return Le;Gr=true;let n=e=>{typeof e=="function"&&(Le=e);};try{n(zo("sharp"));}catch{Le=null;}if(!Le)try{let e=await import('sharp');n(e.default??e);}catch{Le=null;}return Le}function Vr(n,e){let t=new Uint8Array(n*n),r=n/2,s=n/2,i=n/10,o=[[i,i],[n-i,i],[i,n-i],[n-i,n-i]];for(let a=0;a<n;a++)for(let d=0;d<n;d++){let c=false;if(e==="circle"){let l=d-r,u=a-s;c=l*l+u*u<=r*r;}else if(e==="rounded"){let l=d>=i&&d<n-i&&a>=0&&a<n,u=d>=0&&d<n&&a>=i&&a<n-i,f=false;for(let v of o){let b=d-v[0],T=a-v[1];if(b*b+T*T<=i*i){f=true;break}}c=l||u||f;}else if(e==="oval"){let l=(d-r)/(n/2),u=(a-s)/(n/3);c=l*l+u*u<=1;}t[a*n+d]=c?255:0;}return t}var Jr=2e4,Fn=(n,e)=>{let t=typeof n=="number"&&Number.isFinite(n)?n:0,r=typeof e=="number"&&Number.isFinite(e)?e:0;if(!(t<=0||r<=0)&&(t>Jr||r>Jr||t*r>Or().maxImagePixels))throw new Error(`Image too large to decode safely: ${t}x${r}`)},Hr=(n,e)=>{if(!Number.isInteger(n)||!Number.isInteger(e)||n<=0||e<=0)throw new Error(`Invalid resize target: ${n}x${e}`);Fn(n,e);},fa=n=>{if(n.length>=24&&n.readUInt32BE(0)===2303741511)return {width:n.readUInt32BE(16),height:n.readUInt32BE(20)};if(n.length>=10&&n.toString("ascii",0,3)==="GIF")return {width:n.readUInt16LE(6),height:n.readUInt16LE(8)};if(n.length>=26&&n.toString("ascii",0,2)==="BM")return {width:n.readInt32LE(18),height:Math.abs(n.readInt32LE(22))};if(n.length>=30&&n.toString("ascii",0,4)==="RIFF"&&n.toString("ascii",8,12)==="WEBP"){let e=n.toString("ascii",12,16);if(e==="VP8X")return {width:1+(n.readUIntLE(24,3)&16777215),height:1+(n.readUIntLE(27,3)&16777215)};if(e==="VP8 "&&n.length>=30)return {width:n.readUInt16LE(26)&16383,height:n.readUInt16LE(28)&16383}}},ie=n=>{let e=fa(n);return e!==void 0&&Fn(e.width,e.height),n},Dn=class{sharp;constructor(e){this.sharp=e;}async thumbnail(e){let t=this.sharp;ie(e);let r=t(e).resize(P.THUMBNAIL.SIZE,P.THUMBNAIL.SIZE,{fit:"cover"});return (await r.metadata()).format==="gif"&&(r=t(e,{pages:1}).resize(P.THUMBNAIL.SIZE,P.THUMBNAIL.SIZE)),(await r.jpeg({quality:P.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}async resize(e,t,r){Hr(t,r);let s=this.sharp(ie(e)),i=await s.metadata();return Fn(i.width,i.height),s.resize(t,r,{fit:"cover"}).png().toBuffer()}async toJpeg(e){let t=this.sharp,r=ie(await R.toBuffer(e)),s=await t(r).metadata();if(!s.format)throw new Error("Invalid image type: format could not be determined");return s.format==="webp"||s.format==="png"?t(r).jpeg().toBuffer():r}async resizeForSticker(e,t,r="default"){let s=this.sharp,i=P.STICKER.SIZE,o=s(ie(e)).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}});if(r!=="default"){let a=Buffer.from(Vr(i,r)),d=s(a,{raw:{width:i,height:i,channels:1}});o=o.joinChannel(await d.png().toBuffer());}return o.webp({quality:t}).toBuffer()}},Bn=class{async thumbnail(e){let t=P.THUMBNAIL.SIZE,r=await jimp.Jimp.fromBuffer(ie(e));r.cover({w:t,h:t});let s=await r.getBuffer("image/jpeg",{quality:P.THUMBNAIL.QUALITY});return Buffer.from(s).toString("base64")}async resize(e,t,r){Hr(t,r);let s=await jimp.Jimp.fromBuffer(ie(e));s.cover({w:t,h:r});let i=await s.getBuffer("image/png");return Buffer.from(i)}async toJpeg(e){let t=await R.toBuffer(e);try{let s=await(await jimp.Jimp.fromBuffer(ie(t))).getBuffer("image/jpeg");return Buffer.from(s)}catch{return t}}async resizeForSticker(e,t,r="default"){let s=P.STICKER.SIZE,i=await jimp.Jimp.fromBuffer(ie(e));if(i.contain({w:s,h:s}),r!=="default"){let d=Vr(s,r),c=new jimp.Jimp({width:s,height:s,color:255});for(let l=0;l<s;l++)for(let u=0;u<s;u++)d[l*s+u]===255&&c.setPixelColor(4294967295,u,l);i.mask(c);}let o=Buffer.from(await i.getBuffer("image/png")),a=Math.max(1,Math.min(100,t));return Q(o,"png","webp","Jimp WebP conversion",["-vcodec","libwebp","-q:v",`${a}`,"-preset","default"])}},nt=null;async function Qt(){if(nt)return nt;let n=await ga();return n?nt=new Dn(n):(console.warn("\x1B[33m%s\x1B[0m","[media-process] Jimp is slow. For faster performance, run: npm install sharp"),nt=new Bn),nt}var V=class{static async thumbnail(e){return (await Qt()).thumbnail(e)}static async resize(e,t,r){return (await Qt()).resize(e,t,r)}static async toJpeg(e){return (await Qt()).toJpeg(e)}static async resizeForSticker(e,t,r="default"){return (await Qt()).resizeForSticker(e,t,r)}};var Ne=class n{static defaultMetadata={packageName:"Zaileys Library",authorName:"https://github.com/zeative/zaileys"};static setDefaultMetadata(e){e&&(n.defaultMetadata={...n.defaultMetadata,...e});}static getDefaultMetadata(){return {...n.defaultMetadata}}static async create(e,t){try{let r=await R.toBuffer(e),s=await $(r);if(!s)throw new Error("Unable to detect file type");let i=t?.quality||P.STICKER.DEFAULT_QUALITY,o=q.isAnimated(s.mime),a=t?.shape||"default",d=s.mime==="image/webp"?r:o?await this.processAnimated(r,s.mime,i):await V.resizeForSticker(r,i,a),c=this.createExifMetadata(t),l=new ha__default.default.Image;await l.load(d),l.exif=c;let u=await l.save(null);return Buffer.isBuffer(u)?u:Buffer.from(u)}catch(r){throw new Error(`Sticker creation failed: ${r instanceof Error?r.message:String(r)}`)}}static createExifMetadata(e){let t=e?.pack??e?.packageName??e?.packname??n.defaultMetadata.pack??n.defaultMetadata.packageName??n.defaultMetadata.packname??"Zaileys Library",r=e?.author??e?.authorName??e?.publisher??n.defaultMetadata.author??n.defaultMetadata.authorName??n.defaultMetadata.publisher??"https://github.com/zeative/zaileys",s={"sticker-pack-id":zt(),"sticker-pack-name":t,"sticker-pack-publisher":r,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"},i=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(s),"utf8"),a=Buffer.concat([i,o]);return a.writeUIntLE(o.length,14,4),a}static async processAnimated(e,t,r){let s=P.STICKER.SIZE,i=P.STICKER.FPS,o=`scale=${s}:${s}:force_original_aspect_ratio=decrease,fps=${i},pad=${s}:${s}:(ow-iw)/2:(oh-ih)/2:color=0x00000000,format=rgba`,a=Math.max(1,Math.min(100,r));return Q(e,this.getExtension(t),"webp","Animated sticker processing",async d=>{let c=P.STICKER.MAX_DURATION;try{c=Math.min(await X.duration(d),P.STICKER.MAX_DURATION);}catch{console.warn("Using default duration:",P.STICKER.MAX_DURATION);}let l=Number.isFinite(a)?Math.round(a):60,u=Number.isFinite(c)&&c>0?Math.min(c,P.STICKER.MAX_DURATION):P.STICKER.MAX_DURATION;return ["-vcodec","libwebp","-vf",o,"-q:v",String(l),"-loop","0","-preset","default","-an","-t",String(u),"-compression_level",String(P.STICKER.COMPRESSION_LEVEL)]})}static getExtension(e){return e===P.MIME.GIF?"gif":e.startsWith(P.MIME.VIDEO)?"mp4":"tmp"}};var Xt=class{static async create(e){try{let t=await R.toBuffer(e),r=await $(t);if(!r)throw new Error("Unable to detect file type");let s;return r.mime.startsWith(P.MIME.VIDEO)?s=await X.thumbnail(t):q.isMedia(r.mime)?s=await V.thumbnail(t):s="",{document:t,mimetype:r.mime,ext:r.ext,fileName:zt(),jpegThumbnail:s}}catch(t){throw new Error(`Document creation failed: ${t instanceof Error?t.message:String(t)}`)}}};var ve=class{input;constructor(e){this.input=e;}get audio(){return {toOpus:()=>we.toOpus(this.input),toMp3:()=>we.toMp3(this.input),convert:(e="opus")=>we.convert(this.input,e),waveform:()=>we.waveform(this.input)}}get video(){return {toMp4:()=>X.toMp4(this.input),thumbnail:()=>X.thumbnail(this.input)}}get image(){return {toJpeg:()=>V.toJpeg(this.input),thumbnail:async()=>{let e=await R.toBuffer(this.input);return V.thumbnail(e)},resize:async(e,t)=>{let r=await R.toBuffer(this.input);return V.resize(r,e,t)}}}get sticker(){return {create:e=>Ne.create(this.input,e)}}get document(){return {create:()=>Xt.create(this.input)}}get thumbnail(){return {get:async()=>{let e=await R.toBuffer(this.input),t=await $(e);if(!t||!q.isMedia(t.mime))throw new Error("Invalid media type: expected image or video");return t.mime.startsWith(P.MIME.VIDEO)?X.thumbnail(this.input):V.thumbnail(e)}}}async toBuffer(){return R.toBuffer(this.input)}};var zr=async(n,e)=>{let{buffer:t}=await B(n),r;try{r=await new ve(t).audio.toOpus();}catch(o){throw new p("MEDIA_LOAD_FAILED",`audio() transcode failed: ${o.message}`,{cause:o})}let s=e?.ptt??true,i={audio:r,ptt:s};if(s)try{let{waveform:o,seconds:a}=await new ve(t).audio.waveform();i.waveform=o,e?.seconds===void 0&&(i.seconds=a);}catch{}return e?.seconds!==void 0&&(i.seconds=e.seconds),i};var Yr=10,W="__zaileysRelayMessage",Wn="__zaileysHeaderMedia",rt="__zaileysRequireGroupJid",Zt="__zaileysStatusMedia",oe=n=>typeof n=="string"&&n.length>0,ya=n=>{let e=n.text;if(!oe(e)||e.trim().length===0)throw new p("INVALID_OPTIONS","button text must be a non-empty string");return e},wa=(n,e)=>{let t=n.type??"reply";if(t==="location"){let s=n.text;return {name:"send_location",buttonParamsJson:JSON.stringify(oe(s)?{display_text:s}:{})}}let r=ya(n);if(t==="reply"){let s=n.id;if(!oe(s))throw new p("INVALID_OPTIONS","reply button requires a non-empty id");if(e.has(s))throw new p("INVALID_OPTIONS",`duplicate button id: ${s}`);return e.add(s),{name:"quick_reply",buttonParamsJson:JSON.stringify({display_text:r,id:s})}}if(t==="url"){let s=n.url;if(!oe(s))throw new p("INVALID_OPTIONS","url button requires a non-empty url");let i=n.webview===true;return {name:"cta_url",buttonParamsJson:JSON.stringify({display_text:r,url:s,merchant_url:s,landing_page_url:s,webview_interaction:i})}}if(t==="copy"){let s=n.code;if(!oe(s))throw new p("INVALID_OPTIONS","copy button requires a non-empty code");return {name:"cta_copy",buttonParamsJson:JSON.stringify({display_text:r,id:s,copy_code:s})}}if(t==="call"){let s=n.phone;if(!oe(s))throw new p("INVALID_OPTIONS","call button requires a non-empty phone");return {name:"cta_call",buttonParamsJson:JSON.stringify({display_text:r,id:s,phone_number:s})}}if(t==="reminder"||t==="cancel-reminder"){let s=n.id;return {name:t==="reminder"?"cta_reminder":"cta_cancel_reminder",buttonParamsJson:JSON.stringify({display_text:r,id:oe(s)?s:r})}}if(t==="address"){let s=n.id;return {name:"address_message",buttonParamsJson:JSON.stringify({display_text:r,id:oe(s)?s:r})}}throw new p("INVALID_OPTIONS",`unknown button type: ${String(t)}`)},va=n=>{let e={};if(n?.bottomSheet){let t=n.bottomSheet;e.bottom_sheet={...t.buttonsLimit!==void 0?{in_thread_buttons_limit:t.buttonsLimit}:{},...t.dividers!==void 0?{divider_indices:t.dividers}:{},...t.listTitle!==void 0?{list_title:t.listTitle}:{},...t.buttonTitle!==void 0?{button_title:t.buttonTitle}:{}};}if(n?.limitedTimeOffer){let t=n.limitedTimeOffer;e.limited_time_offer={...t.text!==void 0?{text:t.text}:{},...t.url!==void 0?{url:t.url}:{},...t.copyCode!==void 0?{copy_code:t.copyCode}:{},...t.expiresAt!==void 0?{expiration_time:t.expiresAt}:{}};}return Object.keys(e).length>0?JSON.stringify(e):""},Un=n=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","buttons() requires at least one button");if(n.length>Yr)throw new p("INVALID_OPTIONS",`buttons() accepts at most ${Yr} buttons`);let e=new Set;return n.map(t=>wa(t,e))},en=(n,e)=>{let t=Un(n),r={body:{text:e?.text&&e.text.length>0?e.text:" "},nativeFlowMessage:{buttons:t,messageParamsJson:va(e)}};e?.footer&&e.footer.length>0&&(r.footer={text:e.footer});let s=e?.image?{kind:"image",src:e.image}:e?.video?{kind:"video",src:e.video}:void 0;return (e?.title&&e.title.length>0||e?.subtitle&&e.subtitle.length>0||s)&&(r.header={title:e?.title??"",subtitle:e?.subtitle??"",hasMediaAttachment:s!==void 0}),s!==void 0?{[W]:{interactiveMessage:r},[Wn]:s}:{[W]:{interactiveMessage:r}}};var Qr=10,jn="__zaileysCardsMedia",Xr=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","carousel() requires at least one card");if(n.length>Qr)throw new p("INVALID_OPTIONS",`carousel() accepts at most ${Qr} cards`);let t=[],r=n.map((o,a)=>{let d={body:{text:o.body&&o.body.length>0?o.body:" "}};o.buttons&&o.buttons.length>0&&(d.nativeFlowMessage={buttons:Un(o.buttons),messageParamsJson:""}),o.footer&&o.footer.length>0&&(d.footer={text:o.footer});let c=o.image?{kind:"image",src:o.image}:o.video?{kind:"video",src:o.video}:void 0;return (o.title&&o.title.length>0||o.subtitle&&o.subtitle.length>0||c)&&(d.header={title:o.title??"",subtitle:o.subtitle??"",hasMediaAttachment:c!==void 0}),c&&t.push({...c,index:a}),d}),s={body:{text:e?.text&&e.text.length>0?e.text:" "},carouselMessage:{cards:r}};return t.length>0?{[W]:{interactiveMessage:s},[jn]:t}:{[W]:{interactiveMessage:s}}};var Zr=(n,e,t)=>{let r=new Int32Array(n.length).fill(-1),s=[];for(let i=0;i<n.length;i+=1){if(n[i-1]==="\\")continue;let o=n[i];if(o===e)s.push(i);else if(o===t){let a=s.pop();a!==void 0&&(r[a]=i);}}return r},Sa=n=>{let e=[],t="",r=0,s=1,i=0,o=0,a=[],d=Zr(n,"(",")"),c=Zr(n,"<",">");for(let l=0;l<n.length;l++)if(n[l]==="["&&n[l-1]!=="\\")a.push(l);else if(n[l]==="]"&&(n[l+1]==="("||n[l+1]==="<")){let u=a.pop();if(u==null)continue;let v=n[l+1]==="<",b=(v?c:d)[l+1]??-1;if(b<0)continue;let T=b+1,O=n.slice(u+1,l).trim(),A=n.slice(l+2,T-1).trim(),S,x;if(v){let[F="",z="",xe="",ze="",Oe=""]=O.split("|").map(Ye=>Ye.trim());S=`zaileys_LATEX_${o++}`,x=`{{${S}}}${F||"image"}{{/${S}}}`,e.push({type:"latex",ie:{key:S,text:F,url:A,width:z,height:xe,font_height:ze,padding:Oe}});}else O?(S=`zaileys_HYPERLINK_${i++}`,x=`{{${S}}}${A}{{/${S}}}`,e.push({type:"hyperlink",ie:{key:S,text:O,url:A}})):(S=`zaileys_CITATION_${s-1}`,x=`{{${S}}}${A}{{/${S}}}`,e.push({type:"citation",ie:{key:S,reference_id:String(s++),url:A}}));t+=n.slice(r,u)+x,r=T,l=T-1;}return t+=n.slice(r),{text:t,ie:e}},ba=n=>n.ie.map(({type:e,ie:t})=>e==="hyperlink"?{key:t.key,metadata:{display_name:t.text,is_trusted:true,url:t.url,__typename:"GenAIInlineLinkItem"}}:e==="latex"?{key:t.key,metadata:{latex_expression:t.text,latex_image:{url:t.url,width:Number(t.width)||100,height:Number(t.height)||100},font_height:Number(t.font_height)||83.33333333333333,padding:Number(t.padding)||15,__typename:"GenAILatexItem"}}:{key:t.key,metadata:{reference_id:Number(t.reference_id),reference_url:t.url,reference_title:t.url,reference_display_name:t.url,sources:[],__typename:"GenAISearchCitationItem"}}),es=5e3,ts=200,ns=1e5,Aa=n=>{if(!Array.isArray(n)||n.length===0||!n.every(i=>Array.isArray(i)))throw new p("INVALID_OPTIONS","table must be a non-empty array of string rows");let[e,...t]=n;if(n.length>es)throw new p("INVALID_OPTIONS",`table exceeds ${es} rows`);let r=e.length;for(let i of t)i.length>r&&(r=i.length);if(r>ts)throw new p("INVALID_OPTIONS",`table exceeds ${ts} columns`);if(r*n.length>ns)throw new p("INVALID_OPTIONS",`table exceeds ${ns} cells`);let s=i=>[...i,...Array(r-i.length).fill("")];return [{is_header:true,cells:s(e)},...t.map(i=>({is_header:false,cells:s(i)}))]},Ca={0:"DEFAULT",1:"KEYWORD",2:"METHOD",3:"STR",4:"NUMBER",5:"COMMENT"},tn=new Set(["break","case","catch","continue","debugger","delete","do","else","finally","for","function","if","in","instanceof","new","return","switch","this","throw","try","typeof","var","void","while","with","true","false","null","undefined","class","const","let","super","extends","export","import","from","as","default","yield","static","constructor","async","await","get","set"]),Ea={javascript:tn,js:tn,typescript:tn,ts:tn},Pa=(n,e)=>{let t=Ea[e.toLowerCase()]??new Set,r=[],s=(o,a)=>{if(!o)return;let d=r[r.length-1];d&&d.highlightType===a?d.codeContent+=o:r.push({codeContent:o,highlightType:a});},i=0;for(;i<n.length;){let o=n[i];if(/\s/.test(o)){let a=i;for(;i<n.length&&/\s/.test(n[i]);)i++;s(n.slice(a,i),0);continue}if(o==="/"&&n[i+1]==="/"){let a=i;for(i+=2;i<n.length&&n[i]!==`
|
|
2
|
-
`;)i++;s(n.slice(a,i),5);continue}if(o==='"'||o==="'"||o==="`"){let a=i,d=o;for(i++;i<n.length;)if(n[i]==="\\"&&i+1<n.length)i+=2;else if(n[i]===d){i++;break}else i++;s(n.slice(a,i),3);continue}if(/[0-9]/.test(o)){let a=i;for(;i<n.length&&/[0-9.]/.test(n[i]);)i++;s(n.slice(a,i),4);continue}if(/[a-zA-Z_$]/.test(o)){let a=i;for(;i<n.length&&/[a-zA-Z0-9_$]/.test(n[i]);)i++;let d=n.slice(a,i),c=0;if(t.has(d))c=1;else {let l=i;for(;l<n.length&&/\s/.test(n[l]);)l++;n[l]==="("&&(c=2);}s(d,c);continue}s(o,0),i++;}return r},K=(n,e)=>({view_model:{[Array.isArray(e)?"primitives":"primitive"]:e,__typename:`GenAI${n}LayoutViewModel`}}),
|
|
3
|
-
`)}:null;if(n==="image")return t.length>0?{type:"image",url:t.length===1?t[0]:t}:null;if(n==="video"){if(t.length===0)return null;let r=t.map(o=>
|
|
1
|
+
'use strict';var au=require('baileys'),crypto=require('node:crypto'),Y=require('node:fs/promises'),url=require('node:url'),H=require('node:path'),fs$1=require('node:fs'),os$1=require('node:os'),child_process=require('node:child_process'),jimp=require('jimp'),wa=require('node-webpmux'),lruCache=require('lru-cache');require('node:stream');var Qc=require('qrcode-terminal'),el=require('pino'),events=require('node:events');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var au__default=/*#__PURE__*/_interopDefault(au);var Y__default=/*#__PURE__*/_interopDefault(Y);var H__default=/*#__PURE__*/_interopDefault(H);var wa__default=/*#__PURE__*/_interopDefault(wa);var Qc__default=/*#__PURE__*/_interopDefault(Qc);var el__default=/*#__PURE__*/_interopDefault(el);var Qo=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var p=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysBuilderError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var P={OPUS:{CODEC:"libopus",CHANNELS:1,FREQUENCY:48e3,BITRATE:"48k",FORMAT:"ogg"},THUMBNAIL:{SIZE:100,QUALITY:50,TIMESTAMP:"10%"},STICKER:{SIZE:512,MAX_DURATION:6,FPS:10,DEFAULT_QUALITY:60,COMPRESSION_LEVEL:6},MIME:{AUDIO:"audio/",VIDEO:"video/",IMAGE:"image/",GIF:"image/gif",MP4:"video/mp4"}},Vt="ffmpeg",Or="ffprobe",Cr=false,Er=async(n,e)=>{if(n===void 0||n.length===0)return e;try{if(process.platform==="win32")return await Y__default.default.access(n),n;let t=()=>Y__default.default.access(n,fs$1.constants.X_OK).then(()=>!0,()=>!1);if(await t())return n;let{mode:r}=await Y__default.default.stat(n);return await Y__default.default.chmod(n,r|64),await t()?n:e}catch{return e}},Ht=async(n=false)=>{if(n||Cr)return;Cr=true;let e=process.env.FFMPEG_PATH,t=process.env.FFPROBE_PATH,r;try{r=(await import('@ffmpeg-installer/ffmpeg')).default?.path;}catch{}if(Vt=e??await Er(r,"ffmpeg"),Vt!=="ffmpeg"){let i=H__default.default.dirname(Vt),o=process.platform==="win32"?";":":",a=process.env.PATH??"";a.split(o).includes(i)||(process.env.PATH=`${i}${o}${a}`);}let s;try{s=(await import('@ffprobe-installer/ffprobe')).default?.path;}catch{}Or=t??await Er(s,"ffprobe");},Pr=12e4,kr=3e4,ea=64*1024,ta=3e4,Tr=64*1024*1024,fe={maxConcurrent:4,maxQueued:64,queueTimeoutMs:12e4,maxImagePixels:5e7},Rr=()=>({...fe}),_r=n=>{let e=(t,r,s)=>{if(r!==void 0&&(!Number.isFinite(r)||!Number.isInteger(r)||r<s))throw new Error(`invalid media limit ${t}: ${r}`)};e("maxConcurrent",n.maxConcurrent,1),e("maxQueued",n.maxQueued,0),e("queueTimeoutMs",n.queueTimeoutMs,1),e("maxImagePixels",n.maxImagePixels,1),Object.assign(fe,Object.fromEntries(Object.entries(n).filter(([,t])=>t!==void 0)));},Dn=0,Xe=[],na=async()=>{if(Dn<fe.maxConcurrent)Dn+=1;else {if(Xe.length>=fe.maxQueued)throw new Error(`ffmpeg queue is full (${fe.maxQueued} jobs waiting)`);await new Promise((e,t)=>{let r={grant:()=>{clearTimeout(s),e();}},s=setTimeout(()=>{let i=Xe.indexOf(r);i>=0&&Xe.splice(i,1),t(new Error(`ffmpeg job waited more than ${fe.queueTimeoutMs}ms for a slot`));},fe.queueTimeoutMs);Xe.push(r);});}let n=false;return ()=>{if(n)return;n=true;let e=Xe.shift();e?e.grant():Dn-=1;}},zt=()=>Date.now().toString(36)+crypto.randomBytes(4).toString("hex"),$=async n=>{let{fileTypeFromBuffer:e}=await import('file-type');return e(n)},se=class{static generateUniqueId(){return crypto.randomBytes(12).toString("hex")}static createTempPath(e,t){return H__default.default.join(os$1.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>Y__default.default.unlink(t)));}static async safeReadFile(e){try{return await Y__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await Y__default.default.writeFile(e,t,{flag:"wx",mode:384});}catch{throw new Error(`Failed to write file: ${e}`)}}},R=class{static async toBuffer(e){if(Buffer.isBuffer(e))return e;if(e instanceof ArrayBuffer)return Buffer.from(e);if(typeof e=="string")return this.fromString(e);throw new Error("Invalid input type: expected string, Buffer, or ArrayBuffer")}static async fromString(e){if(e.startsWith("http://")||e.startsWith("https://"))return this.fromUrl(e);try{if(await Y__default.default.stat(e).then(t=>t.isFile()).catch(()=>!1))return await Y__default.default.readFile(e)}catch{}return Buffer.from(e,"base64")}static async fromUrl(e){let t=new AbortController,r=setTimeout(()=>t.abort(),ta);try{let s=await fetch(e,{signal:t.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let i=await s.arrayBuffer(),o=Buffer.from(i);if(o.byteLength>Tr)throw new Error(`Fetched body exceeds ${Tr} bytes`);return o}catch(s){throw new Error(`Failed to fetch URL: ${s instanceof Error?s.message:String(s)}`)}finally{clearTimeout(r);}}static async getExtension(e){let{fileTypeFromBuffer:t}=await import('file-type'),r=await t(e);if(!r)return "tmp";let s=r.ext.toLowerCase();return ["wav","ogg","mp4","gif","jpg","webp","tmp","mp3","png"].includes(s)?s:"tmp"}},q=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(P.MIME.IMAGE)||e.startsWith(P.MIME.VIDEO)}static isAnimated(e){return e===P.MIME.GIF||e.startsWith(P.MIME.VIDEO)}},he=class{static async process(e){await Ht();let t=await na();try{await new Promise((r,s)=>{let i=["-y","-i",e.input,...e.options,e.output],o=child_process.spawn(Vt,i,{stdio:"ignore"}),a=!1,d=l=>{a||(a=!0,clearTimeout(c),l());},c=setTimeout(()=>{o.kill("SIGKILL");let l=new Error(`FFmpeg timed out after ${Pr}ms`);Promise.resolve(e.onError(l)).catch(()=>{}),d(()=>s(l));},Pr);o.on("close",l=>{if(a)return;if(l===0){Promise.resolve(e.onEnd()).then(()=>d(r),f=>d(()=>s(f)));return}let u=new Error(`FFmpeg exited with code ${l}`);Promise.resolve(e.onError(u)).then(()=>d(()=>s(u)),f=>d(()=>s(f)));}),o.on("error",l=>{Promise.resolve(e.onError(l)).finally(()=>d(()=>s(l)));});});}finally{t();}}static async getDuration(e){if(await Ht(),typeof e!="string"||e.length===0||e.startsWith("-"))throw new Error("getDuration expects a local file path");if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))throw new Error("getDuration does not accept protocol inputs");let t=await Y__default.default.stat(e).catch(()=>{});if(t===void 0||!t.isFile())throw new Error(`getDuration: not a readable file: ${e}`);return new Promise((r,s)=>{let i=child_process.spawn(Or,["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),o="",a=false,d=l=>{a||(a=true,clearTimeout(c),l());},c=setTimeout(()=>{i.kill("SIGKILL"),d(()=>s(new Error(`ffprobe timed out after ${kr}ms`)));},kr);i.stdout.on("data",l=>{o.length>ea||(o+=l.toString());}),i.on("close",l=>{d(l===0?()=>r(parseFloat(o.trim())||0):()=>s(new Error(`ffprobe exited with code ${l}`)));}),i.on("error",l=>d(()=>s(l)));})}};var aa=3e4,da=64*1024*1024,Nr="application/octet-stream",Re=async n=>n.byteLength===0?Nr:(await $(n))?.mime??Nr,Ze=async n=>({buffer:n,mime:await Re(n),size:n.byteLength}),ca=async(n,e,t)=>{let r=Number(n.headers?.get?.("content-length")??"0");if(Number.isFinite(r)&&r>t)throw new p("MEDIA_LOAD_FAILED",`${e} exceeds ${t} bytes`);let s=n.body;if(s==null||typeof s.getReader!="function"){let d=Buffer.from(await n.arrayBuffer());if(d.byteLength>t)throw new p("MEDIA_LOAD_FAILED",`${e} exceeds ${t} bytes`);return d}let i=[],o=0,a=s.getReader();for(;;){let{done:d,value:c}=await a.read();if(d)break;if(c!==void 0){if(o+=c.byteLength,o>t)throw await a.cancel().catch(()=>{}),new p("MEDIA_LOAD_FAILED",`${e} exceeds ${t} bytes`);i.push(c);}}return Buffer.concat(i)},Dr=async(n,e,t)=>{let r=new AbortController,s=setTimeout(()=>r.abort(),e);try{let i=await fetch(n,{signal:r.signal});if(!i.ok)throw new p("MEDIA_LOAD_FAILED",`fetch ${n} failed with status ${i.status}`,{cause:i.status});return await ca(i,n,t)}catch(i){throw i instanceof p?i:new p("MEDIA_LOAD_FAILED",`fetch ${n} failed: ${i.message}`,{cause:i})}finally{clearTimeout(s);}},Br=async(n,e)=>{try{if((await Y.stat(n)).size>e)throw new p("MEDIA_LOAD_FAILED",`${n} exceeds ${e} bytes`);return await Y.readFile(n)}catch(t){throw t instanceof p?t:new p("MEDIA_LOAD_FAILED",`read ${n} failed: ${t.message}`,{cause:t})}},la=n=>n.startsWith("http://")||n.startsWith("https://"),ua=[".zaileys"],Fr=(n,e)=>{let t=H.resolve(n);for(let r of e){let s=H.resolve(r);if(t===s||t.startsWith(s+H.sep))throw new p("MEDIA_LOAD_FAILED",`refusing to read ${n}: it resolves inside the protected directory ${r}`)}return t},pa=/^(?:0\.|10\.|127\.|169\.254\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.)/,ma=n=>{let e=n.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e.endsWith(".internal")||e==="::1"||e==="::"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe80:")?true:pa.test(e)},Wr=(n,e)=>{let t;try{t=new URL(n);}catch{throw new p("MEDIA_LOAD_FAILED",`invalid url: ${n}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new p("MEDIA_LOAD_FAILED",`unsupported url scheme: ${t.protocol}`);if(!e&&ma(t.hostname))throw new p("MEDIA_LOAD_FAILED",`refusing to fetch a private address: ${t.hostname}`);return n},et={},Ur=n=>{if(n.maxBytes!==void 0&&(!Number.isInteger(n.maxBytes)||n.maxBytes<1))throw new p("INVALID_OPTIONS",`invalid maxBytes: ${n.maxBytes}`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<1))throw new p("INVALID_OPTIONS",`invalid timeoutMs: ${n.timeoutMs}`);et={...et,...Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0))};},jr=()=>({...et}),B=async(n,e)=>{await Ht();let t={...et,...e,deniedDirs:[...et.deniedDirs??[],...e?.deniedDirs??[]]},r=t.timeoutMs??aa,s=t.maxBytes??da,i=t.allowPrivateNetwork===true,o=[...ua,...t.deniedDirs??[]];if(Buffer.isBuffer(n))return Ze(n);if(n instanceof URL)return n.protocol==="file:"?Ze(await Br(Fr(url.fileURLToPath(n),o),s)):Ze(await Dr(Wr(n.toString(),i),r,s));if(la(n))return Ze(await Dr(Wr(n,i),r,s));if(t.allowLocalPaths===false)throw new p("MEDIA_LOAD_FAILED","local filesystem paths are disabled; pass a URL, a Buffer, or a file: URL");return Ze(await Br(Fr(n,o),s))};var _e=async(n,e)=>{let{buffer:t}=await B(n),r={image:t};return e?.caption!==void 0&&(r.caption=e.caption),e?.viewOnce!==void 0&&(r.viewOnce=e.viewOnce),r};var ye=async(n,e)=>{let{buffer:t,mime:r}=await B(n);if(!r.startsWith("video/"))throw new p("INVALID_OPTIONS",`video() expects a video source, got mime ${r}`);let s={video:t};return e?.caption!==void 0&&(s.caption=e.caption),e?.gifPlayback!==void 0&&(s.gifPlayback=e.gifPlayback),e?.viewOnce!==void 0&&(s.viewOnce=e.viewOnce),e?.ptv===true&&(s.ptv=true),s};var qr=2,$r=30,ga=async n=>{if(n.type==="image")return _e(n.src,n.caption!==void 0?{caption:n.caption}:void 0);if(n.type==="video")return ye(n.src,n.caption!==void 0?{caption:n.caption}:void 0);throw new p("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(n.type)}`)},Kr=async(n,e,t,r)=>{if(!Array.isArray(t)||t.length<qr)throw new p("INVALID_OPTIONS",`album() requires a minimum of ${qr} items`);if(t.length>$r)throw new p("INVALID_OPTIONS",`album() accepts a maximum of ${$r} items`);let s=0,i=0;for(let u of t)if(u.type==="image")s+=1;else if(u.type==="video")i+=1;else throw new p("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(u.type)}`);let o={album:{expectedImageCount:s,expectedVideoCount:i}};r.mentions&&r.mentions.length>0&&(o.mentions=r.mentions),r.mentionAll&&(o.mentionAll=true);let a={};r.quoted&&(a.quoted=r.quoted),r.disappearingSeconds!==void 0&&(a.ephemeralExpiration=r.disappearingSeconds);let d;try{d=await n.sendMessage(e,o,a);}catch(u){throw new p("SEND_FAILED","album parent send rejected",{cause:u})}let c=d?.key;if(!c)throw new p("SEND_FAILED","album parent returned no message key");let l=0;for(let u of t){let f=await ga(u);f.albumParentKey=c;try{await n.sendMessage(e,f);}catch(v){throw new p("SEND_FAILED","album child send rejected",{cause:{parentKey:c,index:l,error:v}})}l+=1;}return c};var Q=async(n,e,t,r,s)=>{let i=r.replace(/[^a-z0-9]+/gi,"_").toLowerCase(),o=se.createTempPath(`${i}_in`,e),a=se.createTempPath(`${i}_out`,t);await se.safeWriteFile(o,n);try{let d=typeof s=="function"?await s(o):s;return await he.process({input:o,output:a,options:d,onEnd:async()=>{},onError:async()=>{}}),await se.safeReadFile(a)}catch(d){throw new Error(`${r} failed: ${d instanceof Error?d.message:String(d)}`)}finally{await se.cleanup([o,a]);}};var Yt=64,Gr=8e3,we=class{static async toOpus(e){return this.convert(e,"opus")}static async toMp3(e){return this.convert(e,"mp3")}static async convert(e,t="opus"){let r=await R.toBuffer(e);q.validate(await $(r),P.MIME.AUDIO);let s=await R.getExtension(r),i=t==="opus"?["-vn","-c:a","libopus","-b:a","48k","-ac","1","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","ogg"]:["-vn","-c:a","libmp3lame","-b:a","128k","-ac","2","-avoid_negative_ts","make_zero","-map_metadata","-1","-f","mp3"];return Q(r,s,t==="opus"?"ogg":"mp3",`${t.toUpperCase()} conversion`,i)}static async waveform(e){let t=await R.toBuffer(e),r=await R.getExtension(t),s=await Q(t,r,"tmp","Waveform generation",["-vn","-ac","1","-ar",String(Gr),"-f","s16le"]),i=Math.floor(s.length/2);return {waveform:this.computeWaveform(s),seconds:Math.max(1,Math.round(i/Gr))}}static computeWaveform(e){let t=Math.floor(e.length/2),r=new Uint8Array(Yt);if(t===0)return r;let s=Math.max(1,Math.floor(t/Yt)),i=[];for(let a=0;a<Yt;a++){let d=0,c=0;for(let l=0;l<s;l++){let u=(a*s+l)*2;u+1<e.length&&(d+=Math.abs(e.readInt16LE(u)),c+=1);}i.push(c>0?d/c:0);}let o=Math.max(...i)||1;for(let a=0;a<Yt;a++)r[a]=Math.floor(i[a]/o*100);return r}};var fa=["-c:v","libx264","-preset","ultrafast","-crf","28","-c:a","aac","-b:a","128k","-movflags","+faststart","-vf","scale=trunc(iw/2)*2:trunc(ih/2)*2","-pix_fmt","yuv420p","-f","mp4"],X=class{static async toMp4(e){let t=await R.toBuffer(e);q.validate(await $(t),P.MIME.VIDEO);let r=await R.getExtension(t);return Q(t,r,"mp4","Video re-encoding",fa)}static async thumbnail(e){let t=await R.toBuffer(e);q.validate(await $(t),P.MIME.VIDEO);let r=await R.getExtension(t),s=P.THUMBNAIL.SIZE;return (await Q(t,r,"jpg","Thumbnail generation",async o=>{let a=await he.getDuration(o);return ["-ss",Math.max(0,a*.1).toString(),"-vframes","1","-s",`${s}x${s}`]})).toString("base64")}static async duration(e){return he.getDuration(e)}};var Le=null,Jr=false;async function ha(){if(Jr)return Le;Jr=true;let n=e=>{typeof e=="function"&&(Le=e);};try{n(Qo("sharp"));}catch{Le=null;}if(!Le)try{let e=await import('sharp');n(e.default??e);}catch{Le=null;}return Le}function Hr(n,e){let t=new Uint8Array(n*n),r=n/2,s=n/2,i=n/10,o=[[i,i],[n-i,i],[i,n-i],[n-i,n-i]];for(let a=0;a<n;a++)for(let d=0;d<n;d++){let c=false;if(e==="circle"){let l=d-r,u=a-s;c=l*l+u*u<=r*r;}else if(e==="rounded"){let l=d>=i&&d<n-i&&a>=0&&a<n,u=d>=0&&d<n&&a>=i&&a<n-i,f=false;for(let v of o){let S=d-v[0],T=a-v[1];if(S*S+T*T<=i*i){f=true;break}}c=l||u||f;}else if(e==="oval"){let l=(d-r)/(n/2),u=(a-s)/(n/3);c=l*l+u*u<=1;}t[a*n+d]=c?255:0;}return t}var Vr=2e4,Wn=(n,e)=>{let t=typeof n=="number"&&Number.isFinite(n)?n:0,r=typeof e=="number"&&Number.isFinite(e)?e:0;if(!(t<=0||r<=0)&&(t>Vr||r>Vr||t*r>Rr().maxImagePixels))throw new Error(`Image too large to decode safely: ${t}x${r}`)},zr=(n,e)=>{if(!Number.isInteger(n)||!Number.isInteger(e)||n<=0||e<=0)throw new Error(`Invalid resize target: ${n}x${e}`);Wn(n,e);},ya=n=>{if(n.length>=24&&n.readUInt32BE(0)===2303741511)return {width:n.readUInt32BE(16),height:n.readUInt32BE(20)};if(n.length>=10&&n.toString("ascii",0,3)==="GIF")return {width:n.readUInt16LE(6),height:n.readUInt16LE(8)};if(n.length>=26&&n.toString("ascii",0,2)==="BM")return {width:n.readInt32LE(18),height:Math.abs(n.readInt32LE(22))};if(n.length>=30&&n.toString("ascii",0,4)==="RIFF"&&n.toString("ascii",8,12)==="WEBP"){let e=n.toString("ascii",12,16);if(e==="VP8X")return {width:1+(n.readUIntLE(24,3)&16777215),height:1+(n.readUIntLE(27,3)&16777215)};if(e==="VP8 "&&n.length>=30)return {width:n.readUInt16LE(26)&16383,height:n.readUInt16LE(28)&16383}}},ie=n=>{let e=ya(n);return e!==void 0&&Wn(e.width,e.height),n},Bn=class{sharp;constructor(e){this.sharp=e;}async thumbnail(e){let t=this.sharp;ie(e);let r=t(e).resize(P.THUMBNAIL.SIZE,P.THUMBNAIL.SIZE,{fit:"cover"});return (await r.metadata()).format==="gif"&&(r=t(e,{pages:1}).resize(P.THUMBNAIL.SIZE,P.THUMBNAIL.SIZE)),(await r.jpeg({quality:P.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}async resize(e,t,r){zr(t,r);let s=this.sharp(ie(e)),i=await s.metadata();return Wn(i.width,i.height),s.resize(t,r,{fit:"cover"}).png().toBuffer()}async toJpeg(e){let t=this.sharp,r=ie(await R.toBuffer(e)),s=await t(r).metadata();if(!s.format)throw new Error("Invalid image type: format could not be determined");return s.format==="webp"||s.format==="png"?t(r).jpeg().toBuffer():r}async resizeForSticker(e,t,r="default"){let s=this.sharp,i=P.STICKER.SIZE,o=s(ie(e)).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}});if(r!=="default"){let a=Buffer.from(Hr(i,r)),d=s(a,{raw:{width:i,height:i,channels:1}});o=o.joinChannel(await d.png().toBuffer());}return o.webp({quality:t}).toBuffer()}},Fn=class{async thumbnail(e){let t=P.THUMBNAIL.SIZE,r=await jimp.Jimp.fromBuffer(ie(e));r.cover({w:t,h:t});let s=await r.getBuffer("image/jpeg",{quality:P.THUMBNAIL.QUALITY});return Buffer.from(s).toString("base64")}async resize(e,t,r){zr(t,r);let s=await jimp.Jimp.fromBuffer(ie(e));s.cover({w:t,h:r});let i=await s.getBuffer("image/png");return Buffer.from(i)}async toJpeg(e){let t=await R.toBuffer(e);try{let s=await(await jimp.Jimp.fromBuffer(ie(t))).getBuffer("image/jpeg");return Buffer.from(s)}catch{return t}}async resizeForSticker(e,t,r="default"){let s=P.STICKER.SIZE,i=await jimp.Jimp.fromBuffer(ie(e));if(i.contain({w:s,h:s}),r!=="default"){let d=Hr(s,r),c=new jimp.Jimp({width:s,height:s,color:255});for(let l=0;l<s;l++)for(let u=0;u<s;u++)d[l*s+u]===255&&c.setPixelColor(4294967295,u,l);i.mask(c);}let o=Buffer.from(await i.getBuffer("image/png")),a=Math.max(1,Math.min(100,t));return Q(o,"png","webp","Jimp WebP conversion",["-vcodec","libwebp","-q:v",`${a}`,"-preset","default"])}},nt=null;async function Qt(){if(nt)return nt;let n=await ha();return n?nt=new Bn(n):(console.warn("\x1B[33m%s\x1B[0m","[media-process] Jimp is slow. For faster performance, run: npm install sharp"),nt=new Fn),nt}var V=class{static async thumbnail(e){return (await Qt()).thumbnail(e)}static async resize(e,t,r){return (await Qt()).resize(e,t,r)}static async toJpeg(e){return (await Qt()).toJpeg(e)}static async resizeForSticker(e,t,r="default"){return (await Qt()).resizeForSticker(e,t,r)}};var Ne=class n{static defaultMetadata={packageName:"Zaileys Library",authorName:"https://github.com/zeative/zaileys"};static setDefaultMetadata(e){e&&(n.defaultMetadata={...n.defaultMetadata,...e});}static getDefaultMetadata(){return {...n.defaultMetadata}}static async create(e,t){try{let r=await R.toBuffer(e),s=await $(r);if(!s)throw new Error("Unable to detect file type");let i=t?.quality||P.STICKER.DEFAULT_QUALITY,o=q.isAnimated(s.mime),a=t?.shape||"default",d=s.mime==="image/webp"?r:o?await this.processAnimated(r,s.mime,i):await V.resizeForSticker(r,i,a),c=this.createExifMetadata(t),l=new wa__default.default.Image;await l.load(d),l.exif=c;let u=await l.save(null);return Buffer.isBuffer(u)?u:Buffer.from(u)}catch(r){throw new Error(`Sticker creation failed: ${r instanceof Error?r.message:String(r)}`)}}static createExifMetadata(e){let t=e?.pack??e?.packageName??e?.packname??n.defaultMetadata.pack??n.defaultMetadata.packageName??n.defaultMetadata.packname??"Zaileys Library",r=e?.author??e?.authorName??e?.publisher??n.defaultMetadata.author??n.defaultMetadata.authorName??n.defaultMetadata.publisher??"https://github.com/zeative/zaileys",s={"sticker-pack-id":zt(),"sticker-pack-name":t,"sticker-pack-publisher":r,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"},i=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(s),"utf8"),a=Buffer.concat([i,o]);return a.writeUIntLE(o.length,14,4),a}static async processAnimated(e,t,r){let s=P.STICKER.SIZE,i=P.STICKER.FPS,o=`scale=${s}:${s}:force_original_aspect_ratio=decrease,fps=${i},pad=${s}:${s}:(ow-iw)/2:(oh-ih)/2:color=0x00000000,format=rgba`,a=Math.max(1,Math.min(100,r));return Q(e,this.getExtension(t),"webp","Animated sticker processing",async d=>{let c=P.STICKER.MAX_DURATION;try{c=Math.min(await X.duration(d),P.STICKER.MAX_DURATION);}catch{console.warn("Using default duration:",P.STICKER.MAX_DURATION);}let l=Number.isFinite(a)?Math.round(a):60,u=Number.isFinite(c)&&c>0?Math.min(c,P.STICKER.MAX_DURATION):P.STICKER.MAX_DURATION;return ["-vcodec","libwebp","-vf",o,"-q:v",String(l),"-loop","0","-preset","default","-an","-t",String(u),"-compression_level",String(P.STICKER.COMPRESSION_LEVEL)]})}static getExtension(e){return e===P.MIME.GIF?"gif":e.startsWith(P.MIME.VIDEO)?"mp4":"tmp"}};var Xt=class{static async create(e){try{let t=await R.toBuffer(e),r=await $(t);if(!r)throw new Error("Unable to detect file type");let s;return r.mime.startsWith(P.MIME.VIDEO)?s=await X.thumbnail(t):q.isMedia(r.mime)?s=await V.thumbnail(t):s="",{document:t,mimetype:r.mime,ext:r.ext,fileName:zt(),jpegThumbnail:s}}catch(t){throw new Error(`Document creation failed: ${t instanceof Error?t.message:String(t)}`)}}};var ve=class{input;constructor(e){this.input=e;}get audio(){return {toOpus:()=>we.toOpus(this.input),toMp3:()=>we.toMp3(this.input),convert:(e="opus")=>we.convert(this.input,e),waveform:()=>we.waveform(this.input)}}get video(){return {toMp4:()=>X.toMp4(this.input),thumbnail:()=>X.thumbnail(this.input)}}get image(){return {toJpeg:()=>V.toJpeg(this.input),thumbnail:async()=>{let e=await R.toBuffer(this.input);return V.thumbnail(e)},resize:async(e,t)=>{let r=await R.toBuffer(this.input);return V.resize(r,e,t)}}}get sticker(){return {create:e=>Ne.create(this.input,e)}}get document(){return {create:()=>Xt.create(this.input)}}get thumbnail(){return {get:async()=>{let e=await R.toBuffer(this.input),t=await $(e);if(!t||!q.isMedia(t.mime))throw new Error("Invalid media type: expected image or video");return t.mime.startsWith(P.MIME.VIDEO)?X.thumbnail(this.input):V.thumbnail(e)}}}async toBuffer(){return R.toBuffer(this.input)}};var Yr=async(n,e)=>{let{buffer:t}=await B(n),r;try{r=await new ve(t).audio.toOpus();}catch(o){throw new p("MEDIA_LOAD_FAILED",`audio() transcode failed: ${o.message}`,{cause:o})}let s=e?.ptt??true,i={audio:r,ptt:s};if(s)try{let{waveform:o,seconds:a}=await new ve(t).audio.waveform();i.waveform=o,e?.seconds===void 0&&(i.seconds=a);}catch{}return e?.seconds!==void 0&&(i.seconds=e.seconds),i};var Qr=10,W="__zaileysRelayMessage",Un="__zaileysHeaderMedia",rt="__zaileysRequireGroupJid",Zt="__zaileysBypassDownload",en="__zaileysStatusMedia",oe=n=>typeof n=="string"&&n.length>0,va=n=>{let e=n.text;if(!oe(e)||e.trim().length===0)throw new p("INVALID_OPTIONS","button text must be a non-empty string");return e},Ma=(n,e)=>{let t=n.type??"reply";if(t==="location"){let s=n.text;return {name:"send_location",buttonParamsJson:JSON.stringify(oe(s)?{display_text:s}:{})}}let r=va(n);if(t==="reply"){let s=n.id;if(!oe(s))throw new p("INVALID_OPTIONS","reply button requires a non-empty id");if(e.has(s))throw new p("INVALID_OPTIONS",`duplicate button id: ${s}`);return e.add(s),{name:"quick_reply",buttonParamsJson:JSON.stringify({display_text:r,id:s})}}if(t==="url"){let s=n.url;if(!oe(s))throw new p("INVALID_OPTIONS","url button requires a non-empty url");let i=n.webview===true;return {name:"cta_url",buttonParamsJson:JSON.stringify({display_text:r,url:s,merchant_url:s,landing_page_url:s,webview_interaction:i})}}if(t==="copy"){let s=n.code;if(!oe(s))throw new p("INVALID_OPTIONS","copy button requires a non-empty code");return {name:"cta_copy",buttonParamsJson:JSON.stringify({display_text:r,id:s,copy_code:s})}}if(t==="call"){let s=n.phone;if(!oe(s))throw new p("INVALID_OPTIONS","call button requires a non-empty phone");return {name:"cta_call",buttonParamsJson:JSON.stringify({display_text:r,id:s,phone_number:s})}}if(t==="reminder"||t==="cancel-reminder"){let s=n.id;return {name:t==="reminder"?"cta_reminder":"cta_cancel_reminder",buttonParamsJson:JSON.stringify({display_text:r,id:oe(s)?s:r})}}if(t==="address"){let s=n.id;return {name:"address_message",buttonParamsJson:JSON.stringify({display_text:r,id:oe(s)?s:r})}}throw new p("INVALID_OPTIONS",`unknown button type: ${String(t)}`)},Sa=n=>{let e={};if(n?.bottomSheet){let t=n.bottomSheet;e.bottom_sheet={...t.buttonsLimit!==void 0?{in_thread_buttons_limit:t.buttonsLimit}:{},...t.dividers!==void 0?{divider_indices:t.dividers}:{},...t.listTitle!==void 0?{list_title:t.listTitle}:{},...t.buttonTitle!==void 0?{button_title:t.buttonTitle}:{}};}if(n?.limitedTimeOffer){let t=n.limitedTimeOffer;e.limited_time_offer={...t.text!==void 0?{text:t.text}:{},...t.url!==void 0?{url:t.url}:{},...t.copyCode!==void 0?{copy_code:t.copyCode}:{},...t.expiresAt!==void 0?{expiration_time:t.expiresAt}:{}};}return Object.keys(e).length>0?JSON.stringify(e):""},jn=n=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","buttons() requires at least one button");if(n.length>Qr)throw new p("INVALID_OPTIONS",`buttons() accepts at most ${Qr} buttons`);let e=new Set;return n.map(t=>Ma(t,e))},tn=(n,e)=>{let t=jn(n),r={body:{text:e?.text&&e.text.length>0?e.text:" "},nativeFlowMessage:{buttons:t,messageParamsJson:Sa(e)}};e?.footer&&e.footer.length>0&&(r.footer={text:e.footer});let s=e?.image?{kind:"image",src:e.image}:e?.video?{kind:"video",src:e.video}:void 0;return (e?.title&&e.title.length>0||e?.subtitle&&e.subtitle.length>0||s)&&(r.header={title:e?.title??"",subtitle:e?.subtitle??"",hasMediaAttachment:s!==void 0}),s!==void 0?{[W]:{interactiveMessage:r},[Un]:s}:{[W]:{interactiveMessage:r}}};var Xr=10,qn="__zaileysCardsMedia",Zr=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","carousel() requires at least one card");if(n.length>Xr)throw new p("INVALID_OPTIONS",`carousel() accepts at most ${Xr} cards`);let t=[],r=n.map((o,a)=>{let d={body:{text:o.body&&o.body.length>0?o.body:" "}};o.buttons&&o.buttons.length>0&&(d.nativeFlowMessage={buttons:jn(o.buttons),messageParamsJson:""}),o.footer&&o.footer.length>0&&(d.footer={text:o.footer});let c=o.image?{kind:"image",src:o.image}:o.video?{kind:"video",src:o.video}:void 0;return (o.title&&o.title.length>0||o.subtitle&&o.subtitle.length>0||c)&&(d.header={title:o.title??"",subtitle:o.subtitle??"",hasMediaAttachment:c!==void 0}),c&&t.push({...c,index:a}),d}),s={body:{text:e?.text&&e.text.length>0?e.text:" "},carouselMessage:{cards:r}};return t.length>0?{[W]:{interactiveMessage:s},[qn]:t}:{[W]:{interactiveMessage:s}}};var es=(n,e,t)=>{let r=new Int32Array(n.length).fill(-1),s=[];for(let i=0;i<n.length;i+=1){if(n[i-1]==="\\")continue;let o=n[i];if(o===e)s.push(i);else if(o===t){let a=s.pop();a!==void 0&&(r[a]=i);}}return r},Aa=n=>{let e=[],t="",r=0,s=1,i=0,o=0,a=[],d=es(n,"(",")"),c=es(n,"<",">");for(let l=0;l<n.length;l++)if(n[l]==="["&&n[l-1]!=="\\")a.push(l);else if(n[l]==="]"&&(n[l+1]==="("||n[l+1]==="<")){let u=a.pop();if(u==null)continue;let v=n[l+1]==="<",S=(v?c:d)[l+1]??-1;if(S<0)continue;let T=S+1,O=n.slice(u+1,l).trim(),A=n.slice(l+2,T-1).trim(),b,x;if(v){let[F="",z="",xe="",ze="",Oe=""]=O.split("|").map(Ye=>Ye.trim());b=`zaileys_LATEX_${o++}`,x=`{{${b}}}${F||"image"}{{/${b}}}`,e.push({type:"latex",ie:{key:b,text:F,url:A,width:z,height:xe,font_height:ze,padding:Oe}});}else O?(b=`zaileys_HYPERLINK_${i++}`,x=`{{${b}}}${A}{{/${b}}}`,e.push({type:"hyperlink",ie:{key:b,text:O,url:A}})):(b=`zaileys_CITATION_${s-1}`,x=`{{${b}}}${A}{{/${b}}}`,e.push({type:"citation",ie:{key:b,reference_id:String(s++),url:A}}));t+=n.slice(r,u)+x,r=T,l=T-1;}return t+=n.slice(r),{text:t,ie:e}},Ca=n=>n.ie.map(({type:e,ie:t})=>e==="hyperlink"?{key:t.key,metadata:{display_name:t.text,is_trusted:true,url:t.url,__typename:"GenAIInlineLinkItem"}}:e==="latex"?{key:t.key,metadata:{latex_expression:t.text,latex_image:{url:t.url,width:Number(t.width)||100,height:Number(t.height)||100},font_height:Number(t.font_height)||83.33333333333333,padding:Number(t.padding)||15,__typename:"GenAILatexItem"}}:{key:t.key,metadata:{reference_id:Number(t.reference_id),reference_url:t.url,reference_title:t.url,reference_display_name:t.url,sources:[],__typename:"GenAISearchCitationItem"}}),ts=5e3,ns=200,rs=1e5,Ea=n=>{if(!Array.isArray(n)||n.length===0||!n.every(i=>Array.isArray(i)))throw new p("INVALID_OPTIONS","table must be a non-empty array of string rows");let[e,...t]=n;if(n.length>ts)throw new p("INVALID_OPTIONS",`table exceeds ${ts} rows`);let r=e.length;for(let i of t)i.length>r&&(r=i.length);if(r>ns)throw new p("INVALID_OPTIONS",`table exceeds ${ns} columns`);if(r*n.length>rs)throw new p("INVALID_OPTIONS",`table exceeds ${rs} cells`);let s=i=>[...i,...Array(r-i.length).fill("")];return [{is_header:true,cells:s(e)},...t.map(i=>({is_header:false,cells:s(i)}))]},Pa={0:"DEFAULT",1:"KEYWORD",2:"METHOD",3:"STR",4:"NUMBER",5:"COMMENT"},nn=new Set(["break","case","catch","continue","debugger","delete","do","else","finally","for","function","if","in","instanceof","new","return","switch","this","throw","try","typeof","var","void","while","with","true","false","null","undefined","class","const","let","super","extends","export","import","from","as","default","yield","static","constructor","async","await","get","set"]),ka={javascript:nn,js:nn,typescript:nn,ts:nn},Ta=(n,e)=>{let t=ka[e.toLowerCase()]??new Set,r=[],s=(o,a)=>{if(!o)return;let d=r[r.length-1];d&&d.highlightType===a?d.codeContent+=o:r.push({codeContent:o,highlightType:a});},i=0;for(;i<n.length;){let o=n[i];if(/\s/.test(o)){let a=i;for(;i<n.length&&/\s/.test(n[i]);)i++;s(n.slice(a,i),0);continue}if(o==="/"&&n[i+1]==="/"){let a=i;for(i+=2;i<n.length&&n[i]!==`
|
|
2
|
+
`;)i++;s(n.slice(a,i),5);continue}if(o==='"'||o==="'"||o==="`"){let a=i,d=o;for(i++;i<n.length;)if(n[i]==="\\"&&i+1<n.length)i+=2;else if(n[i]===d){i++;break}else i++;s(n.slice(a,i),3);continue}if(/[0-9]/.test(o)){let a=i;for(;i<n.length&&/[0-9.]/.test(n[i]);)i++;s(n.slice(a,i),4);continue}if(/[a-zA-Z_$]/.test(o)){let a=i;for(;i<n.length&&/[a-zA-Z0-9_$]/.test(n[i]);)i++;let d=n.slice(a,i),c=0;if(t.has(d))c=1;else {let l=i;for(;l<n.length&&/\s/.test(n[l]);)l++;n[l]==="("&&(c=2);}s(d,c);continue}s(o,0),i++;}return r},K=(n,e)=>({view_model:{[Array.isArray(e)?"primitives":"primitive"]:e,__typename:`GenAI${n}LayoutViewModel`}}),Ia="GenAIaeacdsnwHtmlPrimitive",xa=n=>`<style>html,body{margin:0;height:${n}px;max-height:${n}px;overflow:hidden}</style>`,Oa="https://github.com/zeative/zaileys",rn=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new p("INVALID_OPTIONS","text({ rich: true }) requires non-empty markdown content");let t=[],r=[];for(let o of n)if(o.type==="text"){let a=Aa(o.text),d=Ca(a);r.push({messageType:2,messageText:a.text}),t.push(K("Single",{text:a.text,...d.length>0?{inline_entities:d}:{},__typename:"GenAIMarkdownTextUXPrimitive"}));}else if(o.type==="html"){if(typeof o.html!="string"||o.html.trim().length===0)throw new p("INVALID_OPTIONS","html part requires a non-empty HTML string");t.push(K("Single",{payload:o.height===void 0?o.html:xa(o.height)+o.html,trusted_sources:[],__typename:Ia}));}else if(o.type==="code"){let a=o.language??"plaintext",d=Ta(o.content,a);r.push({messageType:5,codeMetadata:{codeLanguage:a,codeBlocks:d}}),t.push(K("Single",{language:a,code_blocks:d.map(c=>({content:c.codeContent,type:Pa[c.highlightType]})),__typename:"GenAICodeUXPrimitive"}));}else if(o.type==="table"){let a=Ea(o.rows);r.push({messageType:4,tableMetadata:{title:"",rows:a.map(d=>({items:d.cells,...d.is_header?{isHeading:true}:{}}))}}),t.push(K("Single",{rows:a,__typename:"GenATableUXPrimitive"}));}else if(o.type==="image"){let a=Array.isArray(o.url)?o.url:[o.url];if(a.length===0)throw new p("INVALID_OPTIONS","image requires at least one url");r.push({messageType:1,gridImageMetadata:{gridImageUrl:{imagePreviewUrl:a[0]},imageUrls:a.map(d=>({imagePreviewUrl:d,imageHighResUrl:d,sourceUrl:Oa}))}});for(let d of a)t.push(K("Single",{media:{url:d,mime_type:"image/png"},imagine_type:"IMAGE",status:{status:"READY"},__typename:"GenAIImaginePrimitive"}));}else if(o.type==="video"){let a=Array.isArray(o.url)?o.url:[o.url];if(a.length===0)throw new p("INVALID_OPTIONS","video requires at least one url");r.push({messageType:2,messageText:"[ CANNOT_LOAD_VIDEO - zaileys ]"});for(let d of a)t.push(K("Single",{media:{url:d,mime_type:"video/mp4",duration:o.duration??0},imagine_type:"ANIMATE",status:{status:"READY"},__typename:"GenAIImaginePrimitive"}));}else if(o.type==="product"){let a=Array.isArray(o.products),d=a?o.products:[o.products];if(d.length===0)throw new p("INVALID_OPTIONS","product requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_PRODUCT - zaileys ]"});let c=d.map(l=>({title:l.title,brand:l.brand??"",price:l.price??"",sale_price:l.salePrice??"",product_url:l.url??"",image:{url:l.image??""},additional_images:[{url:l.icon??""}],__typename:"GenAIProductItemCardPrimitive"}));t.push(a?K("HScroll",c):K("Single",c[0]));}else if(o.type==="reels"){let a=Array.isArray(o.reels)?o.reels:[o.reels];if(a.length===0)throw new p("INVALID_OPTIONS","reels requires at least one item");r.push({messageType:9,contentItemsMetadata:{contentType:1,itemsMetadata:a.map(d=>({reelItem:{title:d.username??"",profileIconUrl:d.profileUrl??"",thumbnailUrl:d.thumbnail??"",videoUrl:d.url??""}}))}}),t.push(K("HScroll",a.map(d=>({reels_url:d.url??"",thumbnail_url:d.thumbnail??"",creator:d.username??d.title??"",avatar_url:d.profileUrl??"",reels_title:d.title??"",likes_count:d.likes??0,shares_count:d.shares??0,view_count:d.views??0,reel_source:d.source??"IG",is_verified:!!d.verified,__typename:"GenAIReelPrimitive"}))));}else if(o.type==="post"){let a=Array.isArray(o.posts)?o.posts:[o.posts];if(a.length===0)throw new p("INVALID_OPTIONS","post requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_POST - zaileys ]"}),t.push(K("HScroll",a.map(d=>({title:d.title??"",subtitle:d.subtitle??"",username:d.username??"",profile_picture_url:d.profileUrl??"",is_verified:!!d.verified,thumbnail_url:d.thumbnail??"",post_caption:d.caption??"",likes_count:d.likes??0,comments_count:d.comments??0,shares_count:d.shares??0,post_url:d.url??"",post_deeplink:d.deeplink??"",source_app:d.source??"INSTAGRAM",footer_label:d.footer??"",footer_icon:d.icon??"",is_carousel:a.length>1,orientation:d.orientation??"LANDSCAPE",post_type:d.postType??"VIDEO",__typename:"GenAIPostPrimitive"}))));}else if(o.type==="tip")r.push({messageType:2,messageText:o.text}),t.push(K("Single",{text:o.text,__typename:"GenAIMetadataTextPrimitive"}));else {let a=Array.isArray(o.prompts)?o.prompts:[o.prompts];if(a.length===0)throw new p("INVALID_OPTIONS","suggest requires at least one prompt");t.push(K("ActionRow",a.map(d=>({prompt_text:d,prompt_type:"SUGGESTED_PROMPT",__typename:"GenAIFollowUpSuggestionPillPrimitive"}))));}e?.footer&&e.footer.length>0&&t.push(K("Single",{text:e.footer,__typename:"GenAIMetadataTextPrimitive"}));let s=(e?.sources??[]).map(([o,a,d])=>({source_type:"THIRD_PARTY",source_display_name:d??"",source_subtitle:"AI",source_url:a??"",favicon:{url:o??"",mime_type:"image/jpeg",width:16,height:16}})),i={messageContextInfo:{deviceListMetadata:{},deviceListMetadataVersion:2,botMetadata:{messageDisclaimerText:e?.title??"",richResponseSourcesMetadata:{sources:s}}},botForwardedMessage:{message:{richResponseMessage:{messageType:1,submessages:r,unifiedResponse:{data:Buffer.from(JSON.stringify({response_id:crypto.randomUUID(),sections:t})).toString("base64")},contextInfo:{forwardingScore:1,isForwarded:true,forwardedAiBotMessageInfo:{botJid:"0@bot"},forwardOrigin:4}}}}};return {[W]:i}};var Ra={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},ee=class{value;constructor(e){this.value=e;}toString(){return this.value}},ss=n=>n.replace(/[&<>"'`]/g,e=>Ra[e]??e),_a=n=>new ee(n),La=n=>new ee((JSON.stringify(n)??"null").replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")),is=n=>n instanceof ee?n.value:Array.isArray(n)?n.map(is).join(""):n==null||n===false?"":ss(String(n)),Na=(n,...e)=>{let t=n[0]??"";for(let r=0;r<e.length;r++)t+=is(e[r])+(n[r+1]??"");return new ee(t)};var De=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var as=256*1024,Da=4096,os=(n,e,t)=>{if(e!==void 0&&(!Number.isInteger(e)||e<=0||t!==void 0&&e>t)){let r=t===void 0?"a positive integer":`an integer from 1 to ${t}`;throw new p("INVALID_OPTIONS",`htmlApp() ${n} must be ${r}, got ${String(e)}`)}},ds=(n,e={})=>{let t=n instanceof ee?n.value:n;if(typeof t!="string"||t.trim().length===0)throw new p("EMPTY_CONTENT","htmlApp() requires a non-empty HTML string");if(e.fallback!==void 0&&(typeof e.fallback!="string"||e.fallback.trim().length===0))throw new p("INVALID_OPTIONS","htmlApp() fallback must be a non-empty string");os("height",e.height,Da),os("maxBytes",e.maxBytes);let r=e.maxBytes??as,s=Buffer.byteLength(t,"utf8");if(s>r)throw new p("INVALID_OPTIONS",`htmlApp() markup is ${s} bytes, over the ${r} byte limit; raise maxBytes or trim the page`);if(e.device!==void 0&&e.device!=="android"){if(e.fallback===void 0)throw new p("INVALID_RECIPIENT",`htmlApp() renders only on Android, not "${e.device}"; check ctx.senderDevice first or pass fallback`);return De(e.fallback)}let i=rn([{type:"html",html:t,...e.height===void 0?{}:{height:e.height}}],e.title===void 0?void 0:{title:e.title});return e.bypassDownload!==false&&(i[Zt]=true),i};var Ba=/^:::([a-zA-Z]+)\s*$/,Fa=/^:::\s*$/,cs=/^```(\w*)\s*$/,ls=/^!\[[^\]]*\]\(([^)]+)\)\s*$/,Wa=/^[\s|:-]*$/,Ua=n=>Wa.test(n)&&n.includes("--"),sn=n=>n.split("|").map(e=>e.trim()),$n=n=>{let e={};for(let t of sn(n)){let r=t.indexOf(":");if(r===-1)continue;let s=t.slice(0,r).trim().toLowerCase(),i=t.slice(r+1).trim();s.length>0&&(e[s]=i);}return e},Me=n=>{if(n===void 0||n.trim().length===0)return;let e=Number(n);return Number.isNaN(e)?void 0:e},ps=n=>n==="true"||n==="1"||n==="yes",us=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},ja=n=>{let e=$n(n),t=e.title;if(t===void 0||t.length===0)return null;let r={title:t};return e.price&&(r.price=e.price),e.sale&&(r.salePrice=e.sale),e.saleprice&&(r.salePrice=e.saleprice),e.brand&&(r.brand=e.brand),e.url&&(r.url=e.url),e.image&&(r.image=e.image),e.icon&&(r.icon=e.icon),r},qa=n=>{let e=$n(n),t={};e.user&&(t.username=e.user),e.username&&(t.username=e.username),e.title&&(t.title=e.title),e.profile&&(t.profileUrl=e.profile),e.thumb&&(t.thumbnail=e.thumb),e.url&&(t.url=e.url);let r=Me(e.likes);r!==void 0&&(t.likes=r);let s=Me(e.shares);s!==void 0&&(t.shares=s);let i=Me(e.views);return i!==void 0&&(t.views=i),e.source&&(t.source=e.source),"verified"in e&&(t.verified=ps(e.verified)),t},$a=n=>{let e=$n(n),t={};e.user&&(t.username=e.user),e.username&&(t.username=e.username),e.title&&(t.title=e.title),e.subtitle&&(t.subtitle=e.subtitle),e.profile&&(t.profileUrl=e.profile),e.thumb&&(t.thumbnail=e.thumb),e.caption&&(t.caption=e.caption);let r=Me(e.likes);r!==void 0&&(t.likes=r);let s=Me(e.comments);s!==void 0&&(t.comments=s);let i=Me(e.shares);return i!==void 0&&(t.shares=i),e.url&&(t.url=e.url),e.source&&(t.source=e.source),e.footer&&(t.footer=e.footer),e.icon&&(t.icon=e.icon),"verified"in e&&(t.verified=ps(e.verified)),t},Ka=(n,e)=>{let t=e.map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(r=>r.length>0);if(n==="suggest"){let r=t.flatMap(s=>sn(s)).filter(s=>s.length>0);return r.length>0?{type:"suggest",prompts:r}:null}if(n==="tip")return t.length>0?{type:"tip",text:t.join(`
|
|
3
|
+
`)}:null;if(n==="image")return t.length>0?{type:"image",url:t.length===1?t[0]:t}:null;if(n==="video"){if(t.length===0)return null;let r=t.map(o=>sn(o)[0]??"").filter(o=>o.length>0);if(r.length===0)return null;let s=Me(sn(t[0])[1]),i={type:"video",url:r.length===1?r[0]:r};return s!==void 0&&(i.duration=s),i}if(n==="product"){let r=t.map(ja).filter(s=>s!==null);return r.length>0?{type:"product",products:r.length===1?r[0]:r}:null}if(n==="reels"){let r=t.map(qa);return r.length>0?{type:"reels",reels:r}:null}if(n==="post"){let r=t.map($a);return r.length>0?{type:"post",posts:r}:null}return null},ms=n=>{let e=n.replace(/\r\n/g,`
|
|
4
4
|
`).split(`
|
|
5
5
|
`),t=[],r=[],s=()=>{let o=r.join(`
|
|
6
|
-
`).trim();o.length>0&&t.push({type:"text",text:o}),r=[];},i=0;for(;i<e.length;){let o=e[i],a=
|
|
6
|
+
`).trim();o.length>0&&t.push({type:"text",text:o}),r=[];},i=0;for(;i<e.length;){let o=e[i],a=Ba.exec(o);if(a){s();let u=[];for(i++;i<e.length&&!Fa.test(e[i]);)u.push(e[i]),i++;i++;let f=Ka(a[1].toLowerCase(),u);f&&t.push(f);continue}let d=cs.exec(o);if(d){s();let u=[];for(i++;i<e.length&&!cs.test(e[i]);)u.push(e[i]),i++;i++;let f=d[1]&&d[1].length>0?d[1]:void 0;t.push(f?{type:"code",language:f,content:u.join(`
|
|
7
7
|
`)}:{type:"code",content:u.join(`
|
|
8
|
-
`)});continue}let c=e[i+1];if(o.includes("|")&&c!==void 0&&c.includes("|")&&
|
|
8
|
+
`)});continue}let c=e[i+1];if(o.includes("|")&&c!==void 0&&c.includes("|")&&Ua(c)){s();let u=[us(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(us(e[i])),i++;t.push({type:"table",rows:u});continue}let l=ls.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let f=ls.exec(e[i]);if(!f)break;u.push(f[1]),i++;}t.push({type:"image",url:u.length===1?u[0]:u});continue}r.push(o),i++;}return s(),t};var gs=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new p("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var fs=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new p("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await B(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var hs=(n,e)=>{let t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))throw new p("INVALID_OPTIONS",`event() ${e} must be a valid Date or epoch ms`);return new Date(Math.floor(t.getTime()/1e3)*1e3)},ys=n=>{if(n==null||typeof n.name!="string"||n.name.trim().length===0)throw new p("INVALID_OPTIONS","event() requires a non-empty name");return {event:{name:n.name,startDate:hs(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:hs(n.endAt,"endAt")}:{},...n.call!==void 0?{call:n.call}:{},...n.canceled!==void 0?{isCancelled:n.canceled}:{},...n.location!==void 0?{location:{degreesLatitude:n.location.latitude,degreesLongitude:n.location.longitude,...n.location.name!==void 0?{name:n.location.name}:{},...n.location.address!==void 0?{address:n.location.address}:{}}}:{}}}};var ws=n=>{if(n==null||typeof n.jid!="string"||!n.jid.endsWith("@g.us"))throw new p("INVALID_OPTIONS","groupInvite() requires a group jid ending in @g.us");if(typeof n.code!="string"||n.code.trim().length===0)throw new p("INVALID_OPTIONS","groupInvite() requires an invite code");let e={inviteCode:n.code,inviteExpiration:n.expiresAt??Math.floor(Date.now()/1e3)+3*86400,groupJid:n.jid,groupName:n.subject??"",caption:n.caption??""};return n.thumbnail!==void 0&&(e.jpegThumbnail=n.thumbnail),{[W]:{groupInviteMessage:e}}};var Ms=4294967295,Va=/^[0-9a-fA-F]{3}$/,Ha=/^[0-9a-fA-F]{6}$/,za=/^[0-9a-fA-F]{8}$/,Ss={system:0,"system-text":1,"fb-script":2,"system-bold":6,morningbreeze:7,calistoga:8,exo2:9,courierprime:10},Be=n=>{throw new p("INVALID_OPTIONS",n)},Ya=n=>{if(typeof n=="number"){if(!Number.isInteger(n))return Be(`groupStatus() backgroundColor must be an integer, got ${n}`);let t=n<0?Ms+n+1:n;return t<0||t>Ms?Be(`groupStatus() backgroundColor is outside the ARGB range, got ${n}`):t}if(typeof n!="string")return Be("groupStatus() backgroundColor must be a hex string or an integer");let e=n.trim().replace("#","");if(za.test(e))return Number.parseInt(e,16);if(Ha.test(e))return Number.parseInt(`FF${e}`,16);if(Va.test(e)){let t=[...e].map(r=>`${r}${r}`).join("");return Number.parseInt(`FF${t}`,16)}return Be(`groupStatus() backgroundColor must be #RGB, #RRGGBB or #AARRGGBB, got ${n}`)},Qa=n=>{if(typeof n=="number")return !Number.isInteger(n)||n<0?Be(`groupStatus() font must be a non-negative integer, got ${n}`):n;let e=Ss[n];return e===void 0?Be(`groupStatus() font must be one of ${Object.keys(Ss).join(", ")}, got ${String(n)}`):e},As=(n,e)=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","groupStatus() requires a non-empty string");let t={text:n};return e?.backgroundColor!==void 0&&(t.backgroundArgb=Ya(e.backgroundColor)),e?.font!==void 0&&(t.font=Qa(e.font)),Cs({extendedTextMessage:t})},Cs=n=>({[W]:{groupStatusMessageV2:{message:n}},[rt]:"groupStatus()"}),Xa=["conversation","extendedTextMessage"],Za={imageMessage:"image",videoMessage:"video",audioMessage:"audio"},bs=n=>({[W]:{groupStatusMessageV2:{message:{}}},[rt]:"groupStatus()",[en]:n}),ed=["image","video","audio"],td=n=>{let e=n;if(typeof e.message=="function"||e.message!==void 0||e.key!==void 0)return null;for(let t of ed)if(e[t]!==void 0)return {kind:t,src:e[t]};return null},nd=n=>typeof n.message=="function"?n.message():n,rd=(n,e,t)=>{let r=au.proto.Message.decode(au.proto.Message.encode(n).finish());e==="conversation"&&(r.extendedTextMessage={text:r.conversation},delete r.conversation);let s=r.extendedTextMessage;return delete s.viewOnce,s.contextInfo={},t?.caption!==void 0&&(s.text=t.caption),Cs({extendedTextMessage:s})},Es=async(n,e)=>{let t=td(n);if(t!==null){let a=n,{buffer:d}=await B(t.src),c={kind:t.kind,buffer:d},l=e?.caption??a.caption;return t.kind!=="audio"&&l!==void 0&&(c.caption=l),t.kind==="audio"&&a.ptt===true&&(c.ptt=true),bs(c)}let r=nd(n),s=r?.message==null?null:au.normalizeMessageContent(r.message),i=s==null?void 0:au.getContentType(s);if(s==null||i===void 0)throw new p("EMPTY_CONTENT","groupStatus() source has no repostable content");let o=Za[i];if(o!==void 0){let a=s[i]??{},d;try{let{downloadMediaMessage:u}=await import('baileys');d=await u(r,"buffer",{});}catch(u){throw new p("MEDIA_LOAD_FAILED","groupStatus() could not download the source media",{cause:u})}let c={kind:o,buffer:d},l=e?.caption??a.caption;return o!=="audio"&&l!==void 0&&(c.caption=l),o==="audio"&&a.ptt===true&&(c.ptt=true),bs(c)}if(!Xa.includes(i))throw new p("INVALID_OPTIONS",`groupStatus() cannot repost ${i}; supported: text, image, video, audio`);return rd(s,i,e)};var Ps=10,ks=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new p("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new p("INVALID_OPTIONS","list() requires at least one section");let e=0,t=new Set,r=n.sections.map(a=>{if(!Array.isArray(a.rows)||a.rows.length===0)throw new p("INVALID_OPTIONS","each list section requires at least one row");let d=a.rows.map(c=>{if(typeof c.id!="string"||c.id.length===0)throw new p("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof c.title!="string"||c.title.trim().length===0)throw new p("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(c.id))throw new p("INVALID_OPTIONS",`duplicate list row id: ${c.id}`);return t.add(c.id),e+=1,{header:"",title:c.title,description:c.description??"",id:c.id}});return {title:a.title,highlight_label:"",rows:d}});if(e>Ps)throw new p("INVALID_OPTIONS",`list() accepts at most ${Ps} rows total`);let s={name:"single_select",buttonParamsJson:JSON.stringify({title:n.buttonText,sections:r})},i={body:{text:n.description&&n.description.length>0?n.description:" "},nativeFlowMessage:{buttons:[s],messageParamsJson:""}};return n.footerText&&n.footerText.length>0&&(i.footer={text:n.footerText}),n.title&&n.title.length>0&&(i.header={title:n.title,subtitle:"",hasMediaAttachment:false}),{[W]:{interactiveMessage:i}}};var Ts=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new p("INVALID_OPTIONS",`location() latitude must be within -90..90, got ${String(n)}`);if(typeof e!="number"||Number.isNaN(e)||e<-180||e>180)throw new p("INVALID_OPTIONS",`location() longitude must be within -180..180, got ${String(e)}`);let r={degreesLatitude:n,degreesLongitude:e};return t?.name!==void 0&&(r.name=t.name),t?.address!==void 0&&(r.address=t.address),{location:r}};var Is=2,xs=12,Os=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Is)throw new p("INVALID_OPTIONS",`poll() requires a minimum of ${Is} options`);if(e.length>xs)throw new p("INVALID_OPTIONS",`poll() accepts a maximum of ${xs} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new p("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new p("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var Rs=async n=>{if(n==null||typeof n.title!="string"||n.title.trim().length===0)throw new p("INVALID_OPTIONS","product() requires a non-empty title");if(typeof n.businessOwnerId!="string"||n.businessOwnerId.length===0)throw new p("INVALID_OPTIONS","product() requires businessOwnerId");let{buffer:e}=await B(n.image),t={productImage:e,title:n.title};n.productId!==void 0&&(t.productId=n.productId),n.description!==void 0&&(t.description=n.description),n.currency!==void 0&&(t.currencyCode=n.currency),n.price!==void 0&&(t.priceAmount1000=Math.round(n.price*1e3)),n.retailerId!==void 0&&(t.retailerId=n.retailerId),n.url!==void 0&&(t.url=n.url);let r={product:t,businessOwnerJid:n.businessOwnerId};return n.body!==void 0&&(r.body=n.body),n.footer!==void 0&&(r.footer=n.footer),r};var _s=async(n,e)=>{let{buffer:t}=await B(n),r;try{r=await new ve(t).sticker.create(e);}catch(i){throw new p("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var Ls=3,Ns=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new p("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new p("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>Ls)throw new p("INVALID_OPTIONS",`template() accepts at most ${Ls} buttons`);let t={text:`${n.header&&n.header.length>0?`*${n.header}*
|
|
9
9
|
|
|
10
|
-
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),en(n.buttons,t)};var Ns=(n,e,t,r)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{},...r?{inheritDisappearing:r}:{}});var $n=new WeakSet,Ds=n=>{$n.add(n);},Bs=n=>{if(!$n.has(n))return n;$n.delete(n);let e=crypto.randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var sn="status@broadcast",cd=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],ae=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s,i){return new n(e,Ns(t,r,s,i))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=nn(ps(e),t):this.internal.content=De(e),this}htmlApp(e,t){return this.internal.content=as(e,t),this}image(e,t){return this.internal.pendingContent=_e(e,t),this}videoNote(e,t){return this.internal.pendingContent=ye(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=ye(e,t),this}audio(e,t){return this.internal.pendingContent=zr(e,t),this}document(e,t){return this.internal.pendingContent=gs(e,t),this}sticker(e,t){return this.internal.pendingContent=Rs(e,t),this}buttons(e,t){return this.internal.content=en(e,t),this}carousel(e,t){return this.internal.content=Xr(e,t),this}list(e){return this.internal.content=Ps(e),this}poll(e,t,r){return this.internal.content=xs(e,t,r),this}location(e,t,r){return this.internal.content=ks(e,t,r),this}contact(e){return this.internal.content=ms(e),this}template(e){return this.internal.content=Ls(e),this}event(e){return this.internal.content=hs(e),this}groupInvite(e){return this.internal.content=ys(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=bs(e,t):this.internal.pendingContent=Cs(e,t),this}product(e){return this.internal.pendingContent=Os(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new p("INVALID_OPTIONS","reply() requires a quoted message or key");let t="key"in e&&e.key!=null;return this.internal.quoted=t?e:{key:e},this}mentions(e){if(e.length===0)throw new p("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.mentions??[],...e]);return this.internal.mentions=[...t],this}mentionAll(){return this.internal.mentionAll=true,this}audience(e){if(e.length===0)throw new p("INVALID_OPTIONS","audience() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.statusJidList??[],...e]);return this.internal.statusJidList=[...t],this}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new p("INVALID_OPTIONS","disappearing() requires a positive integer duration");return this.internal.disappearingSeconds=e,this}then(e,t){return (async()=>{if(this.internal.resolveRecipient&&(this.internal.recipient=await this.internal.resolveRecipient(this.internal.recipient),delete this.internal.resolveRecipient),this.internal.disappearingSeconds===void 0){let c=this.internal.inheritDisappearing?.(this.internal.recipient);c!==void 0&&c>0&&(this.internal.disappearingSeconds=c);}if(this.internal.statusJidList!==void 0&&this.internal.recipient!==sn)throw new p("INVALID_RECIPIENT",`audience() only applies to ${sn}, not ${this.internal.recipient}`);if(this.internal.albumItems){let c={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(c.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(c.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(c.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(c.disappearingSeconds=this.internal.disappearingSeconds),$r(this.socket,this.internal.recipient,this.internal.albumItems,c)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new p("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[W];if(i!==void 0){let c=s[rt];if(typeof c=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${c} can only be sent to a group jid ending in @g.us`);let l=s[Zt],u=l!==void 0?await this.buildStatusMedia(l):i,f=s[Wn],v=s[jn];return this.sendRelay(u,f,v,l!==void 0)}let o=this.internal.content;if(this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true),this.internal.recipient===sn&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${sn} needs audience([...]); without it WhatsApp accepts the message but shows it to nobody`);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds),this.internal.statusJidList!==void 0&&(a.statusJidList=this.internal.statusJidList);let d;try{d=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(c){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:c})}if(!d?.key)throw new p("SEND_FAILED","socket returned no message key");return d.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await B(t.src),s=await ou.prepareWAMessageMedia({[t.kind]:r},{upload:this.socket.waUploadToServer});e.hasMediaAttachment=true,t.kind==="image"&&s.imageMessage&&(e.imageMessage=s.imageMessage),t.kind==="video"&&s.videoMessage&&(e.videoMessage=s.videoMessage);}async buildStatusMedia(e){let t={[e.kind]:e.buffer};e.caption!==void 0&&(t.caption=e.caption),e.ptt===true&&(t.ptt=true);try{let r=await ou.generateWAMessageContent(t,{upload:this.socket.waUploadToServer});return typeof r.toJSON=="function"?r.toJSON():r}catch(r){throw new p("MEDIA_LOAD_FAILED","groupStatus() media upload failed",{cause:r})}}applyRelayMentions(e){let t=this.internal.mentions,r=this.internal.mentionAll===true;if((t===void 0||t.length===0)&&!r)return;let s=ou.normalizeMessageContent(e),i=s==null?void 0:ou.getContentType(s);if(s==null||i===void 0)return;let o=s[i];if(o==null||typeof o!="object")return;let a=o.contextInfo??{};t!==void 0&&t.length>0&&(a.mentionedJid=t),r&&(a.nonJidMentions=1),o.contextInfo=a;}async sendRelay(e,t,r,s=false){let i=this.socket.relayMessage;if(typeof i!="function")throw new p("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let v=e.interactiveMessage?.header;t!==void 0&&v&&await this.uploadHeaderMedia(v,t);let b=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&b)for(let T of r){let O=b[T.index]?.header;O&&await this.uploadHeaderMedia(O,T);}}catch(v){throw new p("SEND_FAILED","interactive media upload failed",{cause:v})}let o=e;!s&&o.messageContextInfo?.messageSecret==null&&(o.messageContextInfo={...o.messageContextInfo,messageSecret:crypto.randomBytes(32)}),this.applyRelayMentions(e);let d={userJid:this.socket.user?.id??""},c=this.internal.quoted;c!==void 0&&c.message!=null&&(d.quoted=c),this.internal.disappearingSeconds!==void 0&&(d.ephemeralExpiration=this.internal.disappearingSeconds);let l=ou.generateWAMessageFromContent(this.internal.recipient,e,d);if(s&&l.message!=null&&Ds(l.message),typeof l.key?.id!="string")throw new p("SEND_FAILED","failed to generate relay message key");let f="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:l.key.id,additionalNodes:cd}:{messageId:l.key.id};try{await i(this.internal.recipient,l.message,f);}catch(v){throw new p("SEND_FAILED","socket relayMessage rejected",{cause:v})}return this.internal.recordSent?.(l),l.key}};var st=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=De(e),this}image(e,t){return this.pendingContent=_e(e,t),this}video(e,t){return this.pendingContent=ye(e,t),this}then(e,t){return this.send().then(e,t)}async send(){let e=this.key.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new p("EMPTY_CONTENT","edit() requires a content method before await");let t={...this.content,edit:this.key},r;try{r=await this.socket.sendMessage(e,t);}catch(s){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new p("SEND_FAILED","socket returned no message key");return r.key}};var Kn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},Gn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},Jn=async(n,e,t={})=>{let r=Kn(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new p("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},Vn=async(n,e,t)=>{let r=Kn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return Gn(s)},Hn=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new p("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return Gn(i)},on=async(n,e,t,r={})=>{let s=Kn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return Gn(o)};var ld=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,it=n=>ld.test(n),zn=async(n,e,t,r=ud)=>{if(it(e))return e;let s=t.get(e);if(s!==void 0)return s;let i=r.get(e);if(i!==void 0)return i;let o=(async()=>{let d=(await n.onWhatsApp(e))?.find(c=>c.exists&&c.jid);if(!d)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,d.jid),d.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},ud=new Map;var L=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysDomainError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var ot=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new L("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new L("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new L("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var at=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async set(e){let t=this.requireSocket();if(e.lastSeen!==void 0&&await t.updateLastSeenPrivacy(e.lastSeen),e.online!==void 0&&await t.updateOnlinePrivacy(e.online),e.profile!==void 0&&await t.updateProfilePicturePrivacy(e.profile),e.status!==void 0&&await t.updateStatusPrivacy(e.status),e.readReceipts!==void 0){let r=typeof e.readReceipts=="boolean"?e.readReceipts?"all":"none":e.readReceipts;await t.updateReadReceiptsPrivacy(r);}e.groupAdd!==void 0&&await t.updateGroupsAddPrivacy(e.groupAdd),e.call!==void 0&&await t.updateCallPrivacy(e.call);}async get(){return this.requireSocket().fetchPrivacySettings()}async block(e){await this.requireSocket().updateBlockStatus(e,"block");}async unblock(e){await this.requireSocket().updateBlockStatus(e,"unblock");}async blocklist(){return this.requireSocket().fetchBlocklist()}async disappearingMode(e){await this.requireSocket().updateDefaultDisappearingMode(e);}async call(e){await this.requireSocket().updateCallPrivacy(e);}};var dt=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new L("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var ct=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var lt=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Fs=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new L("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},ut=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:true,lastMessages:t},e);}async markUnread(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:false,lastMessages:t},e);}async star(e,t=true){let r=Fs(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async fetchHistory(e,t,r){return Fs(t),this.requireSocket().fetchMessageHistory(e,t,r)}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var pt=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var mt=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var j=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCommandError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var pd=n=>{let e=n[0];return e==="{"||e==="["},md=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},gd=n=>n===" "||n===" "||n===`
|
|
11
|
-
`||n==="\r",fd=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let d=n[a];if(s){t+=d,s=false,i=true,o=false;continue}if(d==="\\"&&r!==null){s=true;continue}if(r!==null){d===r?r=null:t+=d,o=false;continue}if((d==='"'||d==="'")&&o){r=d,i=true,o=false;continue}if(gd(d)){i&&(e.push(t),t="",i=false),o=true;continue}t+=d,i=true,o=false;}return i&&e.push(t),e},hd=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},yd=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function Yn(n,e){let t=hd(n,e);if(t===null)return yd(n);let r=n.slice(t.length),s=fd(r),i={matched:true,args:[],flags:{},json:void 0,raw:n};if(s.length===0)return i.name="",i;i.name=(s[0]??"").toLowerCase();let o=false;for(let a=1;a<s.length;a+=1){let d=s[a];if(d!==void 0){if(d.startsWith("--")){let c=d.slice(2);if(c.length===0){i.args.push(d);continue}let l=c.indexOf("=");if(l!==-1){let f=c.slice(0,l),v=c.slice(l+1);i.flags[f]=v;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[c]=u,a+=1):i.flags[c]=true;continue}if(!o&&pd(d)){let c=md(d);c.ok&&(i.json=c.value,o=true);}i.args.push(d);}}return i}var Ws=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new j("INVALID_COMMAND_NAME","empty command segment in spec");return e},Fe=n=>n.join(" "),Us=n=>[n.name,...n.aliases??[]].join("|"),wd=n=>{let e={};return n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},gt=class{paths=new Map;defs=[];maxDepth=1;register(e,t){let r=typeof e=="string"?e:Us(e);if(r.trim().length===0)throw new j("INVALID_COMMAND_NAME","command spec must not be empty");let s=r.split("|").map(d=>Ws(d)),i=s[0],o=s.slice(1).map(d=>Fe(d)),a={name:Fe(i),aliases:o,parts:i,handler:t,meta:typeof e=="string"?{}:wd(e)};for(let d of s){let c=Fe(d);if(this.paths.has(c))throw new j("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let d of s)this.paths.set(Fe(d),a),d.length>this.maxDepth&&(this.maxDepth=d.length);this.defs.push(a);}resolve(e){if(!e.matched||e.name===void 0||e.name.length===0)return;let t=[e.name.toLowerCase(),...e.args.map(s=>s.toLowerCase())],r=Math.min(this.maxDepth,t.length);for(let s=r;s>=1;s-=1){let i=t.slice(0,s).join(" "),o=this.paths.get(i);if(o!==void 0)return {def:o,args:e.args.slice(s-1)}}}unregister(e){let r=(typeof e=="string"?e:Us(e)).split("|").map(a=>Ws(a)),s=Fe(r[0]),i=this.paths.get(s);if(i===void 0)return;for(let a of [i.parts,...i.aliases.map(d=>d.split(" "))])this.paths.delete(Fe(a));let o=this.defs.indexOf(i);o>=0&&this.defs.splice(o,1),this.maxDepth=this.defs.reduce((a,d)=>Math.max(a,d.parts.length),1);}list(){return [...this.defs]}describe(){return this.defs.map(e=>({name:e.name,aliases:[...e.aliases],...e.meta}))}};async function Qn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new j("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(d){throw s.error=d,s.thrown=true,d}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(d){throw s.thrown||d instanceof j?d:new j("MIDDLEWARE_ERROR","middleware threw during execution",{cause:d})}};await i(0);}var Md=1e4,Sd=3600*1e3,Xn=new lruCache.LRUCache({max:Md,ttl:Sd}),bd=(n,e)=>`${n}\0${e}`,Ad=()=>{Xn.clear();},Zn=async(n,e,t)=>{if((n.group===true||n.admin===true)&&!e.isGroup)return {reason:"group-only"};if(n.private===true&&e.isGroup)return {reason:"private-only"};if(n.admin===true){let s=e.roomId;if(s===null)return {reason:"admin-only"};if(!await t.isAdmin(s,e.senderId))return {reason:"admin-only"}}if(n.cooldown!==void 0&&n.cooldown>0){let s=bd(e.command,e.senderId),i=Xn.get(s),o=t.now(),a=n.cooldown*1e3;if(i!==void 0&&o-i<a)return {reason:"cooldown",retryIn:Math.ceil((a-(o-i))/1e3)};Xn.set(s,o);}return null};function er(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=Yn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0){i.name!==void 0&&i.name.length>0&&n.onNotFound?.(i.name,s);return}let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},d=n.buildContext(a,s);(async()=>{let l=await Zn(o.def.meta,d,{isAdmin:n.isAdmin??(async()=>false),now:()=>Date.now()});if(l!==null){n.onBlocked?.(l,d);return}await Qn(n.middleware,d,()=>o.def.handler(d));})().catch(l=>{let u=l instanceof j?l:new j("HANDLER_ERROR","command handler failed",{cause:l});n.onError?.(u,d)!==true&&n.logger.error(u,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Ue=new Map,qs=n=>n!=null&&typeof n=="object"?n:null,$s=n=>Array.isArray(n.content)?n.content.map(qs).filter(e=>e!==null):[],js=(n,e)=>$s(n).find(t=>t.tag===e),We=n=>typeof n=="string"&&n.length>0?n:void 0,tr=n=>{if(n===void 0)return;let e=Number.parseInt(n,10);return Number.isFinite(e)?e:void 0},Cd=(n,e)=>{if(Object.keys(e).length!==0){if(Ue.size>=64){let t=Ue.keys().next().value;t!==void 0&&Ue.delete(t);}Ue.set(n,e);}},Ks=n=>{let e=qs(n);if(e===null||e.tag!=="call")return false;let t=$s(e).find(b=>b.tag==="offer"),r=We(t?.attrs?.["call-id"]);if(t===void 0||r===void 0)return false;let s={},i=We(e.attrs?.platform),o=We(e.attrs?.version),a=We(e.attrs?.notify),d=We(t.attrs?.caller_country_code),c=We(t.attrs?.caller_pn);i!==void 0&&(s.platform=i),o!==void 0&&(s.appVersion=o),a!==void 0&&(s.name=a),d!==void 0&&(s.countryCode=d),c!==void 0&&(s.phoneJid=c);let l=tr(js(t,"net")?.attrs?.medium);l!==void 0&&(s.networkMedium=l);let u=js(t,"video"),f=tr(u?.attrs?.screen_width),v=tr(u?.attrs?.screen_height);return f!==void 0&&v!==void 0&&(s.screen={width:f,height:v}),Cd(r,s),true},Gs=n=>{let e=Ue.get(n);return e!==void 0&&Ue.delete(n),e};var Js=["text","image","video","audio","document","sticker","reaction","edit","delete","poll-vote","button-click","list-select","mention","mention-all","group-update","group-join","group-leave","member-tag","call-incoming","call-ended","history-sync","limited","presence","newsletter"],Vs=n=>n;var Ed=(n,e)=>{let t=H__default.default.dirname(H__default.default.resolve(n)),r=e===void 0?void 0:H__default.default.resolve(e);if(r!==void 0){let i=H__default.default.relative(r,t);return i.length===0||i.startsWith("..")?void 0:i.split(H__default.default.sep)[0]}let s=H__default.default.basename(t);return s.length>0?s:void 0},Pd=n=>n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),kd=n=>{let e={name:n.name};return n.aliases!==void 0&&(e.aliases=n.aliases),n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},Td=(n,e)=>{let t=n.message;typeof t=="function"&&e.command(kd(n),s=>t(s,e));let r=n;for(let s of Js){let i=r[Pd(s)];typeof i=="function"&&e.on(s,o=>{i(o,e);});}},ft=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t,r){if(typeof e?.name!="string"){this.logger?.warn({file:t},"plugin: invalid shape (needs a name); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let s=[],i=Ed(t,r),o={client:this.host,logger:this.logger,pluginDir:H__default.default.dirname(t),category:i,command:(a,d)=>{let c=typeof a=="string"||a.category!==void 0||i===void 0?a:{...a,category:i};this.host.command(c,d),s.push(()=>this.host.unregisterCommand(c));},use:a=>{this.host.use(a),s.push(()=>{this.host.unuse(a);});},on:(a,d)=>{let c=this.host.on(a,d);return s.push(c),c},once:(a,d)=>{let c=false,l=this.host.on(a,u=>{c||(c=true,l(),d(u));});return s.push(l),l}};try{Td(e,o);let a=await e.setup?.(o);typeof a=="function"&&s.push(a);}catch(a){for(let d of [...s].reverse())try{await d();}catch{}this.logger?.error({err:a,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:s});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Od=/\.(ts|js|mjs|cjs)$/,Rd=/(\.d\.ts$|^_|[/\\]_)/;async function rr(n,e,t){let r;try{r=await fs$1.promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=H__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await rr(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function zs(n,e){try{let r=await import(url.pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"?s:void 0}catch{return}}var ht=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=H__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Od,this.ignore=e.options.ignore??Rd;let t=process.env.NODE_ENV!=="production";this.watchEnabled=e.options.watch??t,this.onError=e.options.onError;}async start(){let e=await rr(this.dir,this.pattern,this.ignore);for(let t of e)await this.loadFile(t);this.watchEnabled&&(process.env.NODE_ENV==="production"&&this.logger?.warn({dir:this.dir},"plugin watch is enabled in production: writes to this directory execute code, and each reload leaks the previous module"),this.startWatch());}async stop(){this.debounce&&clearTimeout(this.debounce),this.watcher?.close(),this.watcher=void 0,await this.flushChain,await this.registry.unloadAll(),this.fileToName.clear();}async loadFile(e){let t=await zs(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e,this.dir);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=fs$1.watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=H__default.default.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await fs$1.promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var N=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysAutomationError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var Ld=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Nd=5e3,Dd=600*1e3,be=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new lruCache.LRUCache({max:Nd,ttl:Dd});constructor(e,t={}){if(!(e.perSec>0))throw new N("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new N("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new N("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??Ld;let r=e.burst??e.perSec;this.global={tokens:r,capacity:r,ratePerMs:e.perSec/1e3,last:this.now()},e.perJidPerSec!==void 0&&(this.perJidRatePerMs=e.perJidPerSec/1e3,this.perJidCapacity=e.perJidPerSec);}async acquire(e){await this.consume(this.global),e!==void 0&&this.perJidRatePerMs!==void 0&&await this.consume(this.bucketFor(e));}bucketFor(e){let t=this.perJid.get(e);if(t)return t;let r=this.perJidCapacity??1,s={tokens:r,capacity:r,ratePerMs:this.perJidRatePerMs??1,last:this.now()};return this.perJid.set(e,s),s}consume(e){if(this.refill(e),e.tokens>=1)return e.tokens-=1,Promise.resolve();let t=(1-e.tokens)/e.ratePerMs;return e.tokens-=1,this.sleep(t)}refill(e){let t=this.now(),r=t-e.last;r>0&&(e.tokens=Math.min(e.capacity,e.tokens+r*e.ratePerMs),e.last=t);}};var Bd={"group.create":6e4,"group.join":3e4,"group.participants":1e4,"group.update":3e3,"community.create":12e4,"community.join":3e4,"community.update":3e3,"newsletter.create":12e4,"newsletter.follow":2e3,"newsletter.update":3e3},Fd=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function sr(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??Fd,i={...Bd,...n.intervalsMs??{}},o=new Map,a=new Map,d=async(c,l)=>{let u=i[c]??0,f=o.get(c);if(f!==void 0&&u>0){let v=u-(r()-f);v>0&&await s(v);}return o.set(c,r()),l()};return {run(c,l){if(!t)return l();let f=(a.get(c)??Promise.resolve()).then(()=>d(c,l),()=>d(c,l));return a.set(c,f.then(()=>{},()=>{})),f}}}var Wd=1e4,Ud=12e4,jd={maxRetries:0,backoffMs:()=>0},qd=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),yt=class{concurrency;retry;sleep;pending=[];maxPending;taskTimeoutMs;active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??jd,this.sleep=t.sleep??qd,this.maxPending=e.maxPending??Wd,this.taskTimeoutMs=e.taskTimeoutMs??Ud;}add(e){return this.pending.length>=this.maxPending?Promise.reject(new N("QUEUE_FULL",`task queue is full (${this.maxPending} pending)`)):new Promise((t,r)=>{this.pending.push({run:()=>this.execute(e).then(t,r)}),this.pump();})}onIdle(){return this.active===0&&this.pending.length===0?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e);})}pump(){for(;this.active<this.concurrency&&this.pending.length>0;){let e=this.pending.shift();if(!e)break;this.active++,e.run().finally(()=>{this.active--,this.pump(),this.settleIdle();});}}settleIdle(){if(this.active===0&&this.pending.length===0&&this.idleWaiters.length>0){let e=this.idleWaiters;this.idleWaiters=[];for(let t of e)t();}}async withDeadline(e){if(this.taskTimeoutMs<=0)return e();let t;try{return await Promise.race([e(),new Promise((r,s)=>{t=setTimeout(()=>s(new N("QUEUE_TIMEOUT",`task exceeded ${this.taskTimeoutMs}ms`)),this.taskTimeoutMs);})])}finally{t!==void 0&&clearTimeout(t);}}async execute(e){let t=0;for(;;)try{return await this.withDeadline(e)}catch(r){if(t>=this.retry.maxRetries)throw r;t+=1,await this.sleep(this.retry.backoffMs(t));}}};var $d=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function ir(n,e,t,r={}){let s={sent:[],failed:[]};if(n.length===0)return s;let i=r.rateLimitPerSec??5,o={};t.now&&(o.now=t.now),t.sleep&&(o.sleep=t.sleep);let a=t.limiter??new be({perSec:i},o),d=r.retry,c=t.sleep?{sleep:t.sleep}:{},l=d?new yt({concurrency:1,retry:d},c):void 0,u=n.length,f=0;for(let v of n){await a.acquire(v);let b=()=>e(t.sendTo(v)).then(()=>{});try{l?await l.add(b):await b(),s.sent.push(v),f+=1,r.onProgress?.(f,u,v,!0);}catch(T){s.failed.push({jid:v,error:$d(T)}),f+=1,r.onProgress?.(f,u,v,false);}}return s}var Gd=1e3,Jd=2e3,Vd=600*1e3,wt=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??Gd,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new lruCache.LRUCache({max:Jd,ttl:Vd});pendingClears=new Set;requireSocket(){let e=this.getSocket();if(!e)throw new N("NOT_CONNECTED","client not connected");return e}throttled(e,t){if(!this.throttleEnabled||this.minIntervalMs<=0)return false;let r=`${e}:${t??"global"}`,s=this.lastSent.get(r),i=this.now();return s!==void 0&&i-s<this.minIntervalMs?true:(this.lastSent.set(r,i),false)}async update(e,t){let r=this.requireSocket();if(!this.throttled(e,t))try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new N("PRESENCE_FAILED",`presence update '${e}' failed`,{cause:s})}}scheduleClear(e,t){if(this.getSocket()===void 0)return;let r=setTimeout(()=>{this.pendingClears.delete(r);try{let s=this.getSocket();if(s===void 0)return;Promise.resolve(s.sendPresenceUpdate("paused",e)).catch(()=>{});}catch{return}},t);typeof r.unref=="function"&&r.unref(),this.pendingClears.add(r);}dispose(){for(let e of this.pendingClears)clearTimeout(e);this.pendingClears.clear(),this.lastSent.clear();}async online(){await this.update("available");}async offline(){await this.update("unavailable");}async typing(e,t){await this.update("composing",e),t!==void 0&&this.scheduleClear(e,t);}async recording(e,t){await this.update("recording",e),t!==void 0&&this.scheduleClear(e,t);}};var Ys=2147483e3,zd=5,Yd=3e4,Qd={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},Xd=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",vt=class{store;sendSnapshot;now;timer;logger;acquire;memory=new Map;timers=new Map;failures=new Map;constructor(e){this.store=e.store,this.sendSnapshot=e.sendSnapshot,this.now=e.now??(()=>Date.now()),this.timer=e.timer??Qd,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new N("SCHEDULE_INVALID","scheduleAt requires a valid Date");let s=await this.evaluate(t),i=crypto.randomUUID(),o={id:i,fireAt:r,recipient:s.recipient,payload:s};return await this.persist(o),this.arm(o),{id:i,cancel:()=>{this.cancel(i);}}}async loadPending(){let e=this.store.listScheduledJobs;if(!e){for(let r of this.memory.values())this.timers.has(r.id)||this.arm(r);return}let t;try{t=await e.call(this.store);}catch(r){this.logger?.warn(r,"scheduler loadPending failed");return}for(let r of t)this.timers.has(r.id)||(this.memory.set(r.id,r),this.arm(r));}dispose(){for(let e of this.timers.values())this.timer.clear(e);this.timers.clear();}cancel(e){let t=this.timers.get(e);t!==void 0&&(this.timer.clear(t),this.timers.delete(e)),this.memory.delete(e),this.remove(e);}arm(e){let t=Math.max(0,e.fireAt-this.now());if(t>Ys){let s=this.timer.set(()=>{this.timers.delete(e.id),this.arm(e);},Ys);this.timers.set(e.id,s);return}let r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),Xd(e.payload)){try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){let r=(this.failures.get(e.id)??0)+1;if(this.failures.set(e.id,r),r>=zd){this.logger?.error({id:e.id,attempts:r},"scheduled send failed repeatedly; dropping the job"),this.failures.delete(e.id),this.memory.delete(e.id),await this.remove(e.id);return}this.logger?.warn(t,"scheduled send failed; re-arming for retry"),e.fireAt=this.now()+Yd*r,this.arm(e);return}this.failures.delete(e.id);}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,d)=>{if(r+=1,r>1)throw new N("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=d?{recipient:o,content:a,options:d}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new N("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=ae.create(s,"");try{await e(i);}catch(o){throw o instanceof N?o:new N("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new N("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function Qs(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((d,c)=>Number(c.messageTimestamp??0)-Number(d.messageTimestamp??0));for(let d=0;d<a.length;d+=1){let c=a[d],l=Number(c.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,f=e.maxPerChat!==void 0&&d>=e.maxPerChat;(u||f)&&(await n.deleteMessage(c.key),r+=1);}}return r}var Mt=class{store;options;logger;now;timer;running=false;warnedUnsupported=false;disabled=false;constructor(e){this.store=e.store,this.options=e.options,this.logger=e.logger,this.now=e.now??Date.now;}get active(){return this.options.maxAgeMs!==void 0||this.options.maxPerChat!==void 0}buildPruneOptions(){let e={};return this.options.maxAgeMs!==void 0&&(e.olderThan=Math.floor((this.now()-this.options.maxAgeMs)/1e3)),this.options.maxPerChat!==void 0&&(e.maxPerChat=this.options.maxPerChat),typeof this.options.chats=="function"&&(e.chatFilter=this.options.chats),e}async runOnce(){if(!this.active||this.disabled)return 0;let e=this.buildPruneOptions();return typeof this.store.pruneMessages=="function"?this.store.pruneMessages(e):typeof this.store.deleteMessage=="function"?Qs(this.store,e):(this.disabled=true,this.warnedUnsupported||(this.warnedUnsupported=true,this.logger?.warn({code:"AUTO_DELETE_UNSUPPORTED"},"autoDelete: store implements neither pruneMessages nor deleteMessage; sweeper disabled")),0)}start(){if(!this.active||this.timer)return;let e=this.options.intervalMs??6e4;this.timer=setInterval(()=>{this.running||(this.running=true,this.runOnce().catch(t=>this.logger?.warn(t,"autoDelete sweep failed")).finally(()=>{this.running=false;}));},e),this.timer.unref?.();}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0);}};var je=n=>typeof n!="string"||n.length===0?null:ou.jidNormalizedUser(n),de=n=>typeof n=="string"&&n.length>0?n:void 0,tc=["@s.whatsapp.net","@c.us"],an=n=>n.endsWith("@lid"),Xs=n=>tc.some(e=>n.endsWith(e)),Z=(n,e)=>{if(!n)return null;let t=de(n.participant)??n.remoteJid,r=je(t);if(r===null)return null;let s=de(n.participantAlt)??de(n.remoteJidAlt),i=s!=null?je(s):null,o=de(n.participantUsername)??de(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let d=i!==null?[r,i]:[r],c=d.find(an),l=d.find(Xs);c!==void 0&&(a.lid=c),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=de(e);return u!==void 0&&(a.pushName=u),a},Zs=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=de(n.participant),r=de(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=Z(s);return o&&(i.sender=o),i},St=n=>{if(!n)return {mentionedJids:[],mentionAll:false};let e=n.mentionedJid,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],r=n.groupMentions,s=Array.isArray(r)&&r.length>0;return {mentionedJids:t,mentionAll:s}};var qe=n=>ou.isJidGroup(n)===true,$e=n=>{if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n.toNumber=="function"){let e=n.toNumber();return Number.isFinite(e)?e:null}return null},m=n=>n!=null&&typeof n=="object"?n:null,ei=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],ti=["groupStatusMessage","groupStatusMessageV2"],ni=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of ei){let o=m(m(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Ke=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of ei){let i=m(m(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var or=(n,e)=>{let t=ou.jidDecode(n),r=ou.jidDecode(e);return t===void 0||r===void 0||!t.user||!r.user?false:t.user===r.user&&t.server===r.server},dn=(n,e)=>{if(n===e)return true;let t=n.includes("@")?n:nc(n);return or(t,e)},Rh=n=>{let t=(n.split("@")[0]??"").split(":")[0]?.replace(/\D/g,"")??"";return n.endsWith("@s.whatsapp.net")||n.endsWith("@c.us")?t:""},nc=n=>`${n.replace(/\D/g,"")}@s.whatsapp.net`;var bt=class{getSocket;options;logger;constructor(e,t,r){this.getSocket=e,this.options=t,this.logger=r;}get enabled(){return this.options.enabled===true}async reject(e,t){let r=this.getSocket();if(!r)throw new N("NOT_CONNECTED","cannot reject a call: client not connected");await r.rejectCall(e,t);}async handle(e){if(this.enabled&&!await this.isAllowed(e.from)){try{await this.reject(e.callId,e.from);}catch(t){this.logger?.warn(t,"autoRejectCall: rejectCall failed");return}try{await this.options.onReject?.(e);}catch(t){this.logger?.warn(t,"autoRejectCall: onReject hook failed");}}}async isAllowed(e){let t=this.options.allow;if(t===void 0)return false;try{return Array.isArray(t)?t.some(r=>dn(r,e)):await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var rc={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},sc=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[rc[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},cn=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=sc(n,e)??"application/octet-stream";return {buffer:s,mime:i,size:s.byteLength}}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media download failed"),r instanceof Error?r:new Error("media download failed")}},si=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys');return await r(n,"stream",{})}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media stream download failed"),r instanceof Error?r:new Error("media stream download failed")}};var oc=new Set([".",",",";",":","!","?"]),ac=n=>{let e=n.length;for(;e>0&&oc.has(n[e-1]);)e-=1;return e===n.length?n:n.slice(0,e)},oi=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(ac):[]},ii=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},ai=n=>(ii(n).toString(16).padStart(8,"0")+ii(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),di=n=>ai(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),ci=(n,e)=>ai(`${n??""}|${e}`),li=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},ui=n=>{let e=ou.jidDecode(n);if(!e)return "unknown";let t=e.device;return t===void 0||t===0?"android":t===2?"ios":t===3?"web":t===4?"desktop":"unknown"},dc=n=>n.trim().endsWith("?"),cc=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),lc=(n,e)=>{if(e.length===0)return false;let t;try{t=ou.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return ou.jidNormalizedUser(r)===t}catch{return r===n}})},uc=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.some(s=>dn(s,e)):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},pc=0,mc=14,gc=1,fc=2,hc=n=>{let e=m(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=m(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof m(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===mc,isDeleted:r===pc,isPinned:s===gc,isUnPinned:s===fc,isBot:m(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:ni(e,ti)}},ar=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&qe(e),r=hc(n.message),s=d=>n.lidMap!=null&&d.endsWith("@lid")?n.lidMap.get(d)??d:d,i=s(n.sender.pn??n.sender.jid),o=t?e?ou.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(ou.jidNormalizedUser(e)):i;return {uniqueId:di(n.key),staticId:ci(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(ou.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderUsername:n.sender.username??null,senderDevice:ui(n.sender.deviceJid??n.sender.jid),timestamp:li(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:oi(n.text),isFromMe:n.key.fromMe===true,verified:n.verified!==false,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isOld:n.isOld===true,isQuestion:dc(n.text),isPrefix:cc(n.text,n.prefixes),isTagMe:lc(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",forwardCount:n.forwardCount??0,ephemeralDuration:n.ephemeralDuration??null,addressingMode:n.addressingMode??"pn",mentionedGroups:n.mentionedGroups??[],...n.ad!==void 0?{ad:n.ad}:{},...n.business!==void 0?{business:n.business}:{},...n.media!==void 0?{media:n.media}:{},citation:uc(n.citationConfig,i),roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,message:()=>n.message,reply:n.reply,react:n.react}};var cr={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},gi=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},M=n=>typeof n=="string"&&n.length>0?n:null,ce=(...n)=>{for(let e of n){let t=M(e);if(t!=null)return t}return null},fi=n=>{let e=m(n.message);if(e==null)return n;let t=Ke(e);return t===e?n:{...n,message:t}},yc=n=>{let t=m(m(m(n.botForwardedMessage)?.message)?.richResponseMessage)??m(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=M(m(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
|
|
12
|
-
`).trim();return i.length>0?i:null},wc=n=>{let e=m(n.templateMessage),t=m(e?.hydratedTemplate)??m(e?.hydratedFourRowTemplate);return M(t?.hydratedContentText)},vc=n=>ce(m(n.pollCreationMessage)?.name,m(n.pollCreationMessageV2)?.name,m(n.pollCreationMessageV3)?.name),Mc=n=>{let e=m(n.locationMessage)??m(n.liveLocationMessage);if(e==null)return null;let t=ce(e.name,e.address);if(t!=null){let i=M(e.name),o=M(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},Sc=n=>{let e=M(m(n.contactMessage)?.displayName);if(e!=null)return e;let t=m(n.contactsArrayMessage),r=M(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>M(m(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},hi=n=>ce(n.conversation,m(n.extendedTextMessage)?.text,yc(n),M(m(m(n.interactiveMessage)?.body)?.text),m(n.buttonsMessage)?.contentText,m(n.listMessage)?.description,wc(n),vc(n),Mc(n),Sc(n)),bc=n=>ce(m(n.buttonsResponseMessage)?.selectedDisplayText,m(n.buttonsResponseMessage)?.selectedButtonId,m(n.templateButtonReplyMessage)?.selectedDisplayText,m(n.templateButtonReplyMessage)?.selectedId,m(n.listResponseMessage)?.title,m(m(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,m(m(n.interactiveResponseMessage)?.body)?.text),Ac=n=>ce(m(n.imageMessage)?.caption,m(n.videoMessage)?.caption,m(n.documentMessage)?.caption,m(n.documentMessage)?.fileName),_=n=>{if(typeof n=="number")return n;let e=$e(n);return typeof e=="number"?e:null},Cc=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],yi=n=>{let e=m(n.pollCreationMessage)??m(n.pollCreationMessageV2)??m(n.pollCreationMessageV3);if(e!=null){let A=Array.isArray(e.options)?e.options:[];return {type:"poll",name:M(e.name),options:A.map(S=>M(m(S)?.optionName)).filter(S=>S!=null),selectableCount:_(e.selectableOptionsCount)??0}}let t=m(n.contactMessage);if(t!=null)return {type:"contact",displayName:M(t.displayName),vcard:M(t.vcard),contacts:[{displayName:M(t.displayName),vcard:M(t.vcard)}]};let r=m(n.contactsArrayMessage);if(r!=null){let A=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:M(r.displayName),vcard:null,contacts:A.map(S=>({displayName:M(m(S)?.displayName),vcard:M(m(S)?.vcard)}))}}let s=m(n.locationMessage);if(s!=null)return {type:"location",latitude:_(s.degreesLatitude),longitude:_(s.degreesLongitude),name:M(s.name),address:M(s.address),accuracy:_(s.accuracyInMeters),speed:_(s.speedInMps),caption:M(s.comment)};let i=m(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:_(i.degreesLatitude),longitude:_(i.degreesLongitude),name:null,address:null,accuracy:_(i.accuracyInMeters),speed:_(i.speedInMps),caption:M(i.caption)};let o=m(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:_(o.expectedImageCount),expectedVideoCount:_(o.expectedVideoCount)};let a=m(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:M(a.groupJid),groupName:M(a.groupName),inviteCode:M(a.inviteCode),caption:M(a.caption),expiresAt:_(a.inviteExpiration)};let d=m(m(n.productMessage)?.product);if(m(n.productMessage)!=null){let A=M(m(n.productMessage)?.businessOwnerJid),S=_(d?.priceAmount1000);return {type:"product",productId:M(d?.productId),title:M(d?.title),description:M(d?.description),price:S!=null?S/1e3:null,currency:M(d?.currencyCode),retailerId:M(d?.retailerId),url:M(d?.url),businessOwnerId:A}}let c=m(n.orderMessage);if(c!=null){let A=_(c.totalAmount1000),S={1:"inquiry",2:"accepted",3:"declined"},x=c.status;return {type:"order",orderId:M(c.orderId),title:M(c.orderTitle),itemCount:_(c.itemCount),total:A!=null?A/1e3:null,currency:M(c.totalCurrencyCode),status:typeof x=="number"?S[x]??null:M(x),message:M(c.message)}}let l=m(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||m(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||m(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let A=m(l.node),S=_(A?.amount1000),x=m(A?.noteMessage);return {type:"payment",kind:l.kind,amount:S!=null?S/1e3:null,currency:M(A?.currencyCodeIso4217),note:ce(x?.conversation,m(x?.extendedTextMessage)?.text),expiresAt:_(A?.expiryTimestamp)}}let u=m(n.eventMessage);if(u!=null){let A=m(u.location);return {type:"event",name:M(u.name),description:M(u.description),location:A!=null?ce(A.name,A.address):null,startTime:_(u.startTime),endTime:_(u.endTime),isCanceled:u.isCanceled===true}}let f=m(n.buttonsMessage);if(f!=null){let A=Array.isArray(f.buttons)?f.buttons:[];return {type:"buttons",contentText:M(f.contentText),footerText:M(f.footerText),buttons:A.map(S=>({id:M(m(S)?.buttonId),text:M(m(m(S)?.buttonText)?.displayText)}))}}let v=m(n.listMessage);if(v!=null){let A=Array.isArray(v.sections)?v.sections:[];return {type:"list",title:M(v.title),description:M(v.description),buttonText:M(v.buttonText),sections:A.map(S=>{let x=Array.isArray(m(S)?.rows)?m(S).rows:[];return {title:M(m(S)?.title),rows:x.map(F=>({id:M(m(F)?.rowId),title:M(m(F)?.title),description:M(m(F)?.description)}))}})}}let b=m(n.interactiveMessage);if(b!=null){let A=m(b.nativeFlowMessage),S=Array.isArray(A?.buttons)?A.buttons:[];return {type:"interactive",title:M(m(b.header)?.title),body:M(m(b.body)?.text),footer:M(m(b.footer)?.text),buttons:S.map(x=>({name:M(m(x)?.name),params:M(m(x)?.buttonParamsJson)}))}}let T=m(n.templateMessage);if(T!=null){let A=m(T.hydratedTemplate)??m(T.hydratedFourRowTemplate),S=Array.isArray(A?.hydratedButtons)?A.hydratedButtons:[];return {type:"template",text:M(A?.hydratedContentText),buttons:S.map(x=>{let F=m(x),z=m(F?.quickReplyButton)??m(F?.urlButton)??m(F?.callButton);return {id:M(z?.id),text:M(z?.displayText)}})}}let O=m(n.extendedTextMessage);if(O!=null){let A=ce(O.canonicalUrl,O.matchedText),S=M(O.title),x=M(O.description);if(A!=null&&(S!=null||x!=null))return {type:"link",url:A,title:S,description:x}}return null};var Ct=n=>{let e=m(n.message);if(e==null)return null;let t=Ke(e);return hi(t)??bc(t)??Ac(t)},Pt=n=>{let e=m(fi(n).message);if(e==null)return null;let t=m(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(e)){if(r==null||typeof r!="object")continue;let s=r.contextInfo;if(s!=null)return s}return null},Ec=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[cr[e]];return r==null||typeof r!="object"?null:r},Pc=n=>{let e=n.message;if(e==null)return false;if(e.viewOnceMessage!=null||e.viewOnceMessageV2!=null||e.viewOnceMessageV2Extension!=null)return true;for(let t of Object.values(cr)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},kc=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,wi=n=>vi(n,Pt(n))??void 0,Tc=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,vi=(n,e)=>{let t=e?.expiration;if(typeof t=="number"&&t>0)return t;let r=m(m(n.message)?.ephemeralMessage),s=m(m(r?.message)?.extendedTextMessage)?.contextInfo,i=m(s)?.expiration;return typeof i=="number"&&i>0?i:null},Ic=n=>{let e=n?.groupMentions;if(!Array.isArray(e))return [];let t=[];for(let r of e){let s=m(r)?.groupJid;typeof s=="string"&&s.length>0&&t.push(s);}return t},Mi=n=>typeof n=="string"&&n.length>0?n:void 0,xc=n=>{let e=m(n?.externalAdReply);if(e==null)return;let t={},r=[["clickId","ctwaClid"],["sourceId","sourceId"],["sourceUrl","sourceUrl"],["sourceApp","sourceApp"],["sourceType","sourceType"],["title","title"],["body","body"],["thumbnailUrl","thumbnailUrl"],["ref","ref"]];for(let[s,i]of r){let o=Mi(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},Oc=n=>{let e=Mi(m(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},Ae=n=>{let e=m(n);if(e==null)return "text";let t=Ke(e);for(let r of Object.values(cr))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of Cc)if(t[r]!=null)return s;return "text"},pi=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},Rc=async(n,e,t,r,s,i)=>{try{if(n==null||n.quotedMessage==null)return null;let o=n.stanzaId;if(typeof o!="string"||o.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let b=await e.resolveQuoted(o,t);if(b!=null&&b.message!=null){let T=Ct(b)??"",O=Ce(b,e,Ae(b.message),T,Et(b,e),s);if(O!==null)return O}}let a=Zs(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let d=a.key.participant,c=qe(t),l=a.sender?.pushName;!c&&(d==null||d.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&pi({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof d=="string"&&(e.selfJid.length>0&&ln(d,e.selfJid)||e.selfLid!=null&&ln(d,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&pi(a.sender,r)&&(r.pn!=null&&(a.key.participant=r.pn),r.lid!=null&&(a.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,f=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),v=Ct(f)??"";return Ce(f,e,Ae(u),v,Et(f,e),s,!1)}catch{return null}},lr=n=>St(Pt(n)).mentionedJids,_c=n=>{try{return ou.jidNormalizedUser(n)}catch{return n}},Si=(n,e)=>n.map(t=>{let r=_c(t);return e.lidMap?.get(r)??r}),mi=n=>(n.split("@")[0]??"").split(":")[0]??"",Lc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[mi(s),mi(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},Ce=(n,e,t,r,s,i,o=true)=>{let a=n.key;if(a==null)return null;let d=Z(a,n.pushName??void 0);if(d===null)return null;let c=gi(a);if(c.length===0)return null;let l=Pt(n),u=qe(c),f=c.endsWith("@broadcast"),v=c.endsWith("@newsletter"),b=l?.isForwarded===true||(l?.forwardingScore??0)>0,T=Pc(n),O=kc(n,l),A=e.channelId??"",S=e.receiverId??"",x=e.prefixes??[],F=i??(()=>u?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(d.pushName??null)),z=e.resolveReceiverName??(()=>Promise.resolve(null)),xe=()=>Rc(l,e,c,d,F,a.fromMe===true),ze=c.length>0?c:d.pn??d.jid,Oe=(k,D)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(ze,k,D,n),Ye=k=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(a,k),Ln=Si(St(l).mentionedJids,e),I=Lc(r,e.lidMap),Qe=xc(l),y=Oc(n),w={message:n,key:a,channelId:A,receiverId:S,selfJid:e.selfJid,text:I,chatType:t,sender:d,mentions:Ln,isViewOnce:T,isEphemeral:O,isForwarded:b,isBroadcast:f,isNewsletter:v,isOld:e.isOld===true,prefixes:x,forwardCount:Tc(l?.forwardingScore,0),ephemeralDuration:vi(n,l),addressingMode:a.addressingMode==="lid"?"lid":"pn",mentionedGroups:Ic(l),...Qe!==void 0?{ad:Qe}:{},...y!==void 0?{business:y}:{},...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:F,resolveReceiverName:z,resolveReplied:xe,reply:Oe,react:Ye},E={...s!==void 0?{...w,media:s}:w,verified:o};return ar(e.citationConfig!==void 0?{...E,citationConfig:e.citationConfig}:E)},Nc=["image","video","audio","document","sticker"],bi=(n,e,t)=>{let r=fi(n),s=Ec(r,e);if(s===null)return null;let i=cn(r,e,t.logger),o=si(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:_(s.fileLength),ptt:s.ptt===true,isAnimated:s.isAnimated===true||s.gifPlayback===true,duration:_(s.seconds),width:_(s.width),height:_(s.height),pages:_(s.pageCount),thumbnail:s.jpegThumbnail!=null?Buffer.from(s.jpegThumbnail):null,buffer:async()=>(await i()).buffer,stream:o}},Et=(n,e)=>{let t=m(n.message);if(t==null)return;let r=Ae(n.message);return Nc.includes(r)?bi(n,r,e)??void 0:yi(Ke(t))??void 0},Ai=(n,e)=>{if(m(n.message)==null)return null;let r=Ae(n.message),s=Et(n,e),i=Ct(n)??"";return i===""&&s===void 0?null:Ce(n,e,r,i,s)},Ci=(n,e)=>{let t=m(n.message);if(t==null)return null;let r=Ke(t),s=hi(r),i=yi(r)??void 0;return s===null&&i===void 0?null:Ce(n,e,Ae(n.message),s??"",i)},kt=(n,e,t)=>{let r=bi(e,n,t);return r===null?null:Ce(e,t,n,r.caption??"",r)},Ei=(n,e)=>kt("image",n,e),Pi=(n,e)=>kt("video",n,e),ki=(n,e)=>kt("audio",n,e),Ti=(n,e)=>kt("document",n,e),Ii=(n,e)=>kt("sticker",n,e),ln=(n,e)=>{try{return ou.jidNormalizedUser(n)===ou.jidNormalizedUser(e)}catch{return n===e}},xi=(n,e)=>{if(n.key==null)return null;let r=Pt(n),s=St(r).mentionedJids;if(s.length===0)return null;let i=Si(s,e);if(!(i.some(u=>ln(u,e.selfJid))||e.selfLid!=null&&s.some(u=>ln(u,e.selfLid)))||m(n.message)==null)return null;let d=Ct(n)??"",c=Et(n,e),l=Ce(n,e,Ae(n.message),d,c);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},Oi=(n,e)=>{let t=n.key;if(t==null)return null;let r=gi(t);if(r.length===0||!qe(r))return null;let{mentionAll:s}=St(Pt(n));if(!s||m(n.message)==null)return null;let o=Ct(n)??"",a=Et(n,e),d=Ce(n,e,Ae(n.message),o,a);return d===null?null:{...d,isMentionAll:true,selfJid:e.selfJid}};var Ee="[zaileys]",Dc="The saved session looks invalid or corrupted (connection keeps closing before it authenticates). Delete the auth folder (default: ./.zaileys) and run again to scan a fresh QR / request a new pairing code.";function _i(n){switch(n.kind){case "connecting":return `${Ee} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${Ee} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${Ee} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${Ee} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${Ee} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
|
|
13
|
-
${Ee} ${
|
|
14
|
-
`);}var Ge={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function $i(n,e){let t=n?.enabled??Ge.enabled,r=n?.maxAttempts??Ge.maxAttempts,s=n?.initialDelayMs??Ge.initialDelayMs,i=n?.maxDelayMs??Ge.maxDelayMs,o=n?.jitterFactor??Ge.jitterFactor,a=n?.rateLimitedDelayMs??Ge.rateLimitedDelayMs,d=e?.random??Math.random,c=0;return {next:f=>{if(!t||xt(f))return null;let v=c+1;if(v>r)return null;if(c=v,un(f))return {attempt:v,delayMs:a};let b=Math.pow(2,v-1),T=Math.min(i,s*b),O=1+(d()*2-1)*o,A=T*O,S=Math.min(i,Math.max(0,A));return {attempt:v,delayMs:Math.round(S)}},reset:()=>{c=0;},get attempts(){return c}}}var Xc={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function Ki(n="idle"){let e=n,t=new Set,r=s=>Xc[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var mn=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,gn=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=mn(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(mn(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...d)=>{let l=d[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let u=this.messages.get(mn(l.key));if(u){let f={...u,...l.update};this.saveMessage(f).catch(()=>{});}}},s=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveChat(l).catch(()=>{});},i=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let f={...this.chats.get(l.id)??{},...l};this.saveChat(f).catch(()=>{});}},o=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveContact(l).catch(()=>{});},a=(...d)=>{let c=d[0];if(c?.presences)for(let l of Object.keys(c.presences)){let u=c.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[d,c]of this.listeners)e.ev.on(d,c);}async deleteMessage(e){this.assertOpen();let t=mn(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let d=this.messages.get(a);d&&i.push(d);}i.sort((a,d)=>Number(d.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,d)=>{let c=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&c<e.olderThan||e.maxPerChat!==void 0&&d>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}async reopen(){this.closed=false;}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","MemoryMessageStore is closed")}};var el=["silent","fatal","error","warn","info","debug","trace"];function tl(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":el.includes(e)?e:"silent"}var nl=["creds","*.creds","noiseKey","*.noiseKey","signedIdentityKey","*.signedIdentityKey","signedPreKey","*.signedPreKey","pairingEphemeralKeyPair","*.pairingEphemeralKeyPair","accessToken","*.accessToken","appSecret","*.appSecret","verifyToken","*.verifyToken","password","*.password","authorization","*.authorization","headers.authorization","headers.Authorization"];function rl(n={}){let e=tl(n.level),t=Zc__default.default({level:e,redact:{paths:[...nl],censor:"[redacted]"}});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Gi=["debug","info","warn","error","fatal"];function sl(n){if(n===null||typeof n!="object")return false;for(let e of Gi)if(typeof n[e]!="function")return false;return true}function Ot(){}function il(n){let e={debug:Ot,info:Ot,warn:Ot,error:Ot,fatal:Ot};for(let t of Gi){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function pr(n,e){return n===void 0?e??rl():sl(n)?n:il(n)}var Ji=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),fn,al=()=>{if(fn!==void 0)return fn;let n=ou.proto?.Message?.ProtocolMessage?.Type;return fn=new Set(Ji.map(e=>n?.[e]).filter(e=>typeof e=="number")),fn},dl=n=>{let r=n.message?.protocolMessage?.type;return typeof r=="number"||typeof r=="string"?r:void 0},cl=n=>{let e=dl(n);return e===void 0?false:typeof e=="string"?Ji.includes(e):al().has(e)},ll=n=>{let e=n.messageStubParameters;return Array.isArray(e)?e.some(t=>typeof t=="string"&&t.startsWith("requestId:")):false},Vi=n=>{if(n.requestId!=null)return {...n,messages:[]};let e=n.messages.filter(t=>{let r=t.key?.fromMe===true;return !(r&&ll(t)||!r&&cl(t))});return {...n,messages:e}};var ul=new Set(["offer","ringing"]),pl=new Set(["timeout","reject","accept","terminate"]),Hi=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},zi=n=>{if(typeof n.id!="string"||n.id.length===0||!ul.has(n.status))return null;let e=Gs(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Hi(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},Yi=n=>typeof n.id!="string"||n.id.length===0||!pl.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Hi(n.date),status:n.status};var G=n=>typeof n=="string"&&n.length>0,ml=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},Qi=(n,e,t)=>n.filter(r=>G(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return G(i)&&(s.participantAlt=i),G(e)&&(s.authorPn=e),G(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),Xi=n=>G(n?.id)?{groupId:n.id,update:ml(n),timestamp:Date.now()}:null,Zi=n=>{if(!G(n?.groupId)||!G(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return G(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},gl=new Set(["add","invite","invite-link"]),fl=new Set(["remove","leave"]),eo=n=>{if(!G(n?.id)||!gl.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Qi(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return G(n.author)&&(t.by=n.author),t},to=n=>{if(!G(n?.id)||!fl.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Qi(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return G(n.author)&&(t.by=n.author),t};var hl=["quick_reply","cta_url","cta_call","button_click"],yl=["list_select","single_select"],ne=n=>typeof n=="string"&&n.length>0,ro=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return Z(n.key,e)},so=n=>$e(n.messageTimestamp)??0,io=(n,e)=>{if(!ne(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},hn=(n,e)=>{for(let t of e){let r=n[t];if(ne(r))return r}},oo=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&ne(r.selectedButtonId))return mr(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&ne(s.selectedId))return mr(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&ne(i.name)&&hl.includes(i.name)){let o=io(i.paramsJson,e.logger);if(!o)return null;let a=hn(o,["id","button_id"]);return a===void 0?null:mr(n,a,hn(o,["display_text"])??null)}return null},mr=(n,e,t)=>{let r=ro(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:so(n)};return ne(t)&&(s.buttonText=t),s},ao=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(ne(s))return no(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&ne(i.name)&&yl.includes(i.name)){let o=io(i.paramsJson,e.logger);if(!o)return null;let a=hn(o,["row_id","id"]);return a===void 0?null:no(n,a,hn(o,["title"])??null)}return null},no=(n,e,t)=>{let r=ro(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:so(n)};return ne(t)&&(s.title=t),s};var wl=new Set(["available","unavailable","composing","recording","paused"]),vl=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,co=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},gr=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:vl(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},lo=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!wl.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Rt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var ke=(n,e)=>{let t=$e(n);return t===null?e:t},Sl=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(d=>d?.messageText).filter(d=>typeof d=="string"&&d.length>0);if(a.length>0)return a.join(`
|
|
15
|
-
`)}return ""},bl=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],po=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=Z(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:ke(t.senderTimestampMs,0)}},mo=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==ou.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=Z(n.key,e.pushName);return s===null?null:{key:r,newContent:Sl(t.editedMessage),editedAt:ke(n.update.messageTimestamp,0),sender:s}},go=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==ou.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=Z(n.key,e.pushName);if(s===null)return null;let i=je(n.key.remoteJid),o=je(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:ke(n.update.messageTimestamp,0)}},Al=async(n,e,t)=>{if(e.length===0||t.resolvePoll==null)return [];let r=n.id,s=n.remoteJid;if(typeof r!="string"||typeof s!="string")return [];let o=(await t.resolvePoll(r,s))?.message,a=o?.pollCreationMessage?.options??o?.pollCreationMessageV2?.options??o?.pollCreationMessageV3?.options??[],d=new Map;for(let l of a){let u=l?.optionName??"";d.set(crypto.createHash("sha256").update(Buffer.from(u)).digest("hex").toUpperCase(),u);}let c=[];for(let l of e){let u=d.get(l.toUpperCase());u!==void 0&&c.push(u);}return c},fo=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=Z(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;if(!i)return null;let o=bl(t.vote?.selectedOptions);return {pollKey:i,selectedOptions:o,voter:s,timestamp:ke(t.senderTimestampMs,ke(n.update.messageTimestamp,0)),options:()=>Al(i,o,e)}}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:ke(r.senderTimestampMs,ke(n.update.messageTimestamp,0)),options:()=>Promise.resolve([])}:null}return null};var yn=n=>Array.isArray(n)?n:[],Cl=3e3,El=128,wo=8,Pl=256,kl=2e4,Tl=1e4,Il=2e3,xl=600*1e3,Ol=500,Rl=300*1e3,_l=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Ll=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function fr(n,e,t){let r=[],s=new lruCache.LRUCache({max:Ol,ttl:Rl}),i=t.groupMetadata!=null?y=>{let w=s.get(y);if(w!==void 0)return w;let h=t.groupMetadata;if(h==null)return Promise.resolve(null);let E=h(y).then(k=>k?.subject??null).catch(()=>(s.delete(y),null));return s.set(y,E),E}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},d={selfJid:t.selfJid,...t.resolveQuoted!=null?{resolvePoll:t.resolveQuoted}:{}},c=(y,w)=>{let h=(...E)=>{try{w(E[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,h),r.push(()=>e.ev.off(y,h));},l=(y,w)=>{I(()=>Ai(y,w),h=>n.emit("message",h)),I(()=>Ci(y,w),h=>n.emit("text",h)),I(()=>Ei(y,w),h=>n.emit("image",h)),I(()=>Pi(y,w),h=>n.emit("video",h)),I(()=>ki(y,w),h=>n.emit("audio",h)),I(()=>Ti(y,w),h=>n.emit("document",h)),I(()=>Ii(y,w),h=>n.emit("sticker",h)),I(()=>xi(y,w),h=>n.emit("mention",h)),I(()=>Oi(y,w),h=>n.emit("mention-all",h)),I(()=>oo(y,a),h=>n.emit("button-click",h)),I(()=>ao(y,a),h=>n.emit("list-select",h));},u=y=>{if(typeof y!="string"||y.length===0)return null;let w;try{w=ou.jidNormalizedUser(y);}catch{w=y;}return an(w)?w:null},f=new lruCache.LRUCache({max:Il,ttl:xl}),v=(y,w=false)=>{let h=new Set,E=[y.key?.participant,y.key?.remoteJid,t.selfJid];for(let k of w?E:[...E,...lr(y)]){let D=u(k);if(D!=null&&h.add(D),h.size>=El)break}return [...h]},b=new Map,T=(y,w)=>{let h=b.get(w);if(h!==void 0)return h;let E=(async()=>{try{let k=await _l(Promise.resolve(y(w)),Cl);if(k==null||k.length===0)return null;let D=k;try{D=ou.jidNormalizedUser(k);}catch{D=k;}return f.set(w,D),D}catch(k){return t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw"),null}finally{b.delete(w);}})();return b.set(w,E),E},O=t.maxPendingResolutions??Pl,A=t.maxQueuedResolutions??kl,S=0,x=0,F=[],z=0,xe=0,ze=y=>{let w=y.message,h=w?.conversation,E=w?.extendedTextMessage,k=typeof h=="string"?h:typeof E=="object"&&typeof E?.text=="string"?E.text:"";return 1+Math.floor(lr(y).length/32)+Math.floor(k.length/8192)},Oe=y=>{let w=new Map;for(let h of y){let E=f.get(h);if(E===void 0)return;w.set(h,E);}return w},Ye=(y,w)=>{let h=k=>{S+=1,w(k).finally(()=>{S-=1;let D=F.shift();D!==void 0&&(x-=D.weight,D.start());});};if(S<O){h(false);return}if(x+y<=A){x+=y,F.push({weight:y,start:()=>h(true)});return}z+=1;let E=Date.now();E-xe>=Tl&&(t.logger?.warn({shed:z,pending:S,queuedWeight:x},"inbound pipeline: overloaded, shed messages waiting on LID resolution"),z=0,xe=E);},Ln=async y=>{let w=t.resolveLidToPn;if(w==null||y.length===0)return;let h=new Map,E=[];for(let k of y){let D=f.get(k);D!==void 0?h.set(k,D):E.push(k);}for(let k=0;k<E.length;k+=wo){let D=E.slice(k,k+wo);await Promise.all(D.map(async Jt=>{let ge=await T(w,Jt);ge!==null&&h.set(Jt,ge);}));}return h.size>0?h:void 0},I=(y,w)=>{let h;try{h=y();}catch(E){t.logger?.warn(E,"inbound pipeline: decoder threw");return}h!=null&&w(h);};c("messages.upsert",y=>{let w=Vi(y),h=w.type==="append"?{...o,isOld:!0}:o;for(let E of w.messages){if(t.ignoreMe===!0&&E.key?.fromMe===!0)continue;let k=t.resolveLidToPn!=null?v(E):[];if(k.length===0){l(E,h);continue}let D=Oe(k)??(S>=O?Oe(v(E,!0)):void 0);if(D!==void 0){l(E,{...h,lidMap:D});continue}Ye(ze(E),Jt=>Ln(Jt?v(E,!0):k).then(ge=>l(E,ge!=null?{...h,lidMap:ge}:h)).catch(ge=>{t.logger?.warn(ge,"inbound pipeline: deferred lid resolve emit failed");}));}}),c("messages.update",y=>{for(let w of yn(y))I(()=>mo(w,d),h=>n.emit("edit",h)),I(()=>go(w,d),h=>n.emit("delete",h)),I(()=>fo(w,d),h=>n.emit("poll-vote",h));}),c("messages.reaction",y=>{for(let w of yn(y))I(()=>po(w,d),h=>n.emit("reaction",h));}),c("groups.update",y=>{for(let w of yn(y))I(()=>Xi(w),h=>n.emit("group-update",h));}),c("group-participants.update",y=>{let w=y;I(()=>eo(w),h=>n.emit("group-join",h)),I(()=>to(w),h=>n.emit("group-leave",h));}),c("group.member-tag.update",y=>{I(()=>Zi(y),w=>n.emit("member-tag",w));}),c("call",y=>{for(let w of yn(y))I(()=>zi(w),h=>n.emit("call-incoming",h)),I(()=>Yi(w),h=>n.emit("call-ended",h));}),c("messaging-history.status",y=>{I(()=>co(y),w=>n.emit("history-sync",w));}),c("presence.update",y=>{let w=(()=>{try{return lo(y)}catch(h){return t.logger?.warn(h,"inbound pipeline: decodePresence threw"),[]}})();for(let h of w)n.emit("presence",h);}),c("connection.update",y=>{let w=Ll(y);w!==null&&I(()=>gr({source:"connection-update",reachoutTimeLock:w}),h=>n.emit("limited",h));}),c("message-capping.update",y=>{I(()=>gr({source:"message-capping",capInfo:y}),w=>n.emit("limited",w));}),c("newsletter.reaction",y=>{I(()=>Rt({source:"reaction",payload:y}),w=>n.emit("newsletter",w));}),c("newsletter.view",y=>{I(()=>Rt({source:"view",payload:y}),w=>n.emit("newsletter",w));}),c("newsletter-participants.update",y=>{I(()=>Rt({source:"participants",payload:y}),w=>n.emit("newsletter",w));}),c("newsletter-settings.update",y=>{I(()=>Rt({source:"settings",payload:y}),w=>n.emit("newsletter",w));});let Qe=false;return {detach(){if(!Qe){Qe=true;for(let y of r)y();r.length=0;}}}}var wn=class{inner=new events.EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Dl,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Dl=Symbol("zaileys.typed-ee.tag");var _t=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},C=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function hr(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new C("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new C("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var vn="v23.0",yr="https://graph.facebook.com",vo=3,Bl=500,Fl=n=>new Promise(e=>setTimeout(e,n));function Mn(n,e){let t=n.baseUrl??yr,r=n.apiVersion??vn,s=Fl,i=d=>d.split("?")[0]===d?d.split("/").map(c=>encodeURIComponent(c)).join("/"):`${(d.split("?")[0]??"").split("/").map(c=>encodeURIComponent(c)).join("/")}?${d.slice(d.indexOf("?")+1)}`,o=d=>`${t}/${r}/${i(d)}`,a=async(d,c)=>{let l;for(let u=1;u<=vo;u++){let f;try{f=await fetch(o(d),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(S){throw new C("REQUEST_FAILED","graph request failed (network)",{cause:S})}if(f.ok)return await f.json().catch(()=>({}));let v=await f.json().catch(()=>({})),b=v.error?.message??`http ${f.status}`,T=v.error?` (code ${v.error.code??"?"}${v.error.error_subcode?`/${v.error.error_subcode}`:""})`:"";if(f.status===401||f.status===403)throw new C("AUTH",`graph auth rejected: ${b}${T}`);let O=f.status===429||f.status>=500,A=f.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(l=new C(A,`graph request failed: ${b}${T}`),!O)throw l;u<vo&&await s(Bl*2**(u-1));}throw l??new C("REQUEST_FAILED","graph request failed")};return {url:o,get:d=>a(d,{method:"GET"}),post:(d,c)=>a(d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(d,c)=>a(d,{method:"POST",body:c}),delete:(d,c)=>a(d,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var Mo=n=>n.split("@")[0]??n,le=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,re=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:Mo(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function So(n,e,t){let r=e;if(typeof r.text=="string")return {...re(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...re(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...re(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(d=>typeof d.vcard=="string"?Wl(d.vcard):null).filter(d=>d!==null);if(a.length>0)return {...re(n,"contacts",t),contacts:a}}return null}function Wl(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let d=a.slice(2).split(";");s=(d[0]??"").trim(),r=(d[1]??"").trim();}if(a.startsWith("TEL")){let d=a.indexOf(":");if(d>0){let c=a.slice(d+1).trim(),l=/waid=([0-9]+)/.exec(a);c.length>0&&i.push({phone:c,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function Lt(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:le(Mo(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var Ul=["image","video","audio","document","sticker"];function bo(n){let e=n;for(let t of Ul){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function Ao(n,e,t){let r=t.mimetype??await Re(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new C("REQUEST_FAILED","media upload returned no id");return i.id}function Co(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var jl=["image","video","audio","document","sticker"],ql=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},Sn=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,$l=n=>{for(let e of jl){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},Kl=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},Gl=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},Jl=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
|
|
10
|
+
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),tn(n.buttons,t)};var Ds=(n,e,t,r)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{},...r?{inheritDisappearing:r}:{}});var Kn=new WeakSet,Bs=n=>{Kn.add(n);},Fs=n=>{if(!Kn.has(n))return n;Kn.delete(n);let e=crypto.randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var on="status@broadcast",ld=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],ae=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s,i){return new n(e,Ds(t,r,s,i))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=rn(ms(e),t):this.internal.content=De(e),this}htmlApp(e,t){return this.internal.content=ds(e,t),this}image(e,t){return this.internal.pendingContent=_e(e,t),this}videoNote(e,t){return this.internal.pendingContent=ye(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=ye(e,t),this}audio(e,t){return this.internal.pendingContent=Yr(e,t),this}document(e,t){return this.internal.pendingContent=fs(e,t),this}sticker(e,t){return this.internal.pendingContent=_s(e,t),this}buttons(e,t){return this.internal.content=tn(e,t),this}carousel(e,t){return this.internal.content=Zr(e,t),this}list(e){return this.internal.content=ks(e),this}poll(e,t,r){return this.internal.content=Os(e,t,r),this}location(e,t,r){return this.internal.content=Ts(e,t,r),this}contact(e){return this.internal.content=gs(e),this}template(e){return this.internal.content=Ns(e),this}event(e){return this.internal.content=ys(e),this}groupInvite(e){return this.internal.content=ws(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=As(e,t):this.internal.pendingContent=Es(e,t),this}product(e){return this.internal.pendingContent=Rs(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new p("INVALID_OPTIONS","reply() requires a quoted message or key");let t="key"in e&&e.key!=null;return this.internal.quoted=t?e:{key:e},this}mentions(e){if(e.length===0)throw new p("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.mentions??[],...e]);return this.internal.mentions=[...t],this}mentionAll(){return this.internal.mentionAll=true,this}audience(e){if(e.length===0)throw new p("INVALID_OPTIONS","audience() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.statusJidList??[],...e]);return this.internal.statusJidList=[...t],this}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new p("INVALID_OPTIONS","disappearing() requires a positive integer duration");return this.internal.disappearingSeconds=e,this}then(e,t){return (async()=>{if(this.internal.resolveRecipient&&(this.internal.recipient=await this.internal.resolveRecipient(this.internal.recipient),delete this.internal.resolveRecipient),this.internal.disappearingSeconds===void 0){let c=this.internal.inheritDisappearing?.(this.internal.recipient);c!==void 0&&c>0&&(this.internal.disappearingSeconds=c);}if(this.internal.statusJidList!==void 0&&this.internal.recipient!==on)throw new p("INVALID_RECIPIENT",`audience() only applies to ${on}, not ${this.internal.recipient}`);if(this.internal.albumItems){let c={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(c.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(c.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(c.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(c.disappearingSeconds=this.internal.disappearingSeconds),Kr(this.socket,this.internal.recipient,this.internal.albumItems,c)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new p("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[W];if(i!==void 0){let c=s[rt];if(typeof c=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${c} can only be sent to a group jid ending in @g.us`);let l=s[en],u=l!==void 0?await this.buildStatusMedia(l):i,f=s[Un],v=s[qn];return this.sendRelay(u,f,v,l!==void 0,s[Zt]===true)}let o=this.internal.content;if(this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true),this.internal.recipient===on&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${on} needs audience([...]); without it WhatsApp accepts the message but shows it to nobody`);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds),this.internal.statusJidList!==void 0&&(a.statusJidList=this.internal.statusJidList);let d;try{d=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(c){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:c})}if(!d?.key)throw new p("SEND_FAILED","socket returned no message key");return d.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await B(t.src),s=await au.prepareWAMessageMedia({[t.kind]:r},{upload:this.socket.waUploadToServer});e.hasMediaAttachment=true,t.kind==="image"&&s.imageMessage&&(e.imageMessage=s.imageMessage),t.kind==="video"&&s.videoMessage&&(e.videoMessage=s.videoMessage);}async buildStatusMedia(e){let t={[e.kind]:e.buffer};e.caption!==void 0&&(t.caption=e.caption),e.ptt===true&&(t.ptt=true);try{let r=await au.generateWAMessageContent(t,{upload:this.socket.waUploadToServer});return typeof r.toJSON=="function"?r.toJSON():r}catch(r){throw new p("MEDIA_LOAD_FAILED","groupStatus() media upload failed",{cause:r})}}applyRelayMentions(e){let t=this.internal.mentions,r=this.internal.mentionAll===true;if((t===void 0||t.length===0)&&!r)return;let s=au.normalizeMessageContent(e),i=s==null?void 0:au.getContentType(s);if(s==null||i===void 0)return;let o=s[i];if(o==null||typeof o!="object")return;let a=o.contextInfo??{};t!==void 0&&t.length>0&&(a.mentionedJid=t),r&&(a.nonJidMentions=1),o.contextInfo=a;}async sendRelay(e,t,r,s=false,i=false){let o=this.socket.relayMessage;if(typeof o!="function")throw new p("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let S=e.interactiveMessage?.header;t!==void 0&&S&&await this.uploadHeaderMedia(S,t);let T=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&T)for(let O of r){let A=T[O.index]?.header;A&&await this.uploadHeaderMedia(A,O);}}catch(S){throw new p("SEND_FAILED","interactive media upload failed",{cause:S})}let a=e;!s&&a.messageContextInfo?.messageSecret==null&&(a.messageContextInfo={...a.messageContextInfo,messageSecret:crypto.randomBytes(32)}),this.applyRelayMentions(e);let c={userJid:this.socket.user?.id??""},l=this.internal.quoted;l!==void 0&&l.message!=null&&(c.quoted=l),this.internal.disappearingSeconds!==void 0&&(c.ephemeralExpiration=this.internal.disappearingSeconds);let u=au.generateWAMessageFromContent(this.internal.recipient,e,c);if(s&&u.message!=null&&Bs(u.message),typeof u.key?.id!="string")throw new p("SEND_FAILED","failed to generate relay message key");let v="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:u.key.id,additionalNodes:ld}:{messageId:u.key.id};try{await o(this.internal.recipient,u.message,v);}catch(S){throw new p("SEND_FAILED","socket relayMessage rejected",{cause:S})}return i&&await this.relayIdenticalEdit(u,c),this.internal.recordSent?.(u),u.key}async relayIdenticalEdit(e,t){let r=this.socket.relayMessage;if(typeof r!="function"||e.message==null)return;let s=au.generateWAMessageFromContent(this.internal.recipient,{botForwardedMessage:{message:{protocolMessage:{key:{remoteJid:this.internal.recipient,fromMe:true,id:e.key.id},type:14,editedMessage:e.message}}}},t);if(typeof s.key?.id=="string")try{await r(this.internal.recipient,s.message,{messageId:s.key.id});}catch{}}};var st=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=De(e),this}image(e,t){return this.pendingContent=_e(e,t),this}video(e,t){return this.pendingContent=ye(e,t),this}then(e,t){return this.send().then(e,t)}async send(){let e=this.key.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new p("EMPTY_CONTENT","edit() requires a content method before await");let t={...this.content,edit:this.key},r;try{r=await this.socket.sendMessage(e,t);}catch(s){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new p("SEND_FAILED","socket returned no message key");return r.key}};var Gn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},Jn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},Vn=async(n,e,t={})=>{let r=Gn(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new p("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},Hn=async(n,e,t)=>{let r=Gn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return Jn(s)},zn=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new p("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return Jn(i)},an=async(n,e,t,r={})=>{let s=Gn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return Jn(o)};var ud=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,it=n=>ud.test(n),Yn=async(n,e,t,r=pd)=>{if(it(e))return e;let s=t.get(e);if(s!==void 0)return s;let i=r.get(e);if(i!==void 0)return i;let o=(async()=>{let d=(await n.onWhatsApp(e))?.find(c=>c.exists&&c.jid);if(!d)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,d.jid),d.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},pd=new Map;var L=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysDomainError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var ot=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new L("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new L("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new L("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var at=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async set(e){let t=this.requireSocket();if(e.lastSeen!==void 0&&await t.updateLastSeenPrivacy(e.lastSeen),e.online!==void 0&&await t.updateOnlinePrivacy(e.online),e.profile!==void 0&&await t.updateProfilePicturePrivacy(e.profile),e.status!==void 0&&await t.updateStatusPrivacy(e.status),e.readReceipts!==void 0){let r=typeof e.readReceipts=="boolean"?e.readReceipts?"all":"none":e.readReceipts;await t.updateReadReceiptsPrivacy(r);}e.groupAdd!==void 0&&await t.updateGroupsAddPrivacy(e.groupAdd),e.call!==void 0&&await t.updateCallPrivacy(e.call);}async get(){return this.requireSocket().fetchPrivacySettings()}async block(e){await this.requireSocket().updateBlockStatus(e,"block");}async unblock(e){await this.requireSocket().updateBlockStatus(e,"unblock");}async blocklist(){return this.requireSocket().fetchBlocklist()}async disappearingMode(e){await this.requireSocket().updateDefaultDisappearingMode(e);}async call(e){await this.requireSocket().updateCallPrivacy(e);}};var dt=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new L("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var ct=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var lt=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Us=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new L("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},ut=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:true,lastMessages:t},e);}async markUnread(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:false,lastMessages:t},e);}async star(e,t=true){let r=Us(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async fetchHistory(e,t,r){return Us(t),this.requireSocket().fetchMessageHistory(e,t,r)}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var pt=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var mt=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new L("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var j=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCommandError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var md=n=>{let e=n[0];return e==="{"||e==="["},gd=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},fd=n=>n===" "||n===" "||n===`
|
|
11
|
+
`||n==="\r",hd=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let d=n[a];if(s){t+=d,s=false,i=true,o=false;continue}if(d==="\\"&&r!==null){s=true;continue}if(r!==null){d===r?r=null:t+=d,o=false;continue}if((d==='"'||d==="'")&&o){r=d,i=true,o=false;continue}if(fd(d)){i&&(e.push(t),t="",i=false),o=true;continue}t+=d,i=true,o=false;}return i&&e.push(t),e},yd=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},wd=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function Qn(n,e){let t=yd(n,e);if(t===null)return wd(n);let r=n.slice(t.length),s=hd(r),i={matched:true,args:[],flags:{},json:void 0,raw:n};if(s.length===0)return i.name="",i;i.name=(s[0]??"").toLowerCase();let o=false;for(let a=1;a<s.length;a+=1){let d=s[a];if(d!==void 0){if(d.startsWith("--")){let c=d.slice(2);if(c.length===0){i.args.push(d);continue}let l=c.indexOf("=");if(l!==-1){let f=c.slice(0,l),v=c.slice(l+1);i.flags[f]=v;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[c]=u,a+=1):i.flags[c]=true;continue}if(!o&&md(d)){let c=gd(d);c.ok&&(i.json=c.value,o=true);}i.args.push(d);}}return i}var js=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new j("INVALID_COMMAND_NAME","empty command segment in spec");return e},Fe=n=>n.join(" "),qs=n=>[n.name,...n.aliases??[]].join("|"),vd=n=>{let e={};return n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},gt=class{paths=new Map;defs=[];maxDepth=1;register(e,t){let r=typeof e=="string"?e:qs(e);if(r.trim().length===0)throw new j("INVALID_COMMAND_NAME","command spec must not be empty");let s=r.split("|").map(d=>js(d)),i=s[0],o=s.slice(1).map(d=>Fe(d)),a={name:Fe(i),aliases:o,parts:i,handler:t,meta:typeof e=="string"?{}:vd(e)};for(let d of s){let c=Fe(d);if(this.paths.has(c))throw new j("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let d of s)this.paths.set(Fe(d),a),d.length>this.maxDepth&&(this.maxDepth=d.length);this.defs.push(a);}resolve(e){if(!e.matched||e.name===void 0||e.name.length===0)return;let t=[e.name.toLowerCase(),...e.args.map(s=>s.toLowerCase())],r=Math.min(this.maxDepth,t.length);for(let s=r;s>=1;s-=1){let i=t.slice(0,s).join(" "),o=this.paths.get(i);if(o!==void 0)return {def:o,args:e.args.slice(s-1)}}}unregister(e){let r=(typeof e=="string"?e:qs(e)).split("|").map(a=>js(a)),s=Fe(r[0]),i=this.paths.get(s);if(i===void 0)return;for(let a of [i.parts,...i.aliases.map(d=>d.split(" "))])this.paths.delete(Fe(a));let o=this.defs.indexOf(i);o>=0&&this.defs.splice(o,1),this.maxDepth=this.defs.reduce((a,d)=>Math.max(a,d.parts.length),1);}list(){return [...this.defs]}describe(){return this.defs.map(e=>({name:e.name,aliases:[...e.aliases],...e.meta}))}};async function Xn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new j("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(d){throw s.error=d,s.thrown=true,d}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(d){throw s.thrown||d instanceof j?d:new j("MIDDLEWARE_ERROR","middleware threw during execution",{cause:d})}};await i(0);}var Sd=1e4,bd=3600*1e3,Zn=new lruCache.LRUCache({max:Sd,ttl:bd}),Ad=(n,e)=>`${n}\0${e}`,Cd=()=>{Zn.clear();},er=async(n,e,t)=>{if((n.group===true||n.admin===true)&&!e.isGroup)return {reason:"group-only"};if(n.private===true&&e.isGroup)return {reason:"private-only"};if(n.admin===true){let s=e.roomId;if(s===null)return {reason:"admin-only"};if(!await t.isAdmin(s,e.senderId))return {reason:"admin-only"}}if(n.cooldown!==void 0&&n.cooldown>0){let s=Ad(e.command,e.senderId),i=Zn.get(s),o=t.now(),a=n.cooldown*1e3;if(i!==void 0&&o-i<a)return {reason:"cooldown",retryIn:Math.ceil((a-(o-i))/1e3)};Zn.set(s,o);}return null};function tr(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=Qn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0){i.name!==void 0&&i.name.length>0&&n.onNotFound?.(i.name,s);return}let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},d=n.buildContext(a,s);(async()=>{let l=await er(o.def.meta,d,{isAdmin:n.isAdmin??(async()=>false),now:()=>Date.now()});if(l!==null){n.onBlocked?.(l,d);return}await Xn(n.middleware,d,()=>o.def.handler(d));})().catch(l=>{let u=l instanceof j?l:new j("HANDLER_ERROR","command handler failed",{cause:l});n.onError?.(u,d)!==true&&n.logger.error(u,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Ue=new Map,Ks=n=>n!=null&&typeof n=="object"?n:null,Gs=n=>Array.isArray(n.content)?n.content.map(Ks).filter(e=>e!==null):[],$s=(n,e)=>Gs(n).find(t=>t.tag===e),We=n=>typeof n=="string"&&n.length>0?n:void 0,nr=n=>{if(n===void 0)return;let e=Number.parseInt(n,10);return Number.isFinite(e)?e:void 0},Ed=(n,e)=>{if(Object.keys(e).length!==0){if(Ue.size>=64){let t=Ue.keys().next().value;t!==void 0&&Ue.delete(t);}Ue.set(n,e);}},Js=n=>{let e=Ks(n);if(e===null||e.tag!=="call")return false;let t=Gs(e).find(S=>S.tag==="offer"),r=We(t?.attrs?.["call-id"]);if(t===void 0||r===void 0)return false;let s={},i=We(e.attrs?.platform),o=We(e.attrs?.version),a=We(e.attrs?.notify),d=We(t.attrs?.caller_country_code),c=We(t.attrs?.caller_pn);i!==void 0&&(s.platform=i),o!==void 0&&(s.appVersion=o),a!==void 0&&(s.name=a),d!==void 0&&(s.countryCode=d),c!==void 0&&(s.phoneJid=c);let l=nr($s(t,"net")?.attrs?.medium);l!==void 0&&(s.networkMedium=l);let u=$s(t,"video"),f=nr(u?.attrs?.screen_width),v=nr(u?.attrs?.screen_height);return f!==void 0&&v!==void 0&&(s.screen={width:f,height:v}),Ed(r,s),true},Vs=n=>{let e=Ue.get(n);return e!==void 0&&Ue.delete(n),e};var Hs=["text","image","video","audio","document","sticker","reaction","edit","delete","poll-vote","button-click","list-select","mention","mention-all","group-update","group-join","group-leave","member-tag","call-incoming","call-ended","history-sync","limited","presence","newsletter"],zs=n=>n;var Pd=(n,e)=>{let t=H__default.default.dirname(H__default.default.resolve(n)),r=e===void 0?void 0:H__default.default.resolve(e);if(r!==void 0){let i=H__default.default.relative(r,t);return i.length===0||i.startsWith("..")?void 0:i.split(H__default.default.sep)[0]}let s=H__default.default.basename(t);return s.length>0?s:void 0},kd=n=>n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Td=n=>{let e={name:n.name};return n.aliases!==void 0&&(e.aliases=n.aliases),n.description!==void 0&&(e.description=n.description),n.usage!==void 0&&(e.usage=n.usage),n.category!==void 0&&(e.category=n.category),n.hidden!==void 0&&(e.hidden=n.hidden),n.metadata!==void 0&&(e.metadata=n.metadata),n.group!==void 0&&(e.group=n.group),n.private!==void 0&&(e.private=n.private),n.admin!==void 0&&(e.admin=n.admin),n.cooldown!==void 0&&(e.cooldown=n.cooldown),e},Id=(n,e)=>{let t=n.message;typeof t=="function"&&e.command(Td(n),s=>t(s,e));let r=n;for(let s of Hs){let i=r[kd(s)];typeof i=="function"&&e.on(s,o=>{i(o,e);});}},ft=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t,r){if(typeof e?.name!="string"){this.logger?.warn({file:t},"plugin: invalid shape (needs a name); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let s=[],i=Pd(t,r),o={client:this.host,logger:this.logger,pluginDir:H__default.default.dirname(t),category:i,command:(a,d)=>{let c=typeof a=="string"||a.category!==void 0||i===void 0?a:{...a,category:i};this.host.command(c,d),s.push(()=>this.host.unregisterCommand(c));},use:a=>{this.host.use(a),s.push(()=>{this.host.unuse(a);});},on:(a,d)=>{let c=this.host.on(a,d);return s.push(c),c},once:(a,d)=>{let c=false,l=this.host.on(a,u=>{c||(c=true,l(),d(u));});return s.push(l),l}};try{Id(e,o);let a=await e.setup?.(o);typeof a=="function"&&s.push(a);}catch(a){for(let d of [...s].reverse())try{await d();}catch{}this.logger?.error({err:a,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:s});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Rd=/\.(ts|js|mjs|cjs)$/,_d=/(\.d\.ts$|^_|[/\\]_)/;async function sr(n,e,t){let r;try{r=await fs$1.promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=H__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await sr(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function Qs(n,e){try{let r=await import(url.pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"?s:void 0}catch{return}}var ht=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=H__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Rd,this.ignore=e.options.ignore??_d;let t=process.env.NODE_ENV!=="production";this.watchEnabled=e.options.watch??t,this.onError=e.options.onError;}async start(){let e=await sr(this.dir,this.pattern,this.ignore);for(let t of e)await this.loadFile(t);this.watchEnabled&&(process.env.NODE_ENV==="production"&&this.logger?.warn({dir:this.dir},"plugin watch is enabled in production: writes to this directory execute code, and each reload leaks the previous module"),this.startWatch());}async stop(){this.debounce&&clearTimeout(this.debounce),this.watcher?.close(),this.watcher=void 0,await this.flushChain,await this.registry.unloadAll(),this.fileToName.clear();}async loadFile(e){let t=await Qs(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e,this.dir);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=fs$1.watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=H__default.default.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await fs$1.promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var N=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysAutomationError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var Nd=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Dd=5e3,Bd=600*1e3,be=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new lruCache.LRUCache({max:Dd,ttl:Bd});constructor(e,t={}){if(!(e.perSec>0))throw new N("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new N("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new N("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??Nd;let r=e.burst??e.perSec;this.global={tokens:r,capacity:r,ratePerMs:e.perSec/1e3,last:this.now()},e.perJidPerSec!==void 0&&(this.perJidRatePerMs=e.perJidPerSec/1e3,this.perJidCapacity=e.perJidPerSec);}async acquire(e){await this.consume(this.global),e!==void 0&&this.perJidRatePerMs!==void 0&&await this.consume(this.bucketFor(e));}bucketFor(e){let t=this.perJid.get(e);if(t)return t;let r=this.perJidCapacity??1,s={tokens:r,capacity:r,ratePerMs:this.perJidRatePerMs??1,last:this.now()};return this.perJid.set(e,s),s}consume(e){if(this.refill(e),e.tokens>=1)return e.tokens-=1,Promise.resolve();let t=(1-e.tokens)/e.ratePerMs;return e.tokens-=1,this.sleep(t)}refill(e){let t=this.now(),r=t-e.last;r>0&&(e.tokens=Math.min(e.capacity,e.tokens+r*e.ratePerMs),e.last=t);}};var Fd={"group.create":6e4,"group.join":3e4,"group.participants":1e4,"group.update":3e3,"community.create":12e4,"community.join":3e4,"community.update":3e3,"newsletter.create":12e4,"newsletter.follow":2e3,"newsletter.update":3e3},Wd=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function ir(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??Wd,i={...Fd,...n.intervalsMs??{}},o=new Map,a=new Map,d=async(c,l)=>{let u=i[c]??0,f=o.get(c);if(f!==void 0&&u>0){let v=u-(r()-f);v>0&&await s(v);}return o.set(c,r()),l()};return {run(c,l){if(!t)return l();let f=(a.get(c)??Promise.resolve()).then(()=>d(c,l),()=>d(c,l));return a.set(c,f.then(()=>{},()=>{})),f}}}var Ud=1e4,jd=12e4,qd={maxRetries:0,backoffMs:()=>0},$d=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),yt=class{concurrency;retry;sleep;pending=[];maxPending;taskTimeoutMs;active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??qd,this.sleep=t.sleep??$d,this.maxPending=e.maxPending??Ud,this.taskTimeoutMs=e.taskTimeoutMs??jd;}add(e){return this.pending.length>=this.maxPending?Promise.reject(new N("QUEUE_FULL",`task queue is full (${this.maxPending} pending)`)):new Promise((t,r)=>{this.pending.push({run:()=>this.execute(e).then(t,r)}),this.pump();})}onIdle(){return this.active===0&&this.pending.length===0?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e);})}pump(){for(;this.active<this.concurrency&&this.pending.length>0;){let e=this.pending.shift();if(!e)break;this.active++,e.run().finally(()=>{this.active--,this.pump(),this.settleIdle();});}}settleIdle(){if(this.active===0&&this.pending.length===0&&this.idleWaiters.length>0){let e=this.idleWaiters;this.idleWaiters=[];for(let t of e)t();}}async withDeadline(e){if(this.taskTimeoutMs<=0)return e();let t;try{return await Promise.race([e(),new Promise((r,s)=>{t=setTimeout(()=>s(new N("QUEUE_TIMEOUT",`task exceeded ${this.taskTimeoutMs}ms`)),this.taskTimeoutMs);})])}finally{t!==void 0&&clearTimeout(t);}}async execute(e){let t=0;for(;;)try{return await this.withDeadline(e)}catch(r){if(t>=this.retry.maxRetries)throw r;t+=1,await this.sleep(this.retry.backoffMs(t));}}};var Kd=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function or(n,e,t,r={}){let s={sent:[],failed:[]};if(n.length===0)return s;let i=r.rateLimitPerSec??5,o={};t.now&&(o.now=t.now),t.sleep&&(o.sleep=t.sleep);let a=t.limiter??new be({perSec:i},o),d=r.retry,c=t.sleep?{sleep:t.sleep}:{},l=d?new yt({concurrency:1,retry:d},c):void 0,u=n.length,f=0;for(let v of n){await a.acquire(v);let S=()=>e(t.sendTo(v)).then(()=>{});try{l?await l.add(S):await S(),s.sent.push(v),f+=1,r.onProgress?.(f,u,v,!0);}catch(T){s.failed.push({jid:v,error:Kd(T)}),f+=1,r.onProgress?.(f,u,v,false);}}return s}var Jd=1e3,Vd=2e3,Hd=600*1e3,wt=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??Jd,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new lruCache.LRUCache({max:Vd,ttl:Hd});pendingClears=new Set;requireSocket(){let e=this.getSocket();if(!e)throw new N("NOT_CONNECTED","client not connected");return e}throttled(e,t){if(!this.throttleEnabled||this.minIntervalMs<=0)return false;let r=`${e}:${t??"global"}`,s=this.lastSent.get(r),i=this.now();return s!==void 0&&i-s<this.minIntervalMs?true:(this.lastSent.set(r,i),false)}async update(e,t){let r=this.requireSocket();if(!this.throttled(e,t))try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new N("PRESENCE_FAILED",`presence update '${e}' failed`,{cause:s})}}scheduleClear(e,t){if(this.getSocket()===void 0)return;let r=setTimeout(()=>{this.pendingClears.delete(r);try{let s=this.getSocket();if(s===void 0)return;Promise.resolve(s.sendPresenceUpdate("paused",e)).catch(()=>{});}catch{return}},t);typeof r.unref=="function"&&r.unref(),this.pendingClears.add(r);}dispose(){for(let e of this.pendingClears)clearTimeout(e);this.pendingClears.clear(),this.lastSent.clear();}async online(){await this.update("available");}async offline(){await this.update("unavailable");}async typing(e,t){await this.update("composing",e),t!==void 0&&this.scheduleClear(e,t);}async recording(e,t){await this.update("recording",e),t!==void 0&&this.scheduleClear(e,t);}};var Xs=2147483e3,Yd=5,Qd=3e4,Xd={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},Zd=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",vt=class{store;sendSnapshot;now;timer;logger;acquire;memory=new Map;timers=new Map;failures=new Map;constructor(e){this.store=e.store,this.sendSnapshot=e.sendSnapshot,this.now=e.now??(()=>Date.now()),this.timer=e.timer??Xd,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new N("SCHEDULE_INVALID","scheduleAt requires a valid Date");let s=await this.evaluate(t),i=crypto.randomUUID(),o={id:i,fireAt:r,recipient:s.recipient,payload:s};return await this.persist(o),this.arm(o),{id:i,cancel:()=>{this.cancel(i);}}}async loadPending(){let e=this.store.listScheduledJobs;if(!e){for(let r of this.memory.values())this.timers.has(r.id)||this.arm(r);return}let t;try{t=await e.call(this.store);}catch(r){this.logger?.warn(r,"scheduler loadPending failed");return}for(let r of t)this.timers.has(r.id)||(this.memory.set(r.id,r),this.arm(r));}dispose(){for(let e of this.timers.values())this.timer.clear(e);this.timers.clear();}cancel(e){let t=this.timers.get(e);t!==void 0&&(this.timer.clear(t),this.timers.delete(e)),this.memory.delete(e),this.remove(e);}arm(e){let t=Math.max(0,e.fireAt-this.now());if(t>Xs){let s=this.timer.set(()=>{this.timers.delete(e.id),this.arm(e);},Xs);this.timers.set(e.id,s);return}let r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),Zd(e.payload)){try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){let r=(this.failures.get(e.id)??0)+1;if(this.failures.set(e.id,r),r>=Yd){this.logger?.error({id:e.id,attempts:r},"scheduled send failed repeatedly; dropping the job"),this.failures.delete(e.id),this.memory.delete(e.id),await this.remove(e.id);return}this.logger?.warn(t,"scheduled send failed; re-arming for retry"),e.fireAt=this.now()+Qd*r,this.arm(e);return}this.failures.delete(e.id);}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,d)=>{if(r+=1,r>1)throw new N("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=d?{recipient:o,content:a,options:d}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new N("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=ae.create(s,"");try{await e(i);}catch(o){throw o instanceof N?o:new N("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new N("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function Zs(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((d,c)=>Number(c.messageTimestamp??0)-Number(d.messageTimestamp??0));for(let d=0;d<a.length;d+=1){let c=a[d],l=Number(c.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,f=e.maxPerChat!==void 0&&d>=e.maxPerChat;(u||f)&&(await n.deleteMessage(c.key),r+=1);}}return r}var Mt=class{store;options;logger;now;timer;running=false;warnedUnsupported=false;disabled=false;constructor(e){this.store=e.store,this.options=e.options,this.logger=e.logger,this.now=e.now??Date.now;}get active(){return this.options.maxAgeMs!==void 0||this.options.maxPerChat!==void 0}buildPruneOptions(){let e={};return this.options.maxAgeMs!==void 0&&(e.olderThan=Math.floor((this.now()-this.options.maxAgeMs)/1e3)),this.options.maxPerChat!==void 0&&(e.maxPerChat=this.options.maxPerChat),typeof this.options.chats=="function"&&(e.chatFilter=this.options.chats),e}async runOnce(){if(!this.active||this.disabled)return 0;let e=this.buildPruneOptions();return typeof this.store.pruneMessages=="function"?this.store.pruneMessages(e):typeof this.store.deleteMessage=="function"?Zs(this.store,e):(this.disabled=true,this.warnedUnsupported||(this.warnedUnsupported=true,this.logger?.warn({code:"AUTO_DELETE_UNSUPPORTED"},"autoDelete: store implements neither pruneMessages nor deleteMessage; sweeper disabled")),0)}start(){if(!this.active||this.timer)return;let e=this.options.intervalMs??6e4;this.timer=setInterval(()=>{this.running||(this.running=true,this.runOnce().catch(t=>this.logger?.warn(t,"autoDelete sweep failed")).finally(()=>{this.running=false;}));},e),this.timer.unref?.();}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0);}};var je=n=>typeof n!="string"||n.length===0?null:au.jidNormalizedUser(n),de=n=>typeof n=="string"&&n.length>0?n:void 0,nc=["@s.whatsapp.net","@c.us"],dn=n=>n.endsWith("@lid"),ei=n=>nc.some(e=>n.endsWith(e)),Z=(n,e)=>{if(!n)return null;let t=de(n.participant)??n.remoteJid,r=je(t);if(r===null)return null;let s=de(n.participantAlt)??de(n.remoteJidAlt),i=s!=null?je(s):null,o=de(n.participantUsername)??de(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let d=i!==null?[r,i]:[r],c=d.find(dn),l=d.find(ei);c!==void 0&&(a.lid=c),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=de(e);return u!==void 0&&(a.pushName=u),a},ti=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=de(n.participant),r=de(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=Z(s);return o&&(i.sender=o),i},St=n=>{if(!n)return {mentionedJids:[],mentionAll:false};let e=n.mentionedJid,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],r=n.groupMentions,s=Array.isArray(r)&&r.length>0;return {mentionedJids:t,mentionAll:s}};var qe=n=>au.isJidGroup(n)===true,$e=n=>{if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n.toNumber=="function"){let e=n.toNumber();return Number.isFinite(e)?e:null}return null},m=n=>n!=null&&typeof n=="object"?n:null,ni=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],ri=["groupStatusMessage","groupStatusMessageV2"],si=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of ni){let o=m(m(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Ke=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of ni){let i=m(m(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var ar=(n,e)=>{let t=au.jidDecode(n),r=au.jidDecode(e);return t===void 0||r===void 0||!t.user||!r.user?false:t.user===r.user&&t.server===r.server},cn=(n,e)=>{if(n===e)return true;let t=n.includes("@")?n:rc(n);return ar(t,e)},Lh=n=>{let t=(n.split("@")[0]??"").split(":")[0]?.replace(/\D/g,"")??"";return n.endsWith("@s.whatsapp.net")||n.endsWith("@c.us")?t:""},rc=n=>`${n.replace(/\D/g,"")}@s.whatsapp.net`;var bt=class{getSocket;options;logger;constructor(e,t,r){this.getSocket=e,this.options=t,this.logger=r;}get enabled(){return this.options.enabled===true}async reject(e,t){let r=this.getSocket();if(!r)throw new N("NOT_CONNECTED","cannot reject a call: client not connected");await r.rejectCall(e,t);}async handle(e){if(this.enabled&&!await this.isAllowed(e.from)){try{await this.reject(e.callId,e.from);}catch(t){this.logger?.warn(t,"autoRejectCall: rejectCall failed");return}try{await this.options.onReject?.(e);}catch(t){this.logger?.warn(t,"autoRejectCall: onReject hook failed");}}}async isAllowed(e){let t=this.options.allow;if(t===void 0)return false;try{return Array.isArray(t)?t.some(r=>cn(r,e)):await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var sc={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},ic=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[sc[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},ln=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=ic(n,e)??"application/octet-stream";return {buffer:s,mime:i,size:s.byteLength}}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media download failed"),r instanceof Error?r:new Error("media download failed")}},oi=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys');return await r(n,"stream",{})}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media stream download failed"),r instanceof Error?r:new Error("media stream download failed")}};var ac=new Set([".",",",";",":","!","?"]),dc=n=>{let e=n.length;for(;e>0&&ac.has(n[e-1]);)e-=1;return e===n.length?n:n.slice(0,e)},di=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(dc):[]},ai=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},ci=n=>(ai(n).toString(16).padStart(8,"0")+ai(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),li=n=>ci(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),ui=(n,e)=>ci(`${n??""}|${e}`),pi=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},mi=n=>{let e=au.jidDecode(n);if(!e)return "unknown";let t=e.device;return t===void 0||t===0?"android":t===2?"ios":t===3?"web":t===4?"desktop":"unknown"},cc=n=>n.trim().endsWith("?"),lc=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),uc=(n,e)=>{if(e.length===0)return false;let t;try{t=au.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return au.jidNormalizedUser(r)===t}catch{return r===n}})},pc=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.some(s=>cn(s,e)):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},mc=0,gc=14,fc=1,hc=2,yc=n=>{let e=m(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=m(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof m(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===gc,isDeleted:r===mc,isPinned:s===fc,isUnPinned:s===hc,isBot:m(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:si(e,ri)}},dr=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&qe(e),r=yc(n.message),s=d=>n.lidMap!=null&&d.endsWith("@lid")?n.lidMap.get(d)??d:d,i=s(n.sender.pn??n.sender.jid),o=t?e?au.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(au.jidNormalizedUser(e)):i;return {uniqueId:li(n.key),staticId:ui(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(au.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderUsername:n.sender.username??null,senderDevice:mi(n.sender.deviceJid??n.sender.jid),timestamp:pi(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:di(n.text),isFromMe:n.key.fromMe===true,verified:n.verified!==false,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isOld:n.isOld===true,isQuestion:cc(n.text),isPrefix:lc(n.text,n.prefixes),isTagMe:uc(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",forwardCount:n.forwardCount??0,ephemeralDuration:n.ephemeralDuration??null,addressingMode:n.addressingMode??"pn",mentionedGroups:n.mentionedGroups??[],...n.ad!==void 0?{ad:n.ad}:{},...n.business!==void 0?{business:n.business}:{},...n.media!==void 0?{media:n.media}:{},citation:pc(n.citationConfig,i),roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,message:()=>n.message,reply:n.reply,react:n.react}};var lr={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},hi=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},M=n=>typeof n=="string"&&n.length>0?n:null,ce=(...n)=>{for(let e of n){let t=M(e);if(t!=null)return t}return null},yi=n=>{let e=m(n.message);if(e==null)return n;let t=Ke(e);return t===e?n:{...n,message:t}},wc=n=>{let t=m(m(m(n.botForwardedMessage)?.message)?.richResponseMessage)??m(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=M(m(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
|
|
12
|
+
`).trim();return i.length>0?i:null},vc=n=>{let e=m(n.templateMessage),t=m(e?.hydratedTemplate)??m(e?.hydratedFourRowTemplate);return M(t?.hydratedContentText)},Mc=n=>ce(m(n.pollCreationMessage)?.name,m(n.pollCreationMessageV2)?.name,m(n.pollCreationMessageV3)?.name),Sc=n=>{let e=m(n.locationMessage)??m(n.liveLocationMessage);if(e==null)return null;let t=ce(e.name,e.address);if(t!=null){let i=M(e.name),o=M(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},bc=n=>{let e=M(m(n.contactMessage)?.displayName);if(e!=null)return e;let t=m(n.contactsArrayMessage),r=M(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>M(m(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},wi=n=>ce(n.conversation,m(n.extendedTextMessage)?.text,wc(n),M(m(m(n.interactiveMessage)?.body)?.text),m(n.buttonsMessage)?.contentText,m(n.listMessage)?.description,vc(n),Mc(n),Sc(n),bc(n)),Ac=n=>ce(m(n.buttonsResponseMessage)?.selectedDisplayText,m(n.buttonsResponseMessage)?.selectedButtonId,m(n.templateButtonReplyMessage)?.selectedDisplayText,m(n.templateButtonReplyMessage)?.selectedId,m(n.listResponseMessage)?.title,m(m(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,m(m(n.interactiveResponseMessage)?.body)?.text),Cc=n=>ce(m(n.imageMessage)?.caption,m(n.videoMessage)?.caption,m(n.documentMessage)?.caption,m(n.documentMessage)?.fileName),_=n=>{if(typeof n=="number")return n;let e=$e(n);return typeof e=="number"?e:null},Ec=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],vi=n=>{let e=m(n.pollCreationMessage)??m(n.pollCreationMessageV2)??m(n.pollCreationMessageV3);if(e!=null){let A=Array.isArray(e.options)?e.options:[];return {type:"poll",name:M(e.name),options:A.map(b=>M(m(b)?.optionName)).filter(b=>b!=null),selectableCount:_(e.selectableOptionsCount)??0}}let t=m(n.contactMessage);if(t!=null)return {type:"contact",displayName:M(t.displayName),vcard:M(t.vcard),contacts:[{displayName:M(t.displayName),vcard:M(t.vcard)}]};let r=m(n.contactsArrayMessage);if(r!=null){let A=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:M(r.displayName),vcard:null,contacts:A.map(b=>({displayName:M(m(b)?.displayName),vcard:M(m(b)?.vcard)}))}}let s=m(n.locationMessage);if(s!=null)return {type:"location",latitude:_(s.degreesLatitude),longitude:_(s.degreesLongitude),name:M(s.name),address:M(s.address),accuracy:_(s.accuracyInMeters),speed:_(s.speedInMps),caption:M(s.comment)};let i=m(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:_(i.degreesLatitude),longitude:_(i.degreesLongitude),name:null,address:null,accuracy:_(i.accuracyInMeters),speed:_(i.speedInMps),caption:M(i.caption)};let o=m(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:_(o.expectedImageCount),expectedVideoCount:_(o.expectedVideoCount)};let a=m(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:M(a.groupJid),groupName:M(a.groupName),inviteCode:M(a.inviteCode),caption:M(a.caption),expiresAt:_(a.inviteExpiration)};let d=m(m(n.productMessage)?.product);if(m(n.productMessage)!=null){let A=M(m(n.productMessage)?.businessOwnerJid),b=_(d?.priceAmount1000);return {type:"product",productId:M(d?.productId),title:M(d?.title),description:M(d?.description),price:b!=null?b/1e3:null,currency:M(d?.currencyCode),retailerId:M(d?.retailerId),url:M(d?.url),businessOwnerId:A}}let c=m(n.orderMessage);if(c!=null){let A=_(c.totalAmount1000),b={1:"inquiry",2:"accepted",3:"declined"},x=c.status;return {type:"order",orderId:M(c.orderId),title:M(c.orderTitle),itemCount:_(c.itemCount),total:A!=null?A/1e3:null,currency:M(c.totalCurrencyCode),status:typeof x=="number"?b[x]??null:M(x),message:M(c.message)}}let l=m(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||m(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||m(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let A=m(l.node),b=_(A?.amount1000),x=m(A?.noteMessage);return {type:"payment",kind:l.kind,amount:b!=null?b/1e3:null,currency:M(A?.currencyCodeIso4217),note:ce(x?.conversation,m(x?.extendedTextMessage)?.text),expiresAt:_(A?.expiryTimestamp)}}let u=m(n.eventMessage);if(u!=null){let A=m(u.location);return {type:"event",name:M(u.name),description:M(u.description),location:A!=null?ce(A.name,A.address):null,startTime:_(u.startTime),endTime:_(u.endTime),isCanceled:u.isCanceled===true}}let f=m(n.buttonsMessage);if(f!=null){let A=Array.isArray(f.buttons)?f.buttons:[];return {type:"buttons",contentText:M(f.contentText),footerText:M(f.footerText),buttons:A.map(b=>({id:M(m(b)?.buttonId),text:M(m(m(b)?.buttonText)?.displayText)}))}}let v=m(n.listMessage);if(v!=null){let A=Array.isArray(v.sections)?v.sections:[];return {type:"list",title:M(v.title),description:M(v.description),buttonText:M(v.buttonText),sections:A.map(b=>{let x=Array.isArray(m(b)?.rows)?m(b).rows:[];return {title:M(m(b)?.title),rows:x.map(F=>({id:M(m(F)?.rowId),title:M(m(F)?.title),description:M(m(F)?.description)}))}})}}let S=m(n.interactiveMessage);if(S!=null){let A=m(S.nativeFlowMessage),b=Array.isArray(A?.buttons)?A.buttons:[];return {type:"interactive",title:M(m(S.header)?.title),body:M(m(S.body)?.text),footer:M(m(S.footer)?.text),buttons:b.map(x=>({name:M(m(x)?.name),params:M(m(x)?.buttonParamsJson)}))}}let T=m(n.templateMessage);if(T!=null){let A=m(T.hydratedTemplate)??m(T.hydratedFourRowTemplate),b=Array.isArray(A?.hydratedButtons)?A.hydratedButtons:[];return {type:"template",text:M(A?.hydratedContentText),buttons:b.map(x=>{let F=m(x),z=m(F?.quickReplyButton)??m(F?.urlButton)??m(F?.callButton);return {id:M(z?.id),text:M(z?.displayText)}})}}let O=m(n.extendedTextMessage);if(O!=null){let A=ce(O.canonicalUrl,O.matchedText),b=M(O.title),x=M(O.description);if(A!=null&&(b!=null||x!=null))return {type:"link",url:A,title:b,description:x}}return null};var Ct=n=>{let e=m(n.message);if(e==null)return null;let t=Ke(e);return wi(t)??Ac(t)??Cc(t)},Pt=n=>{let e=m(yi(n).message);if(e==null)return null;let t=m(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(e)){if(r==null||typeof r!="object")continue;let s=r.contextInfo;if(s!=null)return s}return null},Pc=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[lr[e]];return r==null||typeof r!="object"?null:r},kc=n=>{let e=n.message;if(e==null)return false;if(e.viewOnceMessage!=null||e.viewOnceMessageV2!=null||e.viewOnceMessageV2Extension!=null)return true;for(let t of Object.values(lr)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},Tc=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,Mi=n=>Si(n,Pt(n))??void 0,Ic=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,Si=(n,e)=>{let t=e?.expiration;if(typeof t=="number"&&t>0)return t;let r=m(m(n.message)?.ephemeralMessage),s=m(m(r?.message)?.extendedTextMessage)?.contextInfo,i=m(s)?.expiration;return typeof i=="number"&&i>0?i:null},xc=n=>{let e=n?.groupMentions;if(!Array.isArray(e))return [];let t=[];for(let r of e){let s=m(r)?.groupJid;typeof s=="string"&&s.length>0&&t.push(s);}return t},bi=n=>typeof n=="string"&&n.length>0?n:void 0,Oc=n=>{let e=m(n?.externalAdReply);if(e==null)return;let t={},r=[["clickId","ctwaClid"],["sourceId","sourceId"],["sourceUrl","sourceUrl"],["sourceApp","sourceApp"],["sourceType","sourceType"],["title","title"],["body","body"],["thumbnailUrl","thumbnailUrl"],["ref","ref"]];for(let[s,i]of r){let o=bi(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},Rc=n=>{let e=bi(m(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},Ae=n=>{let e=m(n);if(e==null)return "text";let t=Ke(e);for(let r of Object.values(lr))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of Ec)if(t[r]!=null)return s;return "text"},gi=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},_c=async(n,e,t,r,s,i)=>{try{if(n==null||n.quotedMessage==null)return null;let o=n.stanzaId;if(typeof o!="string"||o.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let S=await e.resolveQuoted(o,t);if(S!=null&&S.message!=null){let T=Ct(S)??"",O=Ce(S,e,Ae(S.message),T,Et(S,e),s);if(O!==null)return O}}let a=ti(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let d=a.key.participant,c=qe(t),l=a.sender?.pushName;!c&&(d==null||d.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&gi({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof d=="string"&&(e.selfJid.length>0&&un(d,e.selfJid)||e.selfLid!=null&&un(d,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&gi(a.sender,r)&&(r.pn!=null&&(a.key.participant=r.pn),r.lid!=null&&(a.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,f=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),v=Ct(f)??"";return Ce(f,e,Ae(u),v,Et(f,e),s,!1)}catch{return null}},ur=n=>St(Pt(n)).mentionedJids,Lc=n=>{try{return au.jidNormalizedUser(n)}catch{return n}},Ai=(n,e)=>n.map(t=>{let r=Lc(t);return e.lidMap?.get(r)??r}),fi=n=>(n.split("@")[0]??"").split(":")[0]??"",Nc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[fi(s),fi(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},Ce=(n,e,t,r,s,i,o=true)=>{let a=n.key;if(a==null)return null;let d=Z(a,n.pushName??void 0);if(d===null)return null;let c=hi(a);if(c.length===0)return null;let l=Pt(n),u=qe(c),f=c.endsWith("@broadcast"),v=c.endsWith("@newsletter"),S=l?.isForwarded===true||(l?.forwardingScore??0)>0,T=kc(n),O=Tc(n,l),A=e.channelId??"",b=e.receiverId??"",x=e.prefixes??[],F=i??(()=>u?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(d.pushName??null)),z=e.resolveReceiverName??(()=>Promise.resolve(null)),xe=()=>_c(l,e,c,d,F,a.fromMe===true),ze=c.length>0?c:d.pn??d.jid,Oe=(k,D)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(ze,k,D,n),Ye=k=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(a,k),Nn=Ai(St(l).mentionedJids,e),I=Nc(r,e.lidMap),Qe=Oc(l),y=Rc(n),w={message:n,key:a,channelId:A,receiverId:b,selfJid:e.selfJid,text:I,chatType:t,sender:d,mentions:Nn,isViewOnce:T,isEphemeral:O,isForwarded:S,isBroadcast:f,isNewsletter:v,isOld:e.isOld===true,prefixes:x,forwardCount:Ic(l?.forwardingScore,0),ephemeralDuration:Si(n,l),addressingMode:a.addressingMode==="lid"?"lid":"pn",mentionedGroups:xc(l),...Qe!==void 0?{ad:Qe}:{},...y!==void 0?{business:y}:{},...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:F,resolveReceiverName:z,resolveReplied:xe,reply:Oe,react:Ye},E={...s!==void 0?{...w,media:s}:w,verified:o};return dr(e.citationConfig!==void 0?{...E,citationConfig:e.citationConfig}:E)},Dc=["image","video","audio","document","sticker"],Ci=(n,e,t)=>{let r=yi(n),s=Pc(r,e);if(s===null)return null;let i=ln(r,e,t.logger),o=oi(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:_(s.fileLength),ptt:s.ptt===true,isAnimated:s.isAnimated===true||s.gifPlayback===true,duration:_(s.seconds),width:_(s.width),height:_(s.height),pages:_(s.pageCount),thumbnail:s.jpegThumbnail!=null?Buffer.from(s.jpegThumbnail):null,buffer:async()=>(await i()).buffer,stream:o}},Et=(n,e)=>{let t=m(n.message);if(t==null)return;let r=Ae(n.message);return Dc.includes(r)?Ci(n,r,e)??void 0:vi(Ke(t))??void 0},Ei=(n,e)=>{if(m(n.message)==null)return null;let r=Ae(n.message),s=Et(n,e),i=Ct(n)??"";return i===""&&s===void 0?null:Ce(n,e,r,i,s)},Pi=(n,e)=>{let t=m(n.message);if(t==null)return null;let r=Ke(t),s=wi(r),i=vi(r)??void 0;return s===null&&i===void 0?null:Ce(n,e,Ae(n.message),s??"",i)},kt=(n,e,t)=>{let r=Ci(e,n,t);return r===null?null:Ce(e,t,n,r.caption??"",r)},ki=(n,e)=>kt("image",n,e),Ti=(n,e)=>kt("video",n,e),Ii=(n,e)=>kt("audio",n,e),xi=(n,e)=>kt("document",n,e),Oi=(n,e)=>kt("sticker",n,e),un=(n,e)=>{try{return au.jidNormalizedUser(n)===au.jidNormalizedUser(e)}catch{return n===e}},Ri=(n,e)=>{if(n.key==null)return null;let r=Pt(n),s=St(r).mentionedJids;if(s.length===0)return null;let i=Ai(s,e);if(!(i.some(u=>un(u,e.selfJid))||e.selfLid!=null&&s.some(u=>un(u,e.selfLid)))||m(n.message)==null)return null;let d=Ct(n)??"",c=Et(n,e),l=Ce(n,e,Ae(n.message),d,c);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},_i=(n,e)=>{let t=n.key;if(t==null)return null;let r=hi(t);if(r.length===0||!qe(r))return null;let{mentionAll:s}=St(Pt(n));if(!s||m(n.message)==null)return null;let o=Ct(n)??"",a=Et(n,e),d=Ce(n,e,Ae(n.message),o,a);return d===null?null:{...d,isMentionAll:true,selfJid:e.selfJid}};var Ee="[zaileys]",Bc="The saved session looks invalid or corrupted (connection keeps closing before it authenticates). Delete the auth folder (default: ./.zaileys) and run again to scan a fresh QR / request a new pairing code.";function Ni(n){switch(n.kind){case "connecting":return `${Ee} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${Ee} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${Ee} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${Ee} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${Ee} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
|
|
13
|
+
${Ee} ${Bc}`:t}case "disconnect":return n.willReconnect?null:`${Ee} Disconnected (${n.reason}).`;default:return null}}var Li=false,Fc=["Closing session:","Closing open session","Closing stale open session","Opening session:","Removing old closed session","Migrating session to:","Session already closed","Decrypted message with closed session","Failed to decrypt message with any known session","Session error:"],Wc=n=>typeof n[0]=="string"&&Fc.some(e=>n[0].startsWith(e));function Di(){if(Li)return;Li=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{Wc(r)||t(...r);};};n("info"),n("warn"),n("error");}var g=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysStoreError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var jc="./.zaileys/auth",qc=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),Pe=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",$c=384,Bi=448,Kc=async n=>{try{let e=await fs$1.promises.open(n,"r");try{await e.sync();}finally{await e.close();}}catch{return}},It=class{basePath;get directory(){return this.resolvedBase}resolvedBase;closed=false;constructor(e){this.basePath=e?.basePath??jc,this.resolvedBase=H__default.default.resolve(this.basePath);}assertContained(e){let t=H__default.default.resolve(e);if(t!==this.resolvedBase&&!t.startsWith(this.resolvedBase+H__default.default.sep))throw new g("STORE_WRITE_FAILED",`refusing to touch ${e}: outside ${this.basePath}`);return t}signal={read:async(e,t)=>{this.assertOpen();let r={};return await Promise.all(t.map(async s=>{let i=this.signalPath(e,s);try{let o=await fs$1.promises.readFile(i,"utf8");r[s]=JSON.parse(o,au.BufferJSON.reviver);}catch(o){if(Pe(o))return;throw new g("STORE_READ_FAILED",`failed to read ${i}`,{cause:o})}})),r},write:async e=>{this.assertOpen();let t=[];for(let r of Object.keys(e)){let s=e[r];if(!s)continue;let i=this.signalDir(r);await fs$1.promises.mkdir(i,{recursive:true,mode:Bi});for(let o of Object.keys(s)){let a=s[o],d=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(d).catch(c=>{if(!Pe(c))throw new g("STORE_WRITE_FAILED",`failed to unlink ${d}`,{cause:c})})):a!==void 0&&t.push(this.atomicWrite(d,JSON.stringify(a,au.BufferJSON.replacer)));}}await Promise.all(t);},delete:async(e,t)=>{this.assertOpen(),await Promise.all(t.map(async r=>{let s=this.signalPath(e,r);try{await fs$1.promises.unlink(s);}catch(i){if(!Pe(i))throw new g("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen();let e;try{e=await fs$1.promises.readdir(this.basePath);}catch(t){if(Pe(t))return;throw new g("STORE_WRITE_FAILED",`failed to read ${this.basePath}`,{cause:t})}await Promise.all(e.filter(t=>!(t.startsWith("creds.revoked-")&&t.endsWith(".json"))).map(t=>fs$1.promises.rm(H__default.default.join(this.basePath,t),{recursive:true,force:true})));},close:async()=>{this.closed=true;},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>{this.assertOpen();let e;try{e=await fs$1.promises.readFile(this.credsPath(),"utf8");}catch(t){if(Pe(t))return;throw new g("STORE_READ_FAILED","failed to read creds.json",{cause:t})}try{return JSON.parse(e,au.BufferJSON.reviver)}catch(t){let r=await this.newestBackup();if(r!==void 0)return r;throw new g("STORE_READ_FAILED","creds.json is corrupt",{cause:t})}},writeCreds:async e=>{this.assertOpen(),await fs$1.promises.mkdir(this.basePath,{recursive:true,mode:Bi}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,au.BufferJSON.replacer));},backupCreds:async()=>{this.assertOpen();let e=new Date().toISOString().replace(/[:.]/g,"-");try{await fs$1.promises.copyFile(this.credsPath(),H__default.default.join(this.basePath,`creds.revoked-${e}.json`));}catch(t){if(!Pe(t))throw new g("STORE_WRITE_FAILED","failed to back up creds.json",{cause:t})}},readBackupCreds:async()=>(this.assertOpen(),this.newestBackup()),deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!Pe(e))throw new g("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return H__default.default.join(this.basePath,"creds.json")}async newestBackup(){let e;try{e=await fs$1.promises.readdir(this.basePath);}catch{return}let t=e.filter(r=>r.startsWith("creds.revoked-")&&r.endsWith(".json")).sort();for(let r of t.reverse())try{let s=await fs$1.promises.readFile(H__default.default.join(this.basePath,r),"utf8");return JSON.parse(s,au.BufferJSON.reviver)}catch{continue}}signalDir(e){return H__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return this.assertContained(H__default.default.join(this.signalDir(e),`${qc(t)}.json`))}async atomicWrite(e,t){let r=H__default.default.dirname(e),s=H__default.default.join(r,`tmp-${crypto.randomBytes(8).toString("hex")}`);try{let i=await fs$1.promises.open(s,"w",$c);try{await i.writeFile(t,"utf8"),await i.sync();}finally{await i.close();}await fs$1.promises.rename(s,e),await Kc(r);}catch(i){throw await fs$1.promises.unlink(s).catch(()=>{}),new g("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:i})}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","FileAuthStore is closed")}};function Fi(n,e){let t=n.signal,s=au.makeCacheableSignalKeyStore({get:(o,a)=>t.read(o,a),set:o=>t.write(o),clear:()=>t.clear()},e?.logger??void 0),i={read:async(o,a)=>await s.get(o,[...a]),write:async o=>{await s.set(o);},delete:async(o,a)=>{await t.delete(o,a);let d={},c={};for(let l of a)c[l]=null;d[o]=c,await s.set(d);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close(),...t.reopen!==void 0?{reopen:()=>t.reopen.call(t)}:{}};return {creds:n.creds,signal:i}}function Wi(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);}}}var Jc=429;function Ui(n){if(n===Jc)return "rate-limited";switch(n){case au.DisconnectReason.loggedOut:return "logged-out";case au.DisconnectReason.forbidden:return "forbidden";case au.DisconnectReason.connectionLost:return "connection-lost";case au.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case au.DisconnectReason.connectionClosed:return "connection-closed";case au.DisconnectReason.connectionReplaced:return "connection-replaced";case au.DisconnectReason.badSession:return "bad-session";case au.DisconnectReason.unavailableService:return "unavailable-service";case au.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function xt(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function pn(n){return n==="rate-limited"}var pr=Object.freeze(["logged-out"]);function ji(n,e=pr){return e.includes(n)}function Ly(n){return !xt(n)}var mn={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},Vc=3e5;function qi(n={}){let e=n.enabled??mn.enabled,t=n.maxQrAttempts??mn.maxQrAttempts,r=n.maxPairingAttempts??mn.maxPairingAttempts,s=n.pairingCooldownMs??mn.pairingCooldownMs,i=0,o=0,a=0,d=f=>f<=0?0:Math.min(s*f,Vc);return {evaluate:(f,v)=>{if(!e)return {allowed:true,waitMs:0,attempts:f==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(f==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let S=d(o),T=v-a;return o>0&&T<S?{allowed:false,reason:"cooldown",waitMs:S-T,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(f,v)=>{f==="pairing"?(o+=1,a=v):i+=1;},reset:()=>{i=0,o=0,a=0;},get enabled(){return e},get qrAttempts(){return i},get pairingAttempts(){return o}}}var Hc=/[\s\-()+]/g;function zc(n){return typeof n!="string"?"":n.replace(Hc,"")}function Yc(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=zc(n);if(!/^\d+$/.test(e))throw new Error("phoneNumber must be E.164 with country code");if(e.length<8||e.length>15)throw new Error("phoneNumber must be E.164 with country code");return e}function $i(n){let e=Yc(n.phoneNumber),t=n.ttlMs??6e4;return {phoneNumber:e,async requestCode(r){let s;try{s=await r.requestPairingCode(e);}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`failed to request pairing code: ${o}`)}return {code:s,expiresAt:Date.now()+t}}}}function Xc(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{Qc__default.default.generate(n,{small:true},t=>e(t));})}async function Ki(n,e=t=>{process.stdout.write(t);}){let t=await Xc(n);e(t+`
|
|
14
|
+
`);}var Ge={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Gi(n,e){let t=n?.enabled??Ge.enabled,r=n?.maxAttempts??Ge.maxAttempts,s=n?.initialDelayMs??Ge.initialDelayMs,i=n?.maxDelayMs??Ge.maxDelayMs,o=n?.jitterFactor??Ge.jitterFactor,a=n?.rateLimitedDelayMs??Ge.rateLimitedDelayMs,d=e?.random??Math.random,c=0;return {next:f=>{if(!t||xt(f))return null;let v=c+1;if(v>r)return null;if(c=v,pn(f))return {attempt:v,delayMs:a};let S=Math.pow(2,v-1),T=Math.min(i,s*S),O=1+(d()*2-1)*o,A=T*O,b=Math.min(i,Math.max(0,A));return {attempt:v,delayMs:Math.round(b)}},reset:()=>{c=0;},get attempts(){return c}}}var Zc={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function Ji(n="idle"){let e=n,t=new Set,r=s=>Zc[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var gn=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,fn=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=gn(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(gn(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...d)=>{let l=d[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let u=this.messages.get(gn(l.key));if(u){let f={...u,...l.update};this.saveMessage(f).catch(()=>{});}}},s=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveChat(l).catch(()=>{});},i=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c){let f={...this.chats.get(l.id)??{},...l};this.saveChat(f).catch(()=>{});}},o=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveContact(l).catch(()=>{});},a=(...d)=>{let c=d[0];if(c?.presences)for(let l of Object.keys(c.presences)){let u=c.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[d,c]of this.listeners)e.ev.on(d,c);}async deleteMessage(e){this.assertOpen();let t=gn(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let d=this.messages.get(a);d&&i.push(d);}i.sort((a,d)=>Number(d.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,d)=>{let c=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&c<e.olderThan||e.maxPerChat!==void 0&&d>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}async reopen(){this.closed=false;}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","MemoryMessageStore is closed")}};var tl=["silent","fatal","error","warn","info","debug","trace"];function nl(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":tl.includes(e)?e:"silent"}var rl=["creds","*.creds","noiseKey","*.noiseKey","signedIdentityKey","*.signedIdentityKey","signedPreKey","*.signedPreKey","pairingEphemeralKeyPair","*.pairingEphemeralKeyPair","accessToken","*.accessToken","appSecret","*.appSecret","verifyToken","*.verifyToken","password","*.password","authorization","*.authorization","headers.authorization","headers.Authorization"];function sl(n={}){let e=nl(n.level),t=el__default.default({level:e,redact:{paths:[...rl],censor:"[redacted]"}});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Vi=["debug","info","warn","error","fatal"];function il(n){if(n===null||typeof n!="object")return false;for(let e of Vi)if(typeof n[e]!="function")return false;return true}function Ot(){}function ol(n){let e={debug:Ot,info:Ot,warn:Ot,error:Ot,fatal:Ot};for(let t of Vi){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function mr(n,e){return n===void 0?e??sl():il(n)?n:ol(n)}var Hi=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),hn,dl=()=>{if(hn!==void 0)return hn;let n=au.proto?.Message?.ProtocolMessage?.Type;return hn=new Set(Hi.map(e=>n?.[e]).filter(e=>typeof e=="number")),hn},cl=n=>{let r=n.message?.protocolMessage?.type;return typeof r=="number"||typeof r=="string"?r:void 0},ll=n=>{let e=cl(n);return e===void 0?false:typeof e=="string"?Hi.includes(e):dl().has(e)},ul=n=>{let e=n.messageStubParameters;return Array.isArray(e)?e.some(t=>typeof t=="string"&&t.startsWith("requestId:")):false},zi=n=>{if(n.requestId!=null)return {...n,messages:[]};let e=n.messages.filter(t=>{let r=t.key?.fromMe===true;return !(r&&ul(t)||!r&&ll(t))});return {...n,messages:e}};var pl=new Set(["offer","ringing"]),ml=new Set(["timeout","reject","accept","terminate"]),Yi=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},Qi=n=>{if(typeof n.id!="string"||n.id.length===0||!pl.has(n.status))return null;let e=Vs(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Yi(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},Xi=n=>typeof n.id!="string"||n.id.length===0||!ml.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Yi(n.date),status:n.status};var G=n=>typeof n=="string"&&n.length>0,gl=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},Zi=(n,e,t)=>n.filter(r=>G(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return G(i)&&(s.participantAlt=i),G(e)&&(s.authorPn=e),G(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),eo=n=>G(n?.id)?{groupId:n.id,update:gl(n),timestamp:Date.now()}:null,to=n=>{if(!G(n?.groupId)||!G(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return G(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},fl=new Set(["add","invite","invite-link"]),hl=new Set(["remove","leave"]),no=n=>{if(!G(n?.id)||!fl.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Zi(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return G(n.author)&&(t.by=n.author),t},ro=n=>{if(!G(n?.id)||!hl.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Zi(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return G(n.author)&&(t.by=n.author),t};var yl=["quick_reply","cta_url","cta_call","button_click"],wl=["list_select","single_select"],ne=n=>typeof n=="string"&&n.length>0,io=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return Z(n.key,e)},oo=n=>$e(n.messageTimestamp)??0,ao=(n,e)=>{if(!ne(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},yn=(n,e)=>{for(let t of e){let r=n[t];if(ne(r))return r}},co=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&ne(r.selectedButtonId))return gr(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&ne(s.selectedId))return gr(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&ne(i.name)&&yl.includes(i.name)){let o=ao(i.paramsJson,e.logger);if(!o)return null;let a=yn(o,["id","button_id"]);return a===void 0?null:gr(n,a,yn(o,["display_text"])??null)}return null},gr=(n,e,t)=>{let r=io(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:oo(n)};return ne(t)&&(s.buttonText=t),s},lo=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(ne(s))return so(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&ne(i.name)&&wl.includes(i.name)){let o=ao(i.paramsJson,e.logger);if(!o)return null;let a=yn(o,["row_id","id"]);return a===void 0?null:so(n,a,yn(o,["title"])??null)}return null},so=(n,e,t)=>{let r=io(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:oo(n)};return ne(t)&&(s.title=t),s};var vl=new Set(["available","unavailable","composing","recording","paused"]),Ml=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,uo=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},fr=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:Ml(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},po=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!vl.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Rt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var ke=(n,e)=>{let t=$e(n);return t===null?e:t},bl=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(d=>d?.messageText).filter(d=>typeof d=="string"&&d.length>0);if(a.length>0)return a.join(`
|
|
15
|
+
`)}return ""},Al=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],go=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=Z(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:ke(t.senderTimestampMs,0)}},fo=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==au.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=Z(n.key,e.pushName);return s===null?null:{key:r,newContent:bl(t.editedMessage),editedAt:ke(n.update.messageTimestamp,0),sender:s}},ho=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==au.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=Z(n.key,e.pushName);if(s===null)return null;let i=je(n.key.remoteJid),o=je(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:ke(n.update.messageTimestamp,0)}},Cl=async(n,e,t)=>{if(e.length===0||t.resolvePoll==null)return [];let r=n.id,s=n.remoteJid;if(typeof r!="string"||typeof s!="string")return [];let o=(await t.resolvePoll(r,s))?.message,a=o?.pollCreationMessage?.options??o?.pollCreationMessageV2?.options??o?.pollCreationMessageV3?.options??[],d=new Map;for(let l of a){let u=l?.optionName??"";d.set(crypto.createHash("sha256").update(Buffer.from(u)).digest("hex").toUpperCase(),u);}let c=[];for(let l of e){let u=d.get(l.toUpperCase());u!==void 0&&c.push(u);}return c},yo=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=Z(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;if(!i)return null;let o=Al(t.vote?.selectedOptions);return {pollKey:i,selectedOptions:o,voter:s,timestamp:ke(t.senderTimestampMs,ke(n.update.messageTimestamp,0)),options:()=>Cl(i,o,e)}}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:ke(r.senderTimestampMs,ke(n.update.messageTimestamp,0)),options:()=>Promise.resolve([])}:null}return null};var wn=n=>Array.isArray(n)?n:[],El=3e3,Pl=128,Mo=8,kl=256,Tl=2e4,Il=1e4,xl=2e3,Ol=600*1e3,Rl=500,_l=300*1e3,Ll=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Nl=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function hr(n,e,t){let r=[],s=new lruCache.LRUCache({max:Rl,ttl:_l}),i=t.groupMetadata!=null?y=>{let w=s.get(y);if(w!==void 0)return w;let h=t.groupMetadata;if(h==null)return Promise.resolve(null);let E=h(y).then(k=>k?.subject??null).catch(()=>(s.delete(y),null));return s.set(y,E),E}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},d={selfJid:t.selfJid,...t.resolveQuoted!=null?{resolvePoll:t.resolveQuoted}:{}},c=(y,w)=>{let h=(...E)=>{try{w(E[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,h),r.push(()=>e.ev.off(y,h));},l=(y,w)=>{I(()=>Ei(y,w),h=>n.emit("message",h)),I(()=>Pi(y,w),h=>n.emit("text",h)),I(()=>ki(y,w),h=>n.emit("image",h)),I(()=>Ti(y,w),h=>n.emit("video",h)),I(()=>Ii(y,w),h=>n.emit("audio",h)),I(()=>xi(y,w),h=>n.emit("document",h)),I(()=>Oi(y,w),h=>n.emit("sticker",h)),I(()=>Ri(y,w),h=>n.emit("mention",h)),I(()=>_i(y,w),h=>n.emit("mention-all",h)),I(()=>co(y,a),h=>n.emit("button-click",h)),I(()=>lo(y,a),h=>n.emit("list-select",h));},u=y=>{if(typeof y!="string"||y.length===0)return null;let w;try{w=au.jidNormalizedUser(y);}catch{w=y;}return dn(w)?w:null},f=new lruCache.LRUCache({max:xl,ttl:Ol}),v=(y,w=false)=>{let h=new Set,E=[y.key?.participant,y.key?.remoteJid,t.selfJid];for(let k of w?E:[...E,...ur(y)]){let D=u(k);if(D!=null&&h.add(D),h.size>=Pl)break}return [...h]},S=new Map,T=(y,w)=>{let h=S.get(w);if(h!==void 0)return h;let E=(async()=>{try{let k=await Ll(Promise.resolve(y(w)),El);if(k==null||k.length===0)return null;let D=k;try{D=au.jidNormalizedUser(k);}catch{D=k;}return f.set(w,D),D}catch(k){return t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw"),null}finally{S.delete(w);}})();return S.set(w,E),E},O=t.maxPendingResolutions??kl,A=t.maxQueuedResolutions??Tl,b=0,x=0,F=[],z=0,xe=0,ze=y=>{let w=y.message,h=w?.conversation,E=w?.extendedTextMessage,k=typeof h=="string"?h:typeof E=="object"&&typeof E?.text=="string"?E.text:"";return 1+Math.floor(ur(y).length/32)+Math.floor(k.length/8192)},Oe=y=>{let w=new Map;for(let h of y){let E=f.get(h);if(E===void 0)return;w.set(h,E);}return w},Ye=(y,w)=>{let h=k=>{b+=1,w(k).finally(()=>{b-=1;let D=F.shift();D!==void 0&&(x-=D.weight,D.start());});};if(b<O){h(false);return}if(x+y<=A){x+=y,F.push({weight:y,start:()=>h(true)});return}z+=1;let E=Date.now();E-xe>=Il&&(t.logger?.warn({shed:z,pending:b,queuedWeight:x},"inbound pipeline: overloaded, shed messages waiting on LID resolution"),z=0,xe=E);},Nn=async y=>{let w=t.resolveLidToPn;if(w==null||y.length===0)return;let h=new Map,E=[];for(let k of y){let D=f.get(k);D!==void 0?h.set(k,D):E.push(k);}for(let k=0;k<E.length;k+=Mo){let D=E.slice(k,k+Mo);await Promise.all(D.map(async Jt=>{let ge=await T(w,Jt);ge!==null&&h.set(Jt,ge);}));}return h.size>0?h:void 0},I=(y,w)=>{let h;try{h=y();}catch(E){t.logger?.warn(E,"inbound pipeline: decoder threw");return}h!=null&&w(h);};c("messages.upsert",y=>{let w=zi(y),h=w.type==="append"?{...o,isOld:!0}:o;for(let E of w.messages){if(t.ignoreMe===!0&&E.key?.fromMe===!0)continue;let k=t.resolveLidToPn!=null?v(E):[];if(k.length===0){l(E,h);continue}let D=Oe(k)??(b>=O?Oe(v(E,!0)):void 0);if(D!==void 0){l(E,{...h,lidMap:D});continue}Ye(ze(E),Jt=>Nn(Jt?v(E,!0):k).then(ge=>l(E,ge!=null?{...h,lidMap:ge}:h)).catch(ge=>{t.logger?.warn(ge,"inbound pipeline: deferred lid resolve emit failed");}));}}),c("messages.update",y=>{for(let w of wn(y))I(()=>fo(w,d),h=>n.emit("edit",h)),I(()=>ho(w,d),h=>n.emit("delete",h)),I(()=>yo(w,d),h=>n.emit("poll-vote",h));}),c("messages.reaction",y=>{for(let w of wn(y))I(()=>go(w,d),h=>n.emit("reaction",h));}),c("groups.update",y=>{for(let w of wn(y))I(()=>eo(w),h=>n.emit("group-update",h));}),c("group-participants.update",y=>{let w=y;I(()=>no(w),h=>n.emit("group-join",h)),I(()=>ro(w),h=>n.emit("group-leave",h));}),c("group.member-tag.update",y=>{I(()=>to(y),w=>n.emit("member-tag",w));}),c("call",y=>{for(let w of wn(y))I(()=>Qi(w),h=>n.emit("call-incoming",h)),I(()=>Xi(w),h=>n.emit("call-ended",h));}),c("messaging-history.status",y=>{I(()=>uo(y),w=>n.emit("history-sync",w));}),c("presence.update",y=>{let w=(()=>{try{return po(y)}catch(h){return t.logger?.warn(h,"inbound pipeline: decodePresence threw"),[]}})();for(let h of w)n.emit("presence",h);}),c("connection.update",y=>{let w=Nl(y);w!==null&&I(()=>fr({source:"connection-update",reachoutTimeLock:w}),h=>n.emit("limited",h));}),c("message-capping.update",y=>{I(()=>fr({source:"message-capping",capInfo:y}),w=>n.emit("limited",w));}),c("newsletter.reaction",y=>{I(()=>Rt({source:"reaction",payload:y}),w=>n.emit("newsletter",w));}),c("newsletter.view",y=>{I(()=>Rt({source:"view",payload:y}),w=>n.emit("newsletter",w));}),c("newsletter-participants.update",y=>{I(()=>Rt({source:"participants",payload:y}),w=>n.emit("newsletter",w));}),c("newsletter-settings.update",y=>{I(()=>Rt({source:"settings",payload:y}),w=>n.emit("newsletter",w));});let Qe=false;return {detach(){if(!Qe){Qe=true;for(let y of r)y();r.length=0;}}}}var vn=class{inner=new events.EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Bl,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Bl=Symbol("zaileys.typed-ee.tag");var _t=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},C=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function yr(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new C("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new C("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Mn="v23.0",wr="https://graph.facebook.com",So=3,Fl=500,Wl=n=>new Promise(e=>setTimeout(e,n));function Sn(n,e){let t=n.baseUrl??wr,r=n.apiVersion??Mn,s=Wl,i=d=>d.split("?")[0]===d?d.split("/").map(c=>encodeURIComponent(c)).join("/"):`${(d.split("?")[0]??"").split("/").map(c=>encodeURIComponent(c)).join("/")}?${d.slice(d.indexOf("?")+1)}`,o=d=>`${t}/${r}/${i(d)}`,a=async(d,c)=>{let l;for(let u=1;u<=So;u++){let f;try{f=await fetch(o(d),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(b){throw new C("REQUEST_FAILED","graph request failed (network)",{cause:b})}if(f.ok)return await f.json().catch(()=>({}));let v=await f.json().catch(()=>({})),S=v.error?.message??`http ${f.status}`,T=v.error?` (code ${v.error.code??"?"}${v.error.error_subcode?`/${v.error.error_subcode}`:""})`:"";if(f.status===401||f.status===403)throw new C("AUTH",`graph auth rejected: ${S}${T}`);let O=f.status===429||f.status>=500,A=f.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(l=new C(A,`graph request failed: ${S}${T}`),!O)throw l;u<So&&await s(Fl*2**(u-1));}throw l??new C("REQUEST_FAILED","graph request failed")};return {url:o,get:d=>a(d,{method:"GET"}),post:(d,c)=>a(d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(d,c)=>a(d,{method:"POST",body:c}),delete:(d,c)=>a(d,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var bo=n=>n.split("@")[0]??n,le=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,re=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:bo(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function Ao(n,e,t){let r=e;if(typeof r.text=="string")return {...re(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...re(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...re(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(d=>typeof d.vcard=="string"?Ul(d.vcard):null).filter(d=>d!==null);if(a.length>0)return {...re(n,"contacts",t),contacts:a}}return null}function Ul(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let d=a.slice(2).split(";");s=(d[0]??"").trim(),r=(d[1]??"").trim();}if(a.startsWith("TEL")){let d=a.indexOf(":");if(d>0){let c=a.slice(d+1).trim(),l=/waid=([0-9]+)/.exec(a);c.length>0&&i.push({phone:c,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function Lt(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:le(bo(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var jl=["image","video","audio","document","sticker"];function Co(n){let e=n;for(let t of jl){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function Eo(n,e,t){let r=t.mimetype??await Re(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new C("REQUEST_FAILED","media upload returned no id");return i.id}function Po(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var ql=["image","video","audio","document","sticker"],$l=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},bn=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,Kl=n=>{for(let e of ql){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},Gl=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},Jl=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},Vl=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
|
|
16
16
|
`);return {displayName:i,vcard:`BEGIN:VCARD
|
|
17
17
|
VERSION:3.0
|
|
18
18
|
FN:${i}${o?`
|
|
19
19
|
${o}`:""}
|
|
20
|
-
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Vl=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:le(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Hl=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:$l(n)??Kl(n)??Gl(n)??Jl(n);if(t===null)return null;let r=Vl(t,n),s=Sn(e,n.from);return {key:{id:n.id,remoteJid:le(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},zl=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?le(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},Yl=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Sn(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:le(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},Ql=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Sn(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:le(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},Xl=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=le(n.from),s=Sn(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function Eo(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=ql(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=Xl(l,c);if(u){t.push(u);continue}let f=Yl(l,c);if(f){i.push(f);continue}let v=Ql(l,c);if(v){o.push(v);continue}let b=Hl(l,c);b&&e.push(b);}for(let l of c.statuses??[]){let u=zl(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Po=3,wr=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function ko(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=wr(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(f=>({id:f.id??"",title:f.title??"",description:f.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Po)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Po} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=wr(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?wr(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var eu=6e4,bn=128*1024*1024,tu=[".fbcdn.net",".fbsbx.com",".facebook.com",".whatsapp.com",".whatsapp.net",".cdninstagram.com"],nu=n=>{let e;try{e=new URL(n);}catch{throw new C("REQUEST_FAILED","media url is not a valid url")}if(e.protocol!=="https:")throw new C("REQUEST_FAILED",`refusing a non-https media url: ${e.protocol}`);let t=e.hostname.toLowerCase();if(!tu.some(s=>t===s.slice(1)||t.endsWith(s)))throw new C("REQUEST_FAILED",`refusing to send credentials to ${t}`)},Je=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=Mn(e);}get apiVersion(){return this.options.apiVersion??vn}get baseUrl(){return this.options.baseUrl??yr}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich content (rich: true and htmlApp()) is WhatsApp-Web-only and not supported on the cloud provider. Send the text with send().text() \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=ko(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...re(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=Lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...re(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=Lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...re(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=Lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;nu(t.url);let r=new AbortController,s=setTimeout(()=>r.abort(),eu),i;try{i=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`},redirect:"error",signal:r.signal});}catch(c){throw new C("REQUEST_FAILED","media download failed",{cause:c})}finally{clearTimeout(s);}if(!i.ok)throw new C("REQUEST_FAILED",`media download failed (${i.status})`);let o=Number(i.headers?.get?.("content-length")??"0");if(Number.isFinite(o)&&o>bn)throw new C("REQUEST_FAILED",`media exceeds ${bn} bytes`);let a=Buffer.from(await i.arrayBuffer());if(a.byteLength>bn)throw new C("REQUEST_FAILED",`media exceeds ${bn} bytes`);let d=t.mime_type??await Re(a);return {buffer:a,mime:d,size:a.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=Eo(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=So(e,t,r);if(s===null){let d=bo(t);if(d){let c=await Ao(this.graph,this.options.phoneNumberId,d);s={...re(e,d.kind,r),[d.kind]:Co(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=Lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var Nt=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=Mn(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var su=(n,e)=>{let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?false:crypto.timingSafeEqual(t,r)},iu=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function vr(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o!==null&&su(o,n.verifyToken)?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0){if(!iu(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401})}else if(n.allowUnsigned!==true)return new Response("webhook requires appSecret (or allowUnsigned for local dev)",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var cu="default",lu="qr",xo=6e4,uu=2,pu=3e3,mu="29829202653362039",gu=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},fu=/^[A-Za-z0-9_-]{1,64}$/,hu=(n,e)=>{let t=new Set(Ur().deniedDirs??[]);for(let r of n?.deniedDirs??[])t.add(r);e instanceof It&&t.add(e.directory),Wr({...n?.maxBytes!==void 0?{maxBytes:n.maxBytes}:{},...n?.allowLocalPaths!==void 0?{allowLocalPaths:n.allowLocalPaths}:{},...n?.allowPrivateNetwork!==void 0?{allowPrivateNetwork:n.allowPrivateNetwork}:{},deniedDirs:[...t]}),Rr({...n?.maxImagePixels!==void 0?{maxImagePixels:n.maxImagePixels}:{},...n?.maxConcurrentFfmpeg!==void 0?{maxConcurrent:n.maxConcurrentFfmpeg}:{},...n?.maxQueuedFfmpeg!==void 0?{maxQueued:n.maxQueuedFfmpeg}:{},...n?.ffmpegQueueTimeoutMs!==void 0?{queueTimeoutMs:n.ffmpegQueueTimeoutMs}:{}});},yu=n=>{if(!fu.test(n))throw new Error(`invalid sessionId ${JSON.stringify(n)}: use 1-64 characters from A-Z a-z 0-9 _ -`);return n},Oo=class extends wn{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=Ki();reconnectStrategy;authGuard;clearAuthReasons;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;storesClosedByDisconnect=false;chatExpiration=new Map;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:pr(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?hr(e.cloud):void 0,this.sessionId=yu(e.sessionId??cu),this.logger=pr(e.logger),this.authType=e.authType??lu,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&Li(),this.on("message",r=>this.rememberChatExpiration(r)),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new It({basePath:`./.zaileys/auth/${this.sessionId}`}),hu(e.media,this.auth),this.store=e.store??new gn,this.reconnectStrategy=$i(this.reconnectOptions),this.authGuard=Ui(e.authGuard),this.clearAuthReasons=e.session?.clearAuthOn??ur,this.operationGuard=sr(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new be({perSec:t}):void 0,this.commandPrefixes=wu(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new bt(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&Ne.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof ou.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=ou.fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=_i(e);t&&process.stderr.write(`${t}
|
|
21
|
-
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new _t(e)}get group(){return this.assertWebProvider("group"),this._group??=new ot(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new at(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new dt(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new ct(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new lt(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new ut(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new pt(()=>this._socket,e=>it(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new mt(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new wt(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),ir(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new vt({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}async connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)throw new Error('phoneNumber is required when authType is "pairing"');if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return;if(this._socket){for(let d of this.listenerCleanup)d.off();this.listenerCleanup=[],this._socket=void 0;}this.storesClosedByDisconnect&&await this.reopenStores();let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Di(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t;try{t=await this.auth.creds.readCreds();}catch(d){let c=d instanceof Error?d:new Error(String(d));throw this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.logger.error(c,"failed to read stored credentials; aborting connect to protect the session"),c}this.credsLoadedAtConnect=!!t;let r=Object.assign({},t??ou.initAuthCreds());this.creds=r;let s=Bi(this.auth.signal,this.logger),i={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xo,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:r,keys:s},logger:this.logger,getMessage:d=>this.resolveMessageForResend(d),patchMessageBeforeSending:this.patchOutgoing},o=new Promise((d,c)=>{let l=this.connectResolve,u=this.connectReject;this.connectResolve=()=>{l?.(),d();},this.connectReject=f=>{u?.(f),c(f);};}),a=ou__default.default(i);return this._socket=a,this.store.bind(a),this.wireSocket(a),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Je(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=fr(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return vr({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},...e.allowUnsigned===true?{allowUnsigned:true}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose(),this._presence?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.storesClosedByDisconnect=true,this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}await this.quarantineCreds();try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new gt).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=er({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("message",r),()=>this.off("message",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=wi(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{return ((await this.group.metadata(e)).participants??[]).some(s=>{let i=s;return [s.id,i.phoneNumber,i.jid].filter(a=>typeof a=="string").some(a=>or(a,t))&&s.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,client:this,send:s=>this.send(s??t.roomId??t.senderId),reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new j("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||it(e)?ae.create(t,e,void 0,r,s):ae.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new st(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await Jn(this.requireSocket(),e,t);}async react(e,t){return Vn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new N("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new Nt(this.cloudOptions,()=>this.cloudTransport??=new Je(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return Hn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),on(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),on(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Bs(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return zn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{if(this.creds?.registered===true){let d="registered"in o&&o.registered!==true,c="me"in o&&o.me==null;if(d||c){this.logger.error({sessionId:this.sessionId},"refusing a creds update that would de-register the stored session");return}}let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Ks(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.creds?.registered===true){let s=new Error("WhatsApp asked to pair again while a registered session is stored; aborting to protect it");this.logger.error({sessionId:this.sessionId},s.message),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:s}),this.disconnect();return}if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=ji({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await qi(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xo});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=fr(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Mt({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new ft({client:this,logger:this.logger}),this.pluginLoader=new ht({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:ou.S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:mu},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of gu(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return cn(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=vu(e?.error),r=Fi(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<uu;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),Wi(r,this.clearAuthReasons)&&!i){await this.quarantineCreds();try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!xt(r))&&!this.authExhausted){un(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:pu}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}async reopenStores(){let e=this.auth.signal.reopen,t=this.store.reopen;if(typeof e!="function"||typeof t!="function")throw new Error("this auth or message store adapter cannot be reopened after disconnect(); implement reopen() or create a new Client");await e.call(this.auth.signal),await t.call(this.store),this.storesClosedByDisconnect=false;}async quarantineCreds(){try{await this.auth.creds.backupCreds?.();}catch(e){this.logger.warn(e,"auth.creds.backupCreds failed; continuing with the erase");}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function wu(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function vu(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var Ro=class{credsBlob;credsBackup;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;},backupCreds:async()=>{this.assertOpen(),this.credsBlob!==void 0&&(this.credsBackup=structuredClone(this.credsBlob));},readBackupCreds:async()=>(this.assertOpen(),this.credsBackup)};assertOpen(){if(this.closed)throw new g("STORE_CLOSED","MemoryAuthStore is closed")}};var Mu=/^[A-Za-z][A-Za-z0-9_]{0,40}$/,ue=n=>{if(n===void 0||n==="")return "";if(!Mu.test(n))throw new g("STORE_CONNECTION_FAILED",`invalid tablePrefix ${JSON.stringify(n)}: start with a letter, then letters, digits or _ (max 41)`);return n},pe=(n,e)=>{if(n==="")return s=>s;let t=[...e].sort((s,i)=>i.length-s.length),r=new RegExp(`\\b(${t.join("|")})\\b`,"g");return s=>s.replace(r,i=>`${n}${i}`)},An=(n,e)=>{let t=r=>({query:(s,i)=>r.query(e(s),i),release:()=>r.release()});return {query:(r,s)=>n.query(e(r),s),connect:async()=>t(await n.connect()),end:()=>n.end()}},Cn=(n,e)=>new Proxy(n,{get(t,r){if(r==="prepare")return i=>t.prepare(e(i));if(r==="exec")return i=>t.exec(e(i));let s=Reflect.get(t,r,t);return typeof s=="function"?s.bind(t):s}});var Su=["auth_creds","auth_signal"],En=null,bu=async()=>{if(En)return En;try{return En=(await import('better-sqlite3')).default,En}catch(n){throw new g("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Pn="default",Lo="backup",No=500,Do=n=>Array.from({length:n},()=>"?").join(","),Bo=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Fo=class{options;db=null;prepared=null;readyPromise=null;closed=false;rewrite;constructor(e){this.options=e,this.rewrite=pe(ue(e.tablePrefix),Su);}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Pn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Pn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Pn);},backupCreds:async()=>{let e=await this.ensureReady(),t=e.readCreds.get(Pn);t&&e.writeCreds.run(Lo,t.data);},readBackupCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Lo);if(t)return this.parseBlob(t.data)}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Bo(t,No)){let o=Do(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Do(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Bo(t,No))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new g("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}},reopen:async()=>{this.closed=false,this.db=null,this.prepared=null,this.readyPromise=null;}};async ensureReady(){if(this.closed)throw new g("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await bu(),t;try{t=Cn(new e(this.options.database,{readonly:this.options.readonly??!1}),this.rewrite);}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
22
|
-
CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new g("STORE_CONNECTION_FAILED","failed to migrate sqlite schema",{cause:r})}this.db=t,this.prepared={readCreds:t.prepare("SELECT data FROM auth_creds WHERE id = ?"),writeCreds:t.prepare("INSERT INTO auth_creds(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data"),deleteCreds:t.prepare("DELETE FROM auth_creds WHERE id = ?"),writeSignal:t.prepare("INSERT INTO auth_signal(type, id, data) VALUES(?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET data = excluded.data"),deleteSignal:t.prepare("DELETE FROM auth_signal WHERE type = ? AND id = ?"),clearSignal:t.prepare("DELETE FROM auth_signal"),clearCreds:t.prepare("DELETE FROM auth_creds")};}encodeBlob(e){try{return Buffer.from(JSON.stringify(e,ou.BufferJSON.replacer),"utf8")}catch(t){throw new g("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:t})}}parseBlob(e){try{let t=Buffer.isBuffer(e)?e.toString("utf8"):Buffer.from(e).toString("utf8");return JSON.parse(t,ou.BufferJSON.reviver)}catch(t){throw new g("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var Au=["zaileys_auth_creds","zaileys_auth_signal"],kn,Cu=async()=>(kn||(kn=import('pg').then(n=>n).catch(n=>{throw kn=void 0,new g("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),kn),Eu="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",Pu="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",Wo=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;rewrite;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new g("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new g("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max,this.rewrite=pe(ue(e.tablePrefix),Au);}async ensureReady(){if(this.closed)throw new g("STORE_CLOSED","PostgresAuthStore is closed");if(this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Cu(),r=t.Pool??t.default?.Pool;if(!r)throw new g("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}e=An(e,this.rewrite);try{await e.query(Eu),await e.query(Pu);}catch(t){throw new g("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,d)=>`$${d+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let d=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(d.toString("utf8"),ou.BufferJSON.reviver);}return s}catch(i){throw i instanceof g?i:new g("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a];if(d===null)r.push({kind:"delete",type:String(i),id:a});else if(d!==void 0){let c=Buffer.from(JSON.stringify(d,ou.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:c});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new g("STORE_WRITE_FAILED","failed to write signal rows",{cause:i})}finally{s?.release();}},delete:async(e,t)=>{let r=await this.ensureReady();if(t.length!==0)try{let s=t.map((i,o)=>`$${o+2}`).join(", ");await r.query(`DELETE FROM zaileys_auth_signal WHERE type = $1 AND id IN (${s})`,[String(e),...Array.from(t)]);}catch(s){throw new g("STORE_WRITE_FAILED","failed to delete signal rows",{cause:s})}},clear:async()=>{let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_auth_signal"),await t.query("DELETE FROM zaileys_auth_creds"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new g("STORE_WRITE_FAILED","failed to clear auth tables",{cause:r})}finally{t?.release();}},close:async()=>{if(this.closed)return;this.closed=true;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'default'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,ou.BufferJSON.reviver)}catch(t){throw t instanceof g?t:new g("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,ou.BufferJSON.replacer);await t.query("INSERT INTO zaileys_auth_creds(id, data) VALUES ('default', $1::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",[r]);}catch(r){throw new g("STORE_WRITE_FAILED","failed to write creds",{cause:r})}},deleteCreds:async()=>{let e=await this.ensureReady();try{await e.query("DELETE FROM zaileys_auth_creds WHERE id = 'default'");}catch(t){throw new g("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}},backupCreds:async()=>{let e=await this.ensureReady();try{await e.query("INSERT INTO zaileys_auth_creds(id, data) SELECT 'backup', data FROM zaileys_auth_creds WHERE id = 'default' ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data");}catch(t){throw new g("STORE_WRITE_FAILED","failed to back up creds",{cause:t})}},readBackupCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'backup'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,ou.BufferJSON.reviver)}catch(t){throw t instanceof g?t:new g("STORE_READ_FAILED","failed to read backup creds",{cause:t})}}}};var ku=n=>{if(n===void 0)return "(no url)";try{let e=new URL(n);return e.password!==""&&(e.password="***"),e.username!==""&&(e.username="***"),e.toString()}catch{return "(redacted redis url)"}},Tu="zaileys",Iu=n=>{if(!/^[A-Za-z0-9_.:-]+$/.test(n))throw new g("STORE_CONNECTION_FAILED",`invalid namespace ${JSON.stringify(n)}: use letters, digits, and _ . : - only`);return n},xu=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Ou=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Uo=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new g("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new g("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=Iu(e.namespace??Tu),this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let d=i[a];d!=null&&(o[t[a]]=JSON.parse(d,ou.BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a],c=this.signalKey(i,a),l=this.indexKey(i);d===null?(r.del(c),r.sRem(l,a)):d!==void 0&&(r.set(c,JSON.stringify(d,ou.BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of xu){let s=this.indexKey(r),i=await this.runRead(()=>e.sMembers(s));for(let o of i)t.del(this.signalKey(r,o));t.del(s);}t.del(this.credsKey()),await this.runWrite(()=>t.exec());},close:async()=>{await this.shutdown();},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));if(t!=null)return JSON.parse(t,ou.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,ou.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));},backupCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));t!=null&&await this.runWrite(()=>e.set(this.credsBackupKey(),t));},readBackupCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsBackupKey()));if(t!=null)return JSON.parse(t,ou.BufferJSON.reviver)}};credsKey(){return `${this.namespace}:auth:creds`}credsBackupKey(){return `${this.namespace}:auth:creds-backup`}signalKey(e,t){return `${this.namespace}:auth:signal:${String(e)}:${t}`}indexKey(e){return `${this.namespace}:auth:signal-index:${String(e)}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new g("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Ou(r)?new g("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new g("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to connect to redis at ${ku(this.url)}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new g("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new g("STORE_WRITE_FAILED","redis write failed",{cause:t})}}async shutdown(){if(!this.closed){if(this.closed=true,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","RedisAuthStore is closed")}};var Ru="zaileys",Ft={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},_u=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Ve=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new g("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new g("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??Ru,this.externalClient=e.client,this.url=e.url;}async get(e){if(this.assertOpen(),e.length===0)return new Map;let t=await this.ensureClient(),r=await this.runRead(()=>t.query(Ft.get,{namespace:this.namespace,keys:[...e]})),s=new Map;for(let i of r??[])s.set(i.key,i.value);return s}async set(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ft.set,{namespace:this.namespace,items:[...e]}));}async del(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ft.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ft.clear,e===void 0?{namespace:this.namespace}:{namespace:this.namespace,prefix:e}));}async list(e,t){this.assertOpen();let r=await this.ensureClient(),s={namespace:this.namespace,prefix:e};return typeof t?.before=="number"&&(s.before=t.before),typeof t?.limit=="number"&&(s.limit=t.limit),await this.runRead(()=>r.query(Ft.list,s))??[]}close(){this.closed=true,this.client=void 0;}reopen(){this.closed=false;}async ensureClient(){if(this.externalClient)return this.externalClient;if(this.client)return this.client;let e="convex/browser",t;try{t=await import(e);}catch(r){throw _u(r)?new g("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new g("STORE_CONNECTION_FAILED","failed to load convex module",{cause:r})}return this.client=new t.ConvexHttpClient(this.url),this.client}async runRead(e){try{return await e()}catch(t){throw new g("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new g("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","Convex store is closed")}};var He="creds",Mr="creds-backup",Lu="signal:",Ut=(n,e)=>`${Lu}${n}:${e}`,jo=class{creds;signal;kv;constructor(e){this.kv=new Ve(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([He])).get(He);return s===void 0?void 0:JSON.parse(s,ou.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:He,value:JSON.stringify(r,ou.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([He]);},async backupCreds(){let s=(await t.get([He])).get(He);s!==void 0&&await t.set([{key:Mr,value:s}]);},async readBackupCreds(){let s=(await t.get([Mr])).get(Mr);if(s!==void 0)return JSON.parse(s,ou.BufferJSON.reviver)}},this.signal={async read(r,s){let i=s.map(d=>Ut(r,d)),o=await t.get(i),a={};for(let d of s){let c=o.get(Ut(r,d));a[d]=c===void 0?void 0:JSON.parse(c,ou.BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let d of Object.keys(a)){let c=a[d];c==null?i.push(Ut(o,d)):s.push({key:Ut(o,d),value:JSON.stringify(c,ou.BufferJSON.replacer)});}}s.length>0&&await t.set(s),i.length>0&&await t.del(i);},async delete(r,s){await t.del(s.map(i=>Ut(r,i)));},async clear(){await t.clear();},async close(){t.close();},async reopen(){t.reopen();}};}};var Nu=["messages","chats","contacts","presence","messages_by_jid_ts"],Tn=null,Du=async()=>{if(Tn)return Tn;try{return Tn=(await import('better-sqlite3')).default,Tn}catch(n){throw new g("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},In=n=>{try{return Buffer.from(JSON.stringify(n,ou.BufferJSON.replacer),"utf8")}catch(e){throw new g("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},Te=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,ou.BufferJSON.reviver)}catch(e){throw new g("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},qo=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;rewrite;constructor(e){this.options=e,this.rewrite=pe(ue(e.tablePrefix),Nu);}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe?1:0,o=Number(e.messageTimestamp??0);t.upsertMessage.run(r,s,i,o,In(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?Te(r.data):void 0}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=t?.before;return (typeof i=="number"?r.listMessages.all(e,i,s):r.listMessages.all(e,Number.MAX_SAFE_INTEGER,s)).map(a=>Te(a.data))}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived?1:0;t.upsertChat.run(r,s,In(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?Te(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>Te(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,In(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?Te(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>Te(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,In(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?Te(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
20
|
+
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Hl=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:le(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},zl=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Kl(n)??Gl(n)??Jl(n)??Vl(n);if(t===null)return null;let r=Hl(t,n),s=bn(e,n.from);return {key:{id:n.id,remoteJid:le(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},Yl=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?le(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},Ql=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=bn(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:le(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},Xl=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=bn(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:le(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},Zl=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=le(n.from),s=bn(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ko(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=$l(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=Zl(l,c);if(u){t.push(u);continue}let f=Ql(l,c);if(f){i.push(f);continue}let v=Xl(l,c);if(v){o.push(v);continue}let S=zl(l,c);S&&e.push(S);}for(let l of c.statuses??[]){let u=Yl(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var To=3,vr=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Io(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=vr(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(f=>({id:f.id??"",title:f.title??"",description:f.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>To)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${To} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=vr(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?vr(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var tu=6e4,An=128*1024*1024,nu=[".fbcdn.net",".fbsbx.com",".facebook.com",".whatsapp.com",".whatsapp.net",".cdninstagram.com"],ru=n=>{let e;try{e=new URL(n);}catch{throw new C("REQUEST_FAILED","media url is not a valid url")}if(e.protocol!=="https:")throw new C("REQUEST_FAILED",`refusing a non-https media url: ${e.protocol}`);let t=e.hostname.toLowerCase();if(!nu.some(s=>t===s.slice(1)||t.endsWith(s)))throw new C("REQUEST_FAILED",`refusing to send credentials to ${t}`)},Je=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=Sn(e);}get apiVersion(){return this.options.apiVersion??Mn}get baseUrl(){return this.options.baseUrl??wr}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich content (rich: true and htmlApp()) is WhatsApp-Web-only and not supported on the cloud provider. Send the text with send().text() \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Io(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...re(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=Lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...re(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=Lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...re(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=Lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;ru(t.url);let r=new AbortController,s=setTimeout(()=>r.abort(),tu),i;try{i=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`},redirect:"error",signal:r.signal});}catch(c){throw new C("REQUEST_FAILED","media download failed",{cause:c})}finally{clearTimeout(s);}if(!i.ok)throw new C("REQUEST_FAILED",`media download failed (${i.status})`);let o=Number(i.headers?.get?.("content-length")??"0");if(Number.isFinite(o)&&o>An)throw new C("REQUEST_FAILED",`media exceeds ${An} bytes`);let a=Buffer.from(await i.arrayBuffer());if(a.byteLength>An)throw new C("REQUEST_FAILED",`media exceeds ${An} bytes`);let d=t.mime_type??await Re(a);return {buffer:a,mime:d,size:a.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ko(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=Ao(e,t,r);if(s===null){let d=Co(t);if(d){let c=await Eo(this.graph,this.options.phoneNumberId,d);s={...re(e,d.kind,r),[d.kind]:Po(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=Lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var Nt=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=Sn(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var iu=(n,e)=>{let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?false:crypto.timingSafeEqual(t,r)},ou=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function Mr(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o!==null&&iu(o,n.verifyToken)?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0){if(!ou(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401})}else if(n.allowUnsigned!==true)return new Response("webhook requires appSecret (or allowUnsigned for local dev)",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var lu="default",uu="qr",Ro=6e4,pu=2,mu=3e3,gu="29829202653362039",fu=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},hu=/^[A-Za-z0-9_-]{1,64}$/,yu=(n,e)=>{let t=new Set(jr().deniedDirs??[]);for(let r of n?.deniedDirs??[])t.add(r);e instanceof It&&t.add(e.directory),Ur({...n?.maxBytes!==void 0?{maxBytes:n.maxBytes}:{},...n?.allowLocalPaths!==void 0?{allowLocalPaths:n.allowLocalPaths}:{},...n?.allowPrivateNetwork!==void 0?{allowPrivateNetwork:n.allowPrivateNetwork}:{},deniedDirs:[...t]}),_r({...n?.maxImagePixels!==void 0?{maxImagePixels:n.maxImagePixels}:{},...n?.maxConcurrentFfmpeg!==void 0?{maxConcurrent:n.maxConcurrentFfmpeg}:{},...n?.maxQueuedFfmpeg!==void 0?{maxQueued:n.maxQueuedFfmpeg}:{},...n?.ffmpegQueueTimeoutMs!==void 0?{queueTimeoutMs:n.ffmpegQueueTimeoutMs}:{}});},wu=n=>{if(!hu.test(n))throw new Error(`invalid sessionId ${JSON.stringify(n)}: use 1-64 characters from A-Z a-z 0-9 _ -`);return n},_o=class extends vn{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=Ji();reconnectStrategy;authGuard;clearAuthReasons;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;storesClosedByDisconnect=false;chatExpiration=new Map;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:mr(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?yr(e.cloud):void 0,this.sessionId=wu(e.sessionId??lu),this.logger=mr(e.logger),this.authType=e.authType??uu,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&Di(),this.on("message",r=>this.rememberChatExpiration(r)),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new It({basePath:`./.zaileys/auth/${this.sessionId}`}),yu(e.media,this.auth),this.store=e.store??new fn,this.reconnectStrategy=Gi(this.reconnectOptions),this.authGuard=qi(e.authGuard),this.clearAuthReasons=e.session?.clearAuthOn??pr,this.operationGuard=ir(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new be({perSec:t}):void 0,this.commandPrefixes=vu(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new bt(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&Ne.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof au.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=au.fetchLatestBaileysVersion().then(({version:e})=>{this.waVersion=e;}).catch(e=>{this.logger.warn(e,"fetchLatestBaileysVersion failed; using bundled version");}),this.versionWarming)}catch{return Promise.resolve()}}emitAutoConnectError(e){let t=e instanceof Error?e:new Error(String(e));this.logger.error(t,"auto-connect failed"),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:t});}logStatus(e){if(!this.statusLog)return;let t=Ni(e);t&&process.stderr.write(`${t}
|
|
21
|
+
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new _t(e)}get group(){return this.assertWebProvider("group"),this._group??=new ot(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new at(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new dt(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new ct(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new lt(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new ut(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new pt(()=>this._socket,e=>it(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new mt(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new wt(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),or(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new vt({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}async connect(){if(this._provider==="cloud")return this.connectCloud();if(this.authType==="pairing"&&!this.phoneNumber)throw new Error('phoneNumber is required when authType is "pairing"');if(this.machine.state==="connecting"||this.machine.state==="connected"||this.machine.state!=="idle"&&this.machine.state!=="disconnected"&&this.machine.state!=="reconnecting")return;if(this._socket){for(let d of this.listenerCleanup)d.off();this.listenerCleanup=[],this._socket=void 0;}this.storesClosedByDisconnect&&await this.reopenStores();let e=this.machine.state==="reconnecting";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=Fi(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t;try{t=await this.auth.creds.readCreds();}catch(d){let c=d instanceof Error?d:new Error(String(d));throw this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.logger.error(c,"failed to read stored credentials; aborting connect to protect the session"),c}this.credsLoadedAtConnect=!!t;let r=Object.assign({},t??au.initAuthCreds());this.creds=r;let s=Wi(this.auth.signal,this.logger),i={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:Ro,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:r,keys:s},logger:this.logger,getMessage:d=>this.resolveMessageForResend(d),patchMessageBeforeSending:this.patchOutgoing},o=new Promise((d,c)=>{let l=this.connectResolve,u=this.connectReject;this.connectResolve=()=>{l?.(),d();},this.connectReject=f=>{u?.(f),c(f);};}),a=au__default.default(i);return this._socket=a,this.store.bind(a),this.wireSocket(a),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Je(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=hr(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return Mr({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},...e.allowUnsigned===true?{allowUnsigned:true}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose(),this._presence?.dispose();for(let e of this.listenerCleanup)e.off();if(this.listenerCleanup=[],this._socket){try{this._socket.end(void 0);}catch(e){this.logger.warn(e,"socket.end threw");}this._socket=void 0;}try{await this.auth.signal.close();}catch(e){this.logger.warn(e,"auth.signal.close failed");}try{await this.store.close();}catch(e){this.logger.warn(e,"store.close failed");}if(this.storesClosedByDisconnect=true,this.machine.transition("disconnected"),this.disconnectEmittedFor!==this.connectAttemptSeq){let e=this.pendingDisconnectReason??"unknown";this.pendingDisconnectReason=void 0,this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:e,willReconnect:false});}this.rejectPendingConnect(new Error("disconnected before connect resolved"));}}async logout(){if(this.pendingDisconnectReason="logged-out",this._socket)try{await this._socket.logout();}catch(e){this.logger.warn(e,"socket.logout failed");}await this.quarantineCreds();try{await this.auth.signal.clear();}catch(e){this.logger.warn(e,"auth.signal.clear failed");}try{await this.auth.creds.deleteCreds();}catch(e){this.logger.warn(e,"auth.creds.deleteCreds failed");}if(this.machine.state==="idle"||this.machine.state==="disconnected"){this.disconnectEmittedFor!==this.connectAttemptSeq&&(this.disconnectEmittedFor=this.connectAttemptSeq,this.emit("disconnect",{sessionId:this.sessionId,reason:"logged-out",willReconnect:false})),this.pendingDisconnectReason=void 0;return}await this.disconnect();}command(e,t){return (this.commandRegistry??=new gt).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=tr({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("message",r),()=>this.off("message",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Mi(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{return ((await this.group.metadata(e)).participants??[]).some(s=>{let i=s;return [s.id,i.phoneNumber,i.jid].filter(a=>typeof a=="string").some(a=>ar(a,t))&&s.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,client:this,send:s=>this.send(s??t.roomId??t.senderId),reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new j("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||it(e)?ae.create(t,e,void 0,r,s):ae.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new st(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await Vn(this.requireSocket(),e,t);}async react(e,t){return Hn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new N("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new Nt(this.cloudOptions,()=>this.cloudTransport??=new Je(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return zn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),an(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),an(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Fs(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return Yn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{if(this.creds?.registered===true){let d="registered"in o&&o.registered!==true,c="me"in o&&o.me==null;if(d||c){this.logger.error({sessionId:this.sessionId},"refusing a creds update that would de-register the stored session");return}}let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Js(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.creds?.registered===true){let s=new Error("WhatsApp asked to pair again while a registered session is stored; aborting to protect it");this.logger.error({sessionId:this.sessionId},s.message),this.listenerCount("error")>0&&this.emit("error",{sessionId:this.sessionId,error:s}),this.disconnect();return}if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=$i({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Ki(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+Ro});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=hr(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Mt({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new ft({client:this,logger:this.logger}),this.pluginLoader=new ht({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:au.S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:gu},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of fu(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return ln(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=Mu(e?.error),r=Ui(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<pu;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),ji(r,this.clearAuthReasons)&&!i){await this.quarantineCreds();try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!xt(r))&&!this.authExhausted){pn(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:mu}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}async reopenStores(){let e=this.auth.signal.reopen,t=this.store.reopen;if(typeof e!="function"||typeof t!="function")throw new Error("this auth or message store adapter cannot be reopened after disconnect(); implement reopen() or create a new Client");await e.call(this.auth.signal),await t.call(this.store),this.storesClosedByDisconnect=false;}async quarantineCreds(){try{await this.auth.creds.backupCreds?.();}catch(e){this.logger.warn(e,"auth.creds.backupCreds failed; continuing with the erase");}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function vu(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function Mu(n){if(!n||typeof n!="object")return;let e=n.output;if(!e)return;let t=e.statusCode;return typeof t=="number"?t:void 0}var Lo=class{credsBlob;credsBackup;signalMap=new Map;closed=false;signal={read:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e),s={};if(!r)return s;for(let i of t){let o=r.get(i);o!==void 0&&(s[i]=o);}return s},write:async e=>{this.assertOpen();for(let t of Object.keys(e)){let r=e[t];if(!r)continue;let s=this.signalMap.get(t);s||(s=new Map,this.signalMap.set(t,s));for(let i of Object.keys(r)){let o=r[i];o===null?s.delete(i):o!==void 0&&s.set(i,o);}}},delete:async(e,t)=>{this.assertOpen();let r=this.signalMap.get(e);if(r)for(let s of t)r.delete(s);},clear:async()=>{this.assertOpen(),this.signalMap.clear(),this.credsBlob=void 0;},close:async()=>{this.closed=true;},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;},backupCreds:async()=>{this.assertOpen(),this.credsBlob!==void 0&&(this.credsBackup=structuredClone(this.credsBlob));},readBackupCreds:async()=>(this.assertOpen(),this.credsBackup)};assertOpen(){if(this.closed)throw new g("STORE_CLOSED","MemoryAuthStore is closed")}};var Su=/^[A-Za-z][A-Za-z0-9_]{0,40}$/,ue=n=>{if(n===void 0||n==="")return "";if(!Su.test(n))throw new g("STORE_CONNECTION_FAILED",`invalid tablePrefix ${JSON.stringify(n)}: start with a letter, then letters, digits or _ (max 41)`);return n},pe=(n,e)=>{if(n==="")return s=>s;let t=[...e].sort((s,i)=>i.length-s.length),r=new RegExp(`\\b(${t.join("|")})\\b`,"g");return s=>s.replace(r,i=>`${n}${i}`)},Cn=(n,e)=>{let t=r=>({query:(s,i)=>r.query(e(s),i),release:()=>r.release()});return {query:(r,s)=>n.query(e(r),s),connect:async()=>t(await n.connect()),end:()=>n.end()}},En=(n,e)=>new Proxy(n,{get(t,r){if(r==="prepare")return i=>t.prepare(e(i));if(r==="exec")return i=>t.exec(e(i));let s=Reflect.get(t,r,t);return typeof s=="function"?s.bind(t):s}});var bu=["auth_creds","auth_signal"],Pn=null,Au=async()=>{if(Pn)return Pn;try{return Pn=(await import('better-sqlite3')).default,Pn}catch(n){throw new g("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},kn="default",Do="backup",Bo=500,Fo=n=>Array.from({length:n},()=>"?").join(","),Wo=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Uo=class{options;db=null;prepared=null;readyPromise=null;closed=false;rewrite;constructor(e){this.options=e,this.rewrite=pe(ue(e.tablePrefix),bu);}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(kn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(kn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(kn);},backupCreds:async()=>{let e=await this.ensureReady(),t=e.readCreds.get(kn);t&&e.writeCreds.run(Do,t.data);},readBackupCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Do);if(t)return this.parseBlob(t.data)}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Wo(t,Bo)){let o=Fo(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Fo(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Wo(t,Bo))s(i);},clear:async()=>{let e=await this.ensureReady();this.db.transaction(()=>{e.clearSignal.run(),e.clearCreds.run();})();},close:async()=>{if(!this.closed){this.closed=true;try{this.db?.close();}catch(e){throw new g("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}},reopen:async()=>{this.closed=false,this.db=null,this.prepared=null,this.readyPromise=null;}};async ensureReady(){if(this.closed)throw new g("STORE_CLOSED","SqliteAuthStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await Au(),t;try{t=En(new e(this.options.database,{readonly:this.options.readonly??!1}),this.rewrite);}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
22
|
+
CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new g("STORE_CONNECTION_FAILED","failed to migrate sqlite schema",{cause:r})}this.db=t,this.prepared={readCreds:t.prepare("SELECT data FROM auth_creds WHERE id = ?"),writeCreds:t.prepare("INSERT INTO auth_creds(id, data) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data"),deleteCreds:t.prepare("DELETE FROM auth_creds WHERE id = ?"),writeSignal:t.prepare("INSERT INTO auth_signal(type, id, data) VALUES(?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET data = excluded.data"),deleteSignal:t.prepare("DELETE FROM auth_signal WHERE type = ? AND id = ?"),clearSignal:t.prepare("DELETE FROM auth_signal"),clearCreds:t.prepare("DELETE FROM auth_creds")};}encodeBlob(e){try{return Buffer.from(JSON.stringify(e,au.BufferJSON.replacer),"utf8")}catch(t){throw new g("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:t})}}parseBlob(e){try{let t=Buffer.isBuffer(e)?e.toString("utf8"):Buffer.from(e).toString("utf8");return JSON.parse(t,au.BufferJSON.reviver)}catch(t){throw new g("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var Cu=["zaileys_auth_creds","zaileys_auth_signal"],Tn,Eu=async()=>(Tn||(Tn=import('pg').then(n=>n).catch(n=>{throw Tn=void 0,new g("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),Tn),Pu="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",ku="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",jo=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;rewrite;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new g("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new g("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max,this.rewrite=pe(ue(e.tablePrefix),Cu);}async ensureReady(){if(this.closed)throw new g("STORE_CLOSED","PostgresAuthStore is closed");if(this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Eu(),r=t.Pool??t.default?.Pool;if(!r)throw new g("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}e=Cn(e,this.rewrite);try{await e.query(Pu),await e.query(ku);}catch(t){throw new g("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,d)=>`$${d+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let d=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(d.toString("utf8"),au.BufferJSON.reviver);}return s}catch(i){throw i instanceof g?i:new g("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a];if(d===null)r.push({kind:"delete",type:String(i),id:a});else if(d!==void 0){let c=Buffer.from(JSON.stringify(d,au.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:c});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new g("STORE_WRITE_FAILED","failed to write signal rows",{cause:i})}finally{s?.release();}},delete:async(e,t)=>{let r=await this.ensureReady();if(t.length!==0)try{let s=t.map((i,o)=>`$${o+2}`).join(", ");await r.query(`DELETE FROM zaileys_auth_signal WHERE type = $1 AND id IN (${s})`,[String(e),...Array.from(t)]);}catch(s){throw new g("STORE_WRITE_FAILED","failed to delete signal rows",{cause:s})}},clear:async()=>{let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_auth_signal"),await t.query("DELETE FROM zaileys_auth_creds"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new g("STORE_WRITE_FAILED","failed to clear auth tables",{cause:r})}finally{t?.release();}},close:async()=>{if(this.closed)return;this.closed=true;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'default'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,au.BufferJSON.reviver)}catch(t){throw t instanceof g?t:new g("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,au.BufferJSON.replacer);await t.query("INSERT INTO zaileys_auth_creds(id, data) VALUES ('default', $1::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data",[r]);}catch(r){throw new g("STORE_WRITE_FAILED","failed to write creds",{cause:r})}},deleteCreds:async()=>{let e=await this.ensureReady();try{await e.query("DELETE FROM zaileys_auth_creds WHERE id = 'default'");}catch(t){throw new g("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}},backupCreds:async()=>{let e=await this.ensureReady();try{await e.query("INSERT INTO zaileys_auth_creds(id, data) SELECT 'backup', data FROM zaileys_auth_creds WHERE id = 'default' ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data");}catch(t){throw new g("STORE_WRITE_FAILED","failed to back up creds",{cause:t})}},readBackupCreds:async()=>{let e=await this.ensureReady();try{let r=(await e.query("SELECT data FROM zaileys_auth_creds WHERE id = 'backup'")).rows[0];if(!r)return;let s=typeof r.data=="string"?r.data:JSON.stringify(r.data);return JSON.parse(s,au.BufferJSON.reviver)}catch(t){throw t instanceof g?t:new g("STORE_READ_FAILED","failed to read backup creds",{cause:t})}}}};var Tu=n=>{if(n===void 0)return "(no url)";try{let e=new URL(n);return e.password!==""&&(e.password="***"),e.username!==""&&(e.username="***"),e.toString()}catch{return "(redacted redis url)"}},Iu="zaileys",xu=n=>{if(!/^[A-Za-z0-9_.:-]+$/.test(n))throw new g("STORE_CONNECTION_FAILED",`invalid namespace ${JSON.stringify(n)}: use letters, digits, and _ . : - only`);return n},Ou=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Ru=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},qo=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new g("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new g("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=xu(e.namespace??Iu),this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let d=i[a];d!=null&&(o[t[a]]=JSON.parse(d,au.BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a],c=this.signalKey(i,a),l=this.indexKey(i);d===null?(r.del(c),r.sRem(l,a)):d!==void 0&&(r.set(c,JSON.stringify(d,au.BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of Ou){let s=this.indexKey(r),i=await this.runRead(()=>e.sMembers(s));for(let o of i)t.del(this.signalKey(r,o));t.del(s);}t.del(this.credsKey()),await this.runWrite(()=>t.exec());},close:async()=>{await this.shutdown();},reopen:async()=>{this.closed=false;}};creds={readCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));if(t!=null)return JSON.parse(t,au.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,au.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));},backupCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsKey()));t!=null&&await this.runWrite(()=>e.set(this.credsBackupKey(),t));},readBackupCreds:async()=>{this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.get(this.credsBackupKey()));if(t!=null)return JSON.parse(t,au.BufferJSON.reviver)}};credsKey(){return `${this.namespace}:auth:creds`}credsBackupKey(){return `${this.namespace}:auth:creds-backup`}signalKey(e,t){return `${this.namespace}:auth:signal:${String(e)}:${t}`}indexKey(e){return `${this.namespace}:auth:signal-index:${String(e)}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new g("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Ru(r)?new g("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new g("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to connect to redis at ${Tu(this.url)}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new g("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new g("STORE_WRITE_FAILED","redis write failed",{cause:t})}}async shutdown(){if(!this.closed){if(this.closed=true,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","RedisAuthStore is closed")}};var _u="zaileys",Ft={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Lu=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Ve=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new g("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new g("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??_u,this.externalClient=e.client,this.url=e.url;}async get(e){if(this.assertOpen(),e.length===0)return new Map;let t=await this.ensureClient(),r=await this.runRead(()=>t.query(Ft.get,{namespace:this.namespace,keys:[...e]})),s=new Map;for(let i of r??[])s.set(i.key,i.value);return s}async set(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ft.set,{namespace:this.namespace,items:[...e]}));}async del(e){if(this.assertOpen(),e.length===0)return;let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ft.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ft.clear,e===void 0?{namespace:this.namespace}:{namespace:this.namespace,prefix:e}));}async list(e,t){this.assertOpen();let r=await this.ensureClient(),s={namespace:this.namespace,prefix:e};return typeof t?.before=="number"&&(s.before=t.before),typeof t?.limit=="number"&&(s.limit=t.limit),await this.runRead(()=>r.query(Ft.list,s))??[]}close(){this.closed=true,this.client=void 0;}reopen(){this.closed=false;}async ensureClient(){if(this.externalClient)return this.externalClient;if(this.client)return this.client;let e="convex/browser",t;try{t=await import(e);}catch(r){throw Lu(r)?new g("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new g("STORE_CONNECTION_FAILED","failed to load convex module",{cause:r})}return this.client=new t.ConvexHttpClient(this.url),this.client}async runRead(e){try{return await e()}catch(t){throw new g("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new g("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","Convex store is closed")}};var He="creds",Sr="creds-backup",Nu="signal:",Ut=(n,e)=>`${Nu}${n}:${e}`,$o=class{creds;signal;kv;constructor(e){this.kv=new Ve(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([He])).get(He);return s===void 0?void 0:JSON.parse(s,au.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:He,value:JSON.stringify(r,au.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([He]);},async backupCreds(){let s=(await t.get([He])).get(He);s!==void 0&&await t.set([{key:Sr,value:s}]);},async readBackupCreds(){let s=(await t.get([Sr])).get(Sr);if(s!==void 0)return JSON.parse(s,au.BufferJSON.reviver)}},this.signal={async read(r,s){let i=s.map(d=>Ut(r,d)),o=await t.get(i),a={};for(let d of s){let c=o.get(Ut(r,d));a[d]=c===void 0?void 0:JSON.parse(c,au.BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let d of Object.keys(a)){let c=a[d];c==null?i.push(Ut(o,d)):s.push({key:Ut(o,d),value:JSON.stringify(c,au.BufferJSON.replacer)});}}s.length>0&&await t.set(s),i.length>0&&await t.del(i);},async delete(r,s){await t.del(s.map(i=>Ut(r,i)));},async clear(){await t.clear();},async close(){t.close();},async reopen(){t.reopen();}};}};var Du=["messages","chats","contacts","presence","messages_by_jid_ts"],In=null,Bu=async()=>{if(In)return In;try{return In=(await import('better-sqlite3')).default,In}catch(n){throw new g("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},xn=n=>{try{return Buffer.from(JSON.stringify(n,au.BufferJSON.replacer),"utf8")}catch(e){throw new g("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},Te=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,au.BufferJSON.reviver)}catch(e){throw new g("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ko=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;rewrite;constructor(e){this.options=e,this.rewrite=pe(ue(e.tablePrefix),Du);}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe?1:0,o=Number(e.messageTimestamp??0);t.upsertMessage.run(r,s,i,o,xn(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?Te(r.data):void 0}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=t?.before;return (typeof i=="number"?r.listMessages.all(e,i,s):r.listMessages.all(e,Number.MAX_SAFE_INTEGER,s)).map(a=>Te(a.data))}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived?1:0;t.upsertChat.run(r,s,xn(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?Te(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>Te(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,xn(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?Te(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>Te(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,xn(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?Te(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
23
23
|
SELECT rowid FROM (
|
|
24
24
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|
|
25
25
|
FROM messages ${o}
|
|
26
26
|
) WHERE rn > ?
|
|
27
|
-
)`);s+=a.run(...i??[],e.maxPerChat).changes;}return s}bind(e){if(this.closed)throw new g("STORE_CLOSED","SqliteMessageStore is closed");this.boundSocket=e;let t=(...o)=>{let d=o[0]?.messages;if(Array.isArray(d))for(let c of d)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveChat(d).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveContact(d).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let d of Object.keys(a.presences)){let c=a.presences[d];c&&this.savePresence(d,c).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){let e=await this.ensureReady();this.db.transaction(()=>{e.clearMessages.run(),e.clearChats.run(),e.clearContacts.run(),e.clearPresence.run();})();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);this.listeners.clear(),this.boundSocket=void 0;try{this.db?.close();}catch(e){throw new g("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}async reopen(){this.closed=false,this.db=null,this.prepared=null,this.readyPromise=null;}async ensureReady(){if(this.closed)throw new g("STORE_CLOSED","SqliteMessageStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await
|
|
27
|
+
)`);s+=a.run(...i??[],e.maxPerChat).changes;}return s}bind(e){if(this.closed)throw new g("STORE_CLOSED","SqliteMessageStore is closed");this.boundSocket=e;let t=(...o)=>{let d=o[0]?.messages;if(Array.isArray(d))for(let c of d)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveChat(d).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveContact(d).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let d of Object.keys(a.presences)){let c=a.presences[d];c&&this.savePresence(d,c).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){let e=await this.ensureReady();this.db.transaction(()=>{e.clearMessages.run(),e.clearChats.run(),e.clearContacts.run(),e.clearPresence.run();})();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);this.listeners.clear(),this.boundSocket=void 0;try{this.db?.close();}catch(e){throw new g("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}async reopen(){this.closed=false,this.db=null,this.prepared=null,this.readyPromise=null;}async ensureReady(){if(this.closed)throw new g("STORE_CLOSED","SqliteMessageStore is closed");return this.prepared?this.prepared:(this.readyPromise||(this.readyPromise=this.openAndMigrate().catch(e=>{throw this.readyPromise=null,e})),await this.readyPromise,this.prepared)}async openAndMigrate(){let e=await Bu(),t;try{t=En(new e(this.options.database,{readonly:this.options.readonly??!1}),this.rewrite);}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS messages (
|
|
28
28
|
remote_jid TEXT NOT NULL,
|
|
29
29
|
id TEXT NOT NULL,
|
|
30
30
|
from_me INTEGER NOT NULL,
|
|
@@ -39,4 +39,4 @@ END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsAr
|
|
|
39
39
|
ON CONFLICT(remote_jid, id, from_me) DO UPDATE SET timestamp = excluded.timestamp, data = excluded.data`),getMessage:t.prepare("SELECT data FROM messages WHERE remote_jid = ? AND id = ? AND from_me = ?"),listMessages:t.prepare("SELECT data FROM messages WHERE remote_jid = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?"),upsertChat:t.prepare(`INSERT INTO chats(jid, archived, data) VALUES(?, ?, ?)
|
|
40
40
|
ON CONFLICT(jid) DO UPDATE SET archived = excluded.archived, data = excluded.data`),getChat:t.prepare("SELECT data FROM chats WHERE jid = ?"),listChats:t.prepare("SELECT data FROM chats"),listChatsArchived:t.prepare("SELECT data FROM chats WHERE archived = 1"),upsertContact:t.prepare(`INSERT INTO contacts(jid, data) VALUES(?, ?)
|
|
41
41
|
ON CONFLICT(jid) DO UPDATE SET data = excluded.data`),getContact:t.prepare("SELECT data FROM contacts WHERE jid = ?"),listContacts:t.prepare("SELECT data FROM contacts"),upsertPresence:t.prepare(`INSERT INTO presence(jid, data) VALUES(?, ?)
|
|
42
|
-
ON CONFLICT(jid) DO UPDATE SET data = excluded.data`),getPresence:t.prepare("SELECT data FROM presence WHERE jid = ?"),clearMessages:t.prepare("DELETE FROM messages"),clearChats:t.prepare("DELETE FROM chats"),clearContacts:t.prepare("DELETE FROM contacts"),clearPresence:t.prepare("DELETE FROM presence"),deleteMessage:t.prepare("DELETE FROM messages WHERE remote_jid = ? AND id = ? AND from_me = ?"),pruneByAge:t.prepare("DELETE FROM messages WHERE timestamp < ?"),pruneByAgeChat:t.prepare("DELETE FROM messages WHERE timestamp < ? AND remote_jid = ?")};}};var Bu=["zaileys_messages","zaileys_chats","zaileys_contacts","zaileys_presence","zaileys_chats_archived_idx","zaileys_messages_jid_ts_idx"],xn,Fu=async()=>(xn||(xn=import('pg').then(n=>n).catch(n=>{throw xn=void 0,new g("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),xn),Wu=["CREATE TABLE IF NOT EXISTS zaileys_messages (remote_jid text NOT NULL, id text NOT NULL, from_me boolean NOT NULL, timestamp bigint NOT NULL, data jsonb NOT NULL, PRIMARY KEY(remote_jid, id, from_me))","CREATE INDEX IF NOT EXISTS zaileys_messages_jid_ts_idx ON zaileys_messages(remote_jid, timestamp DESC)","CREATE TABLE IF NOT EXISTS zaileys_chats (jid text PRIMARY KEY, archived boolean NOT NULL DEFAULT false, data jsonb NOT NULL)","CREATE INDEX IF NOT EXISTS zaileys_chats_archived_idx ON zaileys_chats(archived) WHERE archived = true","CREATE TABLE IF NOT EXISTS zaileys_contacts (jid text PRIMARY KEY, data jsonb NOT NULL)","CREATE TABLE IF NOT EXISTS zaileys_presence (jid text PRIMARY KEY, data jsonb NOT NULL, updated_at timestamptz NOT NULL DEFAULT now())"],Ie=n=>{if(n==null)return n;let e=typeof n=="string"?n:JSON.stringify(n);return JSON.parse(e,ou.BufferJSON.reviver)},Ko=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;boundSocket;listeners=new Map;closed=false;rewrite;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new g("STORE_CONNECTION_FAILED","PostgresMessageStore: provide either pool or connectionString, not both");if(!t&&!r)throw new g("STORE_CONNECTION_FAILED","PostgresMessageStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max,this.rewrite=pe(ue(e.tablePrefix),Bu);}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","PostgresMessageStore is closed")}async ensureReady(){if(this.assertOpen(),this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Fu(),r=t.Pool??t.default?.Pool;if(!r)throw new g("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}e=An(e,this.rewrite);try{for(let t of Wu)await e.query(t);}catch(t){throw new g("STORE_CONNECTION_FAILED","failed to migrate message schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe===true,o=Number(e.messageTimestamp??0);try{await t.query("INSERT INTO zaileys_messages(remote_jid, id, from_me, timestamp, data) VALUES ($1, $2, $3, $4, $5::jsonb) ON CONFLICT (remote_jid, id, from_me) DO UPDATE SET data = EXCLUDED.data, timestamp = EXCLUDED.timestamp",[r,s,i,o,JSON.stringify(e,ou.BufferJSON.replacer)]);}catch(a){throw new g("STORE_WRITE_FAILED","failed to save message",{cause:a})}}async getMessage(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0])).rows[0];return s?Ie(s.data):void 0}catch(r){throw r instanceof g?r:new g("STORE_READ_FAILED","failed to read message",{cause:r})}}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?t.before:null;try{return (await r.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND ($2::bigint IS NULL OR timestamp < $2::bigint) ORDER BY timestamp DESC LIMIT $3",[e,i,s])).rows.map(a=>Ie(a.data))}catch(o){throw new g("STORE_READ_FAILED","failed to list messages",{cause:o})}}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived===true;try{await t.query("INSERT INTO zaileys_chats(jid, archived, data) VALUES ($1, $2, $3::jsonb) ON CONFLICT (jid) DO UPDATE SET archived = EXCLUDED.archived, data = EXCLUDED.data",[r,s,JSON.stringify(e,ou.BufferJSON.replacer)]);}catch(i){throw new g("STORE_WRITE_FAILED","failed to save chat",{cause:i})}}async getChat(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_chats WHERE jid = $1",[e])).rows[0];return s?Ie(s.data):void 0}catch(r){throw new g("STORE_READ_FAILED","failed to read chat",{cause:r})}}async listChats(e){let t=await this.ensureReady(),r=typeof e?.archived=="boolean"?e.archived:null;try{return (await t.query("SELECT data FROM zaileys_chats WHERE ($1::boolean IS NULL OR archived = $1::boolean)",[r])).rows.map(i=>Ie(i.data))}catch(s){throw new g("STORE_READ_FAILED","failed to list chats",{cause:s})}}async saveContact(e){let t=await this.ensureReady();try{await t.query("INSERT INTO zaileys_contacts(jid, data) VALUES ($1, $2::jsonb) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data",[e.id,JSON.stringify(e,ou.BufferJSON.replacer)]);}catch(r){throw new g("STORE_WRITE_FAILED","failed to save contact",{cause:r})}}async getContact(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_contacts WHERE jid = $1",[e])).rows[0];return s?Ie(s.data):void 0}catch(r){throw new g("STORE_READ_FAILED","failed to read contact",{cause:r})}}async listContacts(){let e=await this.ensureReady();try{return (await e.query("SELECT data FROM zaileys_contacts")).rows.map(r=>Ie(r.data))}catch(t){throw new g("STORE_READ_FAILED","failed to list contacts",{cause:t})}}async savePresence(e,t){let r=await this.ensureReady();try{await r.query("INSERT INTO zaileys_presence(jid, data, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data, updated_at = now()",[e,JSON.stringify(t,ou.BufferJSON.replacer)]);}catch(s){throw new g("STORE_WRITE_FAILED","failed to save presence",{cause:s})}}async getPresence(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_presence WHERE jid = $1",[e])).rows[0];return s?Ie(s.data):void 0}catch(r){throw new g("STORE_READ_FAILED","failed to read presence",{cause:r})}}async deleteMessage(e){let t=await this.ensureReady();try{await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0]);}catch(r){throw new g("STORE_WRITE_FAILED","failed to delete message",{cause:r})}}async pruneMessages(e){let t=await this.ensureReady();try{let r=0,s;if(e.chatFilter&&(s=(await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[])).rows.map(o=>o.remote_jid).filter(o=>e.chatFilter(o))),e.olderThan!==void 0){let i=s?await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1 AND remote_jid = ANY($2::text[])",[e.olderThan,s]):await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1",[e.olderThan]);r+=i.rowCount??0;}if(e.maxPerChat!==void 0){let i=s??await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[]).then(o=>o.rows.map(a=>a.remote_jid));for(let o of i){let d=(await t.query("SELECT id, from_me FROM zaileys_messages WHERE remote_jid = $1 ORDER BY timestamp DESC",[o])).rows.slice(e.maxPerChat);if(d.length!==0)for(let c of d){let l=await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[o,c.id,c.from_me]);r+=l.rowCount??0;}}}return r}catch(r){throw new g("STORE_WRITE_FAILED","failed to prune messages",{cause:r})}}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...d)=>{let l=d[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.getMessage(l.key).then(u=>{if(!u)return;let f={...u,...l.update};return this.saveMessage(f)}).catch(()=>{});},s=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveChat(l).catch(()=>{});},i=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.getChat(l.id).then(u=>{let f={...u??{},...l};return this.saveChat(f)}).catch(()=>{});},o=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveContact(l).catch(()=>{});},a=(...d)=>{let c=d[0];if(c?.presences)for(let l of Object.keys(c.presences)){let u=c.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[d,c]of this.listeners)e.ev.on(d,c);}async clear(){let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_messages"),await t.query("DELETE FROM zaileys_chats"),await t.query("DELETE FROM zaileys_contacts"),await t.query("DELETE FROM zaileys_presence"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new g("STORE_WRITE_FAILED","failed to clear message tables",{cause:r})}finally{t?.release();}}async reopen(){this.closed=false;}async close(){if(this.closed)return;if(this.closed=true,this.boundSocket?.ev.off)for(let[t,r]of this.listeners)this.boundSocket.ev.off(t,r);this.listeners.clear(),this.boundSocket=void 0;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};var Uu=n=>{if(n===void 0)return "(no url)";try{let e=new URL(n);return e.password!==""&&(e.password="***"),e.username!==""&&(e.username="***"),e.toString()}catch{return "(redacted redis url)"}},ju="zaileys",qu=Object.freeze(["msg:*","msg-data:*","presence:*","chats","chats-archived","contacts"]),$u=n=>{if(!/^[A-Za-z0-9_.:-]+$/.test(n))throw new g("STORE_CONNECTION_FAILED",`invalid namespace ${JSON.stringify(n)}: use letters, digits, and _ . : - only`);return n},Ku=300,Go=1e3,Sr=n=>`${n.id??""}|${n.fromMe?1:0}`,Gu=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Jo=class{namespace;externalClient;url;ownedClient;ready;closed=false;boundSocket;listeners=new Map;constructor(e){if(e.client&&e.url)throw new g("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new g("STORE_CONNECTION_FAILED","RedisMessageStore requires either client or url");this.namespace=$u(e.namespace??ju),this.externalClient=e.client,this.url=e.url;}async saveMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.key.remoteJid??"",s=Sr(e.key),i=Number(e.messageTimestamp??0),o=JSON.stringify(e,ou.BufferJSON.replacer),a=t.multi();a.zAdd(this.msgIndexKey(r),{score:i,value:s}),a.hSet(this.msgDataKey(r),s,o),await this.runWrite(()=>a.exec());}async getMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=await this.runRead(()=>t.hGet(this.msgDataKey(r),Sr(e)));if(s!=null)return JSON.parse(s,ou.BufferJSON.reviver)}async listMessages(e,t){this.assertOpen();let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?`(${t.before}`:"+inf",o=this.msgIndexKey(e),a=r.zRange,d=await this.runRead(async()=>{if(typeof a=="function")try{return await a.call(r,o,i,"-inf",{BY:"SCORE",REV:!0,LIMIT:{offset:0,count:s}})}catch{}return [...await r.zRangeByScore(o,"-inf",i)].reverse().slice(0,s)});if(d.length===0)return [];let c=d.slice(0,s),l=await this.runRead(()=>r.hmGet(this.msgDataKey(e),c)),u=[];for(let f of l)f!=null&&u.push(JSON.parse(f,ou.BufferJSON.reviver));return u}async saveChat(e){this.assertOpen();let t=e.id;if(!t)return;let s=(await this.ensureReady()).multi();s.hSet(this.chatsKey(),t,JSON.stringify(e,ou.BufferJSON.replacer)),e.archived===true?s.sAdd(this.chatsArchiveKey(),t):s.sRem(this.chatsArchiveKey(),t),await this.runWrite(()=>s.exec());}async getChat(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.chatsKey(),e));if(r!=null)return JSON.parse(r,ou.BufferJSON.reviver)}async listChats(e){this.assertOpen();let t=await this.ensureReady();if(e?.archived===true){let i=await this.runRead(()=>t.sMembers(this.chatsArchiveKey()));if(i.length===0)return [];let o=await this.runRead(()=>t.hmGet(this.chatsKey(),i)),a=[];for(let d of o)d!=null&&a.push(JSON.parse(d,ou.BufferJSON.reviver));return a}let r=await this.runRead(()=>t.hGetAll(this.chatsKey())),s=[];for(let i of Object.keys(r)){let o=r[i];if(o==null)continue;let a=JSON.parse(o,ou.BufferJSON.reviver);e?.archived===false&&await this.runRead(()=>t.sIsMember(this.chatsArchiveKey(),i))||s.push(a);}return s}async saveContact(e){this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.hSet(this.contactsKey(),e.id,JSON.stringify(e,ou.BufferJSON.replacer)));}async getContact(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.contactsKey(),e));if(r!=null)return JSON.parse(r,ou.BufferJSON.reviver)}async listContacts(){this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.hGetAll(this.contactsKey())),r=[];for(let s of Object.keys(t)){let i=t[s];i!=null&&r.push(JSON.parse(i,ou.BufferJSON.reviver));}return r}async savePresence(e,t){this.assertOpen();let r=await this.ensureReady();await this.runWrite(()=>r.set(this.presenceKey(e),JSON.stringify(t,ou.BufferJSON.replacer),{EX:Ku}));}async getPresence(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.get(this.presenceKey(e)));if(r!=null)return JSON.parse(r,ou.BufferJSON.reviver)}bind(e){if(this.assertOpen(),this.boundSocket&&this.boundSocket.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let d=o[0]?.messages;if(Array.isArray(d))for(let c of d)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveChat(d).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveContact(d).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let d of Object.keys(a.presences)){let c=a.presences[d];c&&this.savePresence(d,c).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen();let e=await this.ensureReady();for(let t of qu){let r=`${this.namespace}:${t}`,s=0;do{let i=await this.runRead(()=>e.scan(s,{MATCH:r,COUNT:Go}));s=Number(i.cursor),i.keys.length>0&&await this.runWrite(()=>e.del(i.keys));}while(s!==0)}}async reopen(){this.closed=false;}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);if(this.listeners.clear(),this.boundSocket=void 0,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}async deleteMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=Sr(e),i=t.multi();i.zRem(this.msgIndexKey(r),s),i.hDel(this.msgDataKey(r),s),await this.runWrite(()=>i.exec());}async pruneMessages(e){this.assertOpen();let t=await this.ensureReady(),r=0,s=[],i=this.msgIndexKey("*"),o=0,a=this.msgDataKey("");do{let d=await this.runRead(()=>t.scan(o,{MATCH:i,COUNT:Go}));o=Number(d.cursor);for(let c of d.keys)c.startsWith(a)||s.push(c);}while(o!==0);for(let d of s){let c=this.jidFromIndexKey(d);if(e.chatFilter&&!e.chatFilter(c))continue;let l=this.msgDataKey(c),u=new Set;if(e.olderThan!==void 0){let b=await this.runRead(()=>t.zRangeByScore(d,"-inf",`(${e.olderThan}`));for(let T of b)u.add(T);}if(e.maxPerChat!==void 0){let b=e.maxPerChat,T=await this.runRead(()=>t.zRange(d,0,-(b+1)));for(let O of T)u.add(O);}if(u.size===0)continue;let f=[...u],v=t.multi();v.zRem(d,f),v.hDel(l,f),await this.runWrite(()=>v.exec()),r+=f.length;}return r}jidFromIndexKey(e){let t=this.msgIndexKey("");return e.startsWith(t)?e.slice(t.length):e}msgIndexKey(e){return `${this.namespace}:msg:${e}`}msgDataKey(e){return `${this.namespace}:msg-data:${e}`}chatsKey(){return `${this.namespace}:chats`}chatsArchiveKey(){return `${this.namespace}:chats-archived`}contactsKey(){return `${this.namespace}:contacts`}presenceKey(e){return `${this.namespace}:presence:${e}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new g("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Gu(r)?new g("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new g("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to connect to redis at ${Uu(this.url)}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new g("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new g("STORE_WRITE_FAILED","redis write failed",{cause:t})}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","RedisMessageStore is closed")}};var Gt="msg:",$t="chat:",Kt="contact:",Rn="presence:",_n="job:",Ju=Object.freeze([Gt,$t,Kt,Rn,_n]),Vu=n=>`${n.id??""}|${n.fromMe?1:0}`,On=n=>`${Gt}${n.remoteJid??""}:${Vu(n)}`,qt=n=>JSON.stringify(n,ou.BufferJSON.replacer),Hu=n=>{let e=n.slice(Gt.length),t=e.lastIndexOf("|"),r=e.lastIndexOf(":",t===-1?e.length:t);return r===-1?e:e.slice(0,r)},me=n=>JSON.parse(n,ou.BufferJSON.reviver),Vo=class{kv;closed=false;boundSocket;listeners=new Map;constructor(e){this.kv=new Ve(e);}async saveMessage(e){this.assertOpen(),await this.kv.set([{key:On(e.key),value:qt(e),sortKey:Number(e.messageTimestamp??0)}]);}async getMessage(e){this.assertOpen();let r=(await this.kv.get([On(e)])).get(On(e));return r===void 0?void 0:me(r)}async listMessages(e,t){this.assertOpen();let r={};return typeof t?.before=="number"&&(r.before=t.before),typeof t?.limit=="number"&&(r.limit=t.limit),(await this.kv.list(`${Gt}${e}:`,r)).map(i=>me(i.value))}async saveChat(e){this.assertOpen();let t=e.id;t&&await this.kv.set([{key:`${$t}${t}`,value:qt(e)}]);}async getChat(e){this.assertOpen();let r=(await this.kv.get([`${$t}${e}`])).get(`${$t}${e}`);return r===void 0?void 0:me(r)}async listChats(e){this.assertOpen();let t=await this.kv.list($t),r=[];for(let s of t){let i=me(s.value),o=i.archived===true;e?.archived===true&&!o||e?.archived===false&&o||r.push(i);}return r}async saveContact(e){this.assertOpen(),await this.kv.set([{key:`${Kt}${e.id}`,value:qt(e)}]);}async getContact(e){this.assertOpen();let r=(await this.kv.get([`${Kt}${e}`])).get(`${Kt}${e}`);return r===void 0?void 0:me(r)}async listContacts(){return this.assertOpen(),(await this.kv.list(Kt)).map(t=>me(t.value))}async savePresence(e,t){this.assertOpen(),await this.kv.set([{key:`${Rn}${e}`,value:qt(t)}]);}async getPresence(e){this.assertOpen();let r=(await this.kv.get([`${Rn}${e}`])).get(`${Rn}${e}`);return r===void 0?void 0:me(r)}async saveScheduledJob(e){this.assertOpen(),await this.kv.set([{key:`${_n}${e.id}`,value:qt(e),sortKey:e.fireAt}]);}async listScheduledJobs(){return this.assertOpen(),(await this.kv.list(_n)).map(t=>me(t.value))}async deleteScheduledJob(e){this.assertOpen(),await this.kv.del([`${_n}${e}`]);}async deleteMessage(e){this.assertOpen(),await this.kv.del([On(e)]);}async pruneMessages(e){this.assertOpen();let t=await this.kv.list(Gt,{}),r=new Map;for(let i of t){let o=Hu(i.key);if(e.chatFilter&&!e.chatFilter(o))continue;let a=r.get(o)??[];a.push({key:i.key,ts:i.sortKey??0}),r.set(o,a);}let s=[];for(let i of r.values()){i.sort((o,a)=>a.ts-o.ts);for(let o=0;o<i.length;o++){let a=i[o];(e.olderThan!==void 0&&a.ts<e.olderThan||e.maxPerChat!==void 0&&o>=e.maxPerChat)&&s.push(a.key);}}return s.length>0&&await this.kv.del(s),s.length}bind(e){if(this.assertOpen(),this.boundSocket?.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let a=o[0]?.messages;if(Array.isArray(a))for(let d of a)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveChat(d).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveContact(d).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let d of Object.keys(a.presences)){let c=a.presences[d];c&&this.savePresence(d,c).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen();for(let e of Ju)await this.kv.clear(e);}async reopen(){this.closed=false,this.kv.reopen();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);this.listeners.clear(),this.boundSocket=void 0,this.kv.close();}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","ConvexMessageStore is closed")}};var zu=(n,e)=>{if(e<=0)throw new RangeError("chunk size must be positive");let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t};Object.defineProperty(exports,"areJidsSameUser",{enumerable:true,get:function(){return ou.areJidsSameUser}});Object.defineProperty(exports,"getDevice",{enumerable:true,get:function(){return ou.getDevice}});Object.defineProperty(exports,"isJidBroadcast",{enumerable:true,get:function(){return ou.isJidBroadcast}});Object.defineProperty(exports,"isJidGroup",{enumerable:true,get:function(){return ou.isJidGroup}});Object.defineProperty(exports,"isJidNewsletter",{enumerable:true,get:function(){return ou.isJidNewsletter}});Object.defineProperty(exports,"isLidUser",{enumerable:true,get:function(){return ou.isLidUser}});Object.defineProperty(exports,"isPnUser",{enumerable:true,get:function(){return ou.isPnUser}});Object.defineProperty(exports,"jidDecode",{enumerable:true,get:function(){return ou.jidDecode}});Object.defineProperty(exports,"jidEncode",{enumerable:true,get:function(){return ou.jidEncode}});Object.defineProperty(exports,"jidNormalizedUser",{enumerable:true,get:function(){return ou.jidNormalizedUser}});exports.AudioProcessor=we;exports.AutoDeleteSweeper=Mt;exports.AutoRejectCallModule=bt;exports.BufferConverter=R;exports.BusinessModule=mt;exports.ChatModule=ut;exports.Client=Oo;exports.CloudModule=Nt;exports.CloudTransport=Je;exports.CommandRegistry=gt;exports.CommunityModule=ct;exports.ContactModule=pt;exports.ConvexAuthStore=jo;exports.ConvexMessageStore=Vo;exports.DEFAULT_CLEAR_AUTH_REASONS=ur;exports.DEFAULT_GRAPH_VERSION=vn;exports.DocumentProcessor=Xt;exports.EditBuilder=st;exports.FFMPEG_CONSTANTS=P;exports.FFmpegProcessor=he;exports.FileAuthStore=It;exports.FileManager=se;exports.GroupModule=ot;exports.HTML_APP_MAX_BYTES=os;exports.ImageProcessor=V;exports.Media=ve;exports.MemoryAuthStore=Ro;exports.MemoryMessageStore=gn;exports.MessageBuilder=ae;exports.MimeValidator=q;exports.NewsletterModule=dt;exports.PostgresAuthStore=Wo;exports.PostgresMessageStore=Ko;exports.PresenceModule=wt;exports.PrivacyModule=at;exports.ProfileModule=lt;exports.RateLimiter=be;exports.RedisAuthStore=Uo;exports.RedisMessageStore=Jo;exports.SELF_ONLY_PROTOCOL_TYPES=Ji;exports.SafeHtml=ee;exports.Scheduler=vt;exports.SqliteAuthStore=Fo;exports.SqliteMessageStore=qo;exports.StickerProcessor=Ne;exports.TaskQueue=yt;exports.TypedEventEmitter=wn;exports.VideoProcessor=X;exports.ZaileysAutomationError=N;exports.ZaileysBuilderError=p;exports.ZaileysCloudError=C;exports.ZaileysCommandError=j;exports.ZaileysDomainError=L;exports.ZaileysProviderError=_t;exports.ZaileysStoreError=g;exports.adoptLogger=pr;exports.attachCommandDispatcher=er;exports.buildMessageContext=ar;exports.checkGuards=Zn;exports.chunk=zu;exports.computeStaticId=ci;exports.computeUniqueId=di;exports.configureMediaLimits=Rr;exports.createAuthGuard=Ui;exports.createConnectionStateMachine=Ki;exports.createLogger=rl;exports.createOperationGuard=sr;exports.createPairingFlow=ji;exports.createReconnectStrategy=$i;exports.createWebhookHandler=vr;exports.definePlugin=Vs;exports.deleteMessage=Jn;exports.detectFileType=$;exports.detectMimeFromBuffer=Re;exports.dropSpoofedSelfOnly=Vi;exports.epochSecondsToMs=li;exports.escapeHtml=rs;exports.extractLinks=oi;exports.ffmpegTransform=Q;exports.forwardMessage=Hn;exports.generateId=zt;exports.genericPrune=Qs;exports.getMediaLimits=Or;exports.html=_a;exports.htmlJson=Ra;exports.initializeFFmpeg=Ht;exports.isFatalDisconnect=xt;exports.isJid=it;exports.isLidJid=an;exports.isPnJid=Xs;exports.isRateLimited=un;exports.jidToPhone=Rh;exports.loadMedia=B;exports.makeCacheableAuthStore=Di;exports.mapDisconnectReason=Fi;exports.matchesUser=dn;exports.normalizeJid=je;exports.normalizePhoneNumber=Hc;exports.parseCommand=Yn;exports.parseMexUsers=gu;exports.phoneToJid=nc;exports.pinMessage=on;exports.printQrToTerminal=qi;exports.rawHtml=Oa;exports.reactToMessage=Vn;exports.renderQrInTerminal=Qc;exports.resetCooldowns=Ad;exports.resolveExecutable=Cr;exports.resolveUsername=zn;exports.runBroadcast=ir;exports.runMiddleware=Qn;exports.sameUser=or;exports.senderDeviceOf=ui;exports.shouldClearAuth=Wi;exports.shouldReconnect=Ry;exports.signalKeyStoreFromAuthStore=Bi;exports.validateCloudOptions=hr;exports.validateE164=zc;
|
|
42
|
+
ON CONFLICT(jid) DO UPDATE SET data = excluded.data`),getPresence:t.prepare("SELECT data FROM presence WHERE jid = ?"),clearMessages:t.prepare("DELETE FROM messages"),clearChats:t.prepare("DELETE FROM chats"),clearContacts:t.prepare("DELETE FROM contacts"),clearPresence:t.prepare("DELETE FROM presence"),deleteMessage:t.prepare("DELETE FROM messages WHERE remote_jid = ? AND id = ? AND from_me = ?"),pruneByAge:t.prepare("DELETE FROM messages WHERE timestamp < ?"),pruneByAgeChat:t.prepare("DELETE FROM messages WHERE timestamp < ? AND remote_jid = ?")};}};var Fu=["zaileys_messages","zaileys_chats","zaileys_contacts","zaileys_presence","zaileys_chats_archived_idx","zaileys_messages_jid_ts_idx"],On,Wu=async()=>(On||(On=import('pg').then(n=>n).catch(n=>{throw On=void 0,new g("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),On),Uu=["CREATE TABLE IF NOT EXISTS zaileys_messages (remote_jid text NOT NULL, id text NOT NULL, from_me boolean NOT NULL, timestamp bigint NOT NULL, data jsonb NOT NULL, PRIMARY KEY(remote_jid, id, from_me))","CREATE INDEX IF NOT EXISTS zaileys_messages_jid_ts_idx ON zaileys_messages(remote_jid, timestamp DESC)","CREATE TABLE IF NOT EXISTS zaileys_chats (jid text PRIMARY KEY, archived boolean NOT NULL DEFAULT false, data jsonb NOT NULL)","CREATE INDEX IF NOT EXISTS zaileys_chats_archived_idx ON zaileys_chats(archived) WHERE archived = true","CREATE TABLE IF NOT EXISTS zaileys_contacts (jid text PRIMARY KEY, data jsonb NOT NULL)","CREATE TABLE IF NOT EXISTS zaileys_presence (jid text PRIMARY KEY, data jsonb NOT NULL, updated_at timestamptz NOT NULL DEFAULT now())"],Ie=n=>{if(n==null)return n;let e=typeof n=="string"?n:JSON.stringify(n);return JSON.parse(e,au.BufferJSON.reviver)},Jo=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;boundSocket;listeners=new Map;closed=false;rewrite;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new g("STORE_CONNECTION_FAILED","PostgresMessageStore: provide either pool or connectionString, not both");if(!t&&!r)throw new g("STORE_CONNECTION_FAILED","PostgresMessageStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max,this.rewrite=pe(ue(e.tablePrefix),Fu);}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","PostgresMessageStore is closed")}async ensureReady(){if(this.assertOpen(),this.resolvedPool)return this.resolvedPool;this.readyPromise||(this.readyPromise=(async()=>{let e;if(this.externalPool)e=this.externalPool;else {let t=await Wu(),r=t.Pool??t.default?.Pool;if(!r)throw new g("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}e=Cn(e,this.rewrite);try{for(let t of Uu)await e.query(t);}catch(t){throw new g("STORE_CONNECTION_FAILED","failed to migrate message schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}async saveMessage(e){let t=await this.ensureReady(),r=e.key.remoteJid??"",s=e.key.id??"",i=e.key.fromMe===true,o=Number(e.messageTimestamp??0);try{await t.query("INSERT INTO zaileys_messages(remote_jid, id, from_me, timestamp, data) VALUES ($1, $2, $3, $4, $5::jsonb) ON CONFLICT (remote_jid, id, from_me) DO UPDATE SET data = EXCLUDED.data, timestamp = EXCLUDED.timestamp",[r,s,i,o,JSON.stringify(e,au.BufferJSON.replacer)]);}catch(a){throw new g("STORE_WRITE_FAILED","failed to save message",{cause:a})}}async getMessage(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0])).rows[0];return s?Ie(s.data):void 0}catch(r){throw r instanceof g?r:new g("STORE_READ_FAILED","failed to read message",{cause:r})}}async listMessages(e,t){let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?t.before:null;try{return (await r.query("SELECT data FROM zaileys_messages WHERE remote_jid = $1 AND ($2::bigint IS NULL OR timestamp < $2::bigint) ORDER BY timestamp DESC LIMIT $3",[e,i,s])).rows.map(a=>Ie(a.data))}catch(o){throw new g("STORE_READ_FAILED","failed to list messages",{cause:o})}}async saveChat(e){let t=await this.ensureReady(),r=e.id;if(!r)return;let s=e.archived===true;try{await t.query("INSERT INTO zaileys_chats(jid, archived, data) VALUES ($1, $2, $3::jsonb) ON CONFLICT (jid) DO UPDATE SET archived = EXCLUDED.archived, data = EXCLUDED.data",[r,s,JSON.stringify(e,au.BufferJSON.replacer)]);}catch(i){throw new g("STORE_WRITE_FAILED","failed to save chat",{cause:i})}}async getChat(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_chats WHERE jid = $1",[e])).rows[0];return s?Ie(s.data):void 0}catch(r){throw new g("STORE_READ_FAILED","failed to read chat",{cause:r})}}async listChats(e){let t=await this.ensureReady(),r=typeof e?.archived=="boolean"?e.archived:null;try{return (await t.query("SELECT data FROM zaileys_chats WHERE ($1::boolean IS NULL OR archived = $1::boolean)",[r])).rows.map(i=>Ie(i.data))}catch(s){throw new g("STORE_READ_FAILED","failed to list chats",{cause:s})}}async saveContact(e){let t=await this.ensureReady();try{await t.query("INSERT INTO zaileys_contacts(jid, data) VALUES ($1, $2::jsonb) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data",[e.id,JSON.stringify(e,au.BufferJSON.replacer)]);}catch(r){throw new g("STORE_WRITE_FAILED","failed to save contact",{cause:r})}}async getContact(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_contacts WHERE jid = $1",[e])).rows[0];return s?Ie(s.data):void 0}catch(r){throw new g("STORE_READ_FAILED","failed to read contact",{cause:r})}}async listContacts(){let e=await this.ensureReady();try{return (await e.query("SELECT data FROM zaileys_contacts")).rows.map(r=>Ie(r.data))}catch(t){throw new g("STORE_READ_FAILED","failed to list contacts",{cause:t})}}async savePresence(e,t){let r=await this.ensureReady();try{await r.query("INSERT INTO zaileys_presence(jid, data, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (jid) DO UPDATE SET data = EXCLUDED.data, updated_at = now()",[e,JSON.stringify(t,au.BufferJSON.replacer)]);}catch(s){throw new g("STORE_WRITE_FAILED","failed to save presence",{cause:s})}}async getPresence(e){let t=await this.ensureReady();try{let s=(await t.query("SELECT data FROM zaileys_presence WHERE jid = $1",[e])).rows[0];return s?Ie(s.data):void 0}catch(r){throw new g("STORE_READ_FAILED","failed to read presence",{cause:r})}}async deleteMessage(e){let t=await this.ensureReady();try{await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[e.remoteJid??"",e.id??"",e.fromMe===!0]);}catch(r){throw new g("STORE_WRITE_FAILED","failed to delete message",{cause:r})}}async pruneMessages(e){let t=await this.ensureReady();try{let r=0,s;if(e.chatFilter&&(s=(await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[])).rows.map(o=>o.remote_jid).filter(o=>e.chatFilter(o))),e.olderThan!==void 0){let i=s?await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1 AND remote_jid = ANY($2::text[])",[e.olderThan,s]):await t.query("DELETE FROM zaileys_messages WHERE timestamp < $1",[e.olderThan]);r+=i.rowCount??0;}if(e.maxPerChat!==void 0){let i=s??await t.query("SELECT DISTINCT remote_jid FROM zaileys_messages",[]).then(o=>o.rows.map(a=>a.remote_jid));for(let o of i){let d=(await t.query("SELECT id, from_me FROM zaileys_messages WHERE remote_jid = $1 ORDER BY timestamp DESC",[o])).rows.slice(e.maxPerChat);if(d.length!==0)for(let c of d){let l=await t.query("DELETE FROM zaileys_messages WHERE remote_jid = $1 AND id = $2 AND from_me = $3",[o,c.id,c.from_me]);r+=l.rowCount??0;}}}return r}catch(r){throw new g("STORE_WRITE_FAILED","failed to prune messages",{cause:r})}}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...d)=>{let l=d[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.getMessage(l.key).then(u=>{if(!u)return;let f={...u,...l.update};return this.saveMessage(f)}).catch(()=>{});},s=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveChat(l).catch(()=>{});},i=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.getChat(l.id).then(u=>{let f={...u??{},...l};return this.saveChat(f)}).catch(()=>{});},o=(...d)=>{let c=d[0];if(Array.isArray(c))for(let l of c)this.saveContact(l).catch(()=>{});},a=(...d)=>{let c=d[0];if(c?.presences)for(let l of Object.keys(c.presences)){let u=c.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[d,c]of this.listeners)e.ev.on(d,c);}async clear(){let e=await this.ensureReady(),t;try{t=await e.connect(),await t.query("BEGIN"),await t.query("DELETE FROM zaileys_messages"),await t.query("DELETE FROM zaileys_chats"),await t.query("DELETE FROM zaileys_contacts"),await t.query("DELETE FROM zaileys_presence"),await t.query("COMMIT");}catch(r){if(t)try{await t.query("ROLLBACK");}catch{}throw new g("STORE_WRITE_FAILED","failed to clear message tables",{cause:r})}finally{t?.release();}}async reopen(){this.closed=false;}async close(){if(this.closed)return;if(this.closed=true,this.boundSocket?.ev.off)for(let[t,r]of this.listeners)this.boundSocket.ev.off(t,r);this.listeners.clear(),this.boundSocket=void 0;let e=this.ownedPool;if(this.ownedPool=void 0,this.resolvedPool=void 0,this.readyPromise=void 0,e)try{await e.end();}catch{}}};var ju=n=>{if(n===void 0)return "(no url)";try{let e=new URL(n);return e.password!==""&&(e.password="***"),e.username!==""&&(e.username="***"),e.toString()}catch{return "(redacted redis url)"}},qu="zaileys",$u=Object.freeze(["msg:*","msg-data:*","presence:*","chats","chats-archived","contacts"]),Ku=n=>{if(!/^[A-Za-z0-9_.:-]+$/.test(n))throw new g("STORE_CONNECTION_FAILED",`invalid namespace ${JSON.stringify(n)}: use letters, digits, and _ . : - only`);return n},Gu=300,Vo=1e3,br=n=>`${n.id??""}|${n.fromMe?1:0}`,Ju=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Ho=class{namespace;externalClient;url;ownedClient;ready;closed=false;boundSocket;listeners=new Map;constructor(e){if(e.client&&e.url)throw new g("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new g("STORE_CONNECTION_FAILED","RedisMessageStore requires either client or url");this.namespace=Ku(e.namespace??qu),this.externalClient=e.client,this.url=e.url;}async saveMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.key.remoteJid??"",s=br(e.key),i=Number(e.messageTimestamp??0),o=JSON.stringify(e,au.BufferJSON.replacer),a=t.multi();a.zAdd(this.msgIndexKey(r),{score:i,value:s}),a.hSet(this.msgDataKey(r),s,o),await this.runWrite(()=>a.exec());}async getMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=await this.runRead(()=>t.hGet(this.msgDataKey(r),br(e)));if(s!=null)return JSON.parse(s,au.BufferJSON.reviver)}async listMessages(e,t){this.assertOpen();let r=await this.ensureReady(),s=t?.limit??100,i=typeof t?.before=="number"?`(${t.before}`:"+inf",o=this.msgIndexKey(e),a=r.zRange,d=await this.runRead(async()=>{if(typeof a=="function")try{return await a.call(r,o,i,"-inf",{BY:"SCORE",REV:!0,LIMIT:{offset:0,count:s}})}catch{}return [...await r.zRangeByScore(o,"-inf",i)].reverse().slice(0,s)});if(d.length===0)return [];let c=d.slice(0,s),l=await this.runRead(()=>r.hmGet(this.msgDataKey(e),c)),u=[];for(let f of l)f!=null&&u.push(JSON.parse(f,au.BufferJSON.reviver));return u}async saveChat(e){this.assertOpen();let t=e.id;if(!t)return;let s=(await this.ensureReady()).multi();s.hSet(this.chatsKey(),t,JSON.stringify(e,au.BufferJSON.replacer)),e.archived===true?s.sAdd(this.chatsArchiveKey(),t):s.sRem(this.chatsArchiveKey(),t),await this.runWrite(()=>s.exec());}async getChat(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.chatsKey(),e));if(r!=null)return JSON.parse(r,au.BufferJSON.reviver)}async listChats(e){this.assertOpen();let t=await this.ensureReady();if(e?.archived===true){let i=await this.runRead(()=>t.sMembers(this.chatsArchiveKey()));if(i.length===0)return [];let o=await this.runRead(()=>t.hmGet(this.chatsKey(),i)),a=[];for(let d of o)d!=null&&a.push(JSON.parse(d,au.BufferJSON.reviver));return a}let r=await this.runRead(()=>t.hGetAll(this.chatsKey())),s=[];for(let i of Object.keys(r)){let o=r[i];if(o==null)continue;let a=JSON.parse(o,au.BufferJSON.reviver);e?.archived===false&&await this.runRead(()=>t.sIsMember(this.chatsArchiveKey(),i))||s.push(a);}return s}async saveContact(e){this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.hSet(this.contactsKey(),e.id,JSON.stringify(e,au.BufferJSON.replacer)));}async getContact(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.hGet(this.contactsKey(),e));if(r!=null)return JSON.parse(r,au.BufferJSON.reviver)}async listContacts(){this.assertOpen();let e=await this.ensureReady(),t=await this.runRead(()=>e.hGetAll(this.contactsKey())),r=[];for(let s of Object.keys(t)){let i=t[s];i!=null&&r.push(JSON.parse(i,au.BufferJSON.reviver));}return r}async savePresence(e,t){this.assertOpen();let r=await this.ensureReady();await this.runWrite(()=>r.set(this.presenceKey(e),JSON.stringify(t,au.BufferJSON.replacer),{EX:Gu}));}async getPresence(e){this.assertOpen();let t=await this.ensureReady(),r=await this.runRead(()=>t.get(this.presenceKey(e)));if(r!=null)return JSON.parse(r,au.BufferJSON.reviver)}bind(e){if(this.assertOpen(),this.boundSocket&&this.boundSocket.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let d=o[0]?.messages;if(Array.isArray(d))for(let c of d)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveChat(d).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveContact(d).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let d of Object.keys(a.presences)){let c=a.presences[d];c&&this.savePresence(d,c).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen();let e=await this.ensureReady();for(let t of $u){let r=`${this.namespace}:${t}`,s=0;do{let i=await this.runRead(()=>e.scan(s,{MATCH:r,COUNT:Vo}));s=Number(i.cursor),i.keys.length>0&&await this.runWrite(()=>e.del(i.keys));}while(s!==0)}}async reopen(){this.closed=false;}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);if(this.listeners.clear(),this.boundSocket=void 0,this.ownedClient){try{await this.ownedClient.quit();}catch{}this.ownedClient=void 0;}this.ready=void 0;}}async deleteMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.remoteJid??"",s=br(e),i=t.multi();i.zRem(this.msgIndexKey(r),s),i.hDel(this.msgDataKey(r),s),await this.runWrite(()=>i.exec());}async pruneMessages(e){this.assertOpen();let t=await this.ensureReady(),r=0,s=[],i=this.msgIndexKey("*"),o=0,a=this.msgDataKey("");do{let d=await this.runRead(()=>t.scan(o,{MATCH:i,COUNT:Vo}));o=Number(d.cursor);for(let c of d.keys)c.startsWith(a)||s.push(c);}while(o!==0);for(let d of s){let c=this.jidFromIndexKey(d);if(e.chatFilter&&!e.chatFilter(c))continue;let l=this.msgDataKey(c),u=new Set;if(e.olderThan!==void 0){let S=await this.runRead(()=>t.zRangeByScore(d,"-inf",`(${e.olderThan}`));for(let T of S)u.add(T);}if(e.maxPerChat!==void 0){let S=e.maxPerChat,T=await this.runRead(()=>t.zRange(d,0,-(S+1)));for(let O of T)u.add(O);}if(u.size===0)continue;let f=[...u],v=t.multi();v.zRem(d,f),v.hDel(l,f),await this.runWrite(()=>v.exec()),r+=f.length;}return r}jidFromIndexKey(e){let t=this.msgIndexKey("");return e.startsWith(t)?e.slice(t.length):e}msgIndexKey(e){return `${this.namespace}:msg:${e}`}msgDataKey(e){return `${this.namespace}:msg-data:${e}`}chatsKey(){return `${this.namespace}:chats`}chatsArchiveKey(){return `${this.namespace}:chats-archived`}contactsKey(){return `${this.namespace}:contacts`}presenceKey(e){return `${this.namespace}:presence:${e}`}async ensureReady(){return this.ready||(this.ready=this.connect()),this.ready}async connect(){if(this.externalClient){if(!this.externalClient.isOpen)throw new g("STORE_CONNECTION_FAILED","provided redis client is not open (call await client.connect() first)");return this.externalClient}let e;try{e=await import('redis');}catch(r){throw Ju(r)?new g("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new g("STORE_CONNECTION_FAILED","failed to load redis module",{cause:r})}let t=e.createClient({url:this.url});try{await t.connect();}catch(r){throw new g("STORE_CONNECTION_FAILED",`failed to connect to redis at ${ju(this.url)}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new g("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new g("STORE_WRITE_FAILED","redis write failed",{cause:t})}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","RedisMessageStore is closed")}};var Gt="msg:",$t="chat:",Kt="contact:",_n="presence:",Ln="job:",Vu=Object.freeze([Gt,$t,Kt,_n,Ln]),Hu=n=>`${n.id??""}|${n.fromMe?1:0}`,Rn=n=>`${Gt}${n.remoteJid??""}:${Hu(n)}`,qt=n=>JSON.stringify(n,au.BufferJSON.replacer),zu=n=>{let e=n.slice(Gt.length),t=e.lastIndexOf("|"),r=e.lastIndexOf(":",t===-1?e.length:t);return r===-1?e:e.slice(0,r)},me=n=>JSON.parse(n,au.BufferJSON.reviver),zo=class{kv;closed=false;boundSocket;listeners=new Map;constructor(e){this.kv=new Ve(e);}async saveMessage(e){this.assertOpen(),await this.kv.set([{key:Rn(e.key),value:qt(e),sortKey:Number(e.messageTimestamp??0)}]);}async getMessage(e){this.assertOpen();let r=(await this.kv.get([Rn(e)])).get(Rn(e));return r===void 0?void 0:me(r)}async listMessages(e,t){this.assertOpen();let r={};return typeof t?.before=="number"&&(r.before=t.before),typeof t?.limit=="number"&&(r.limit=t.limit),(await this.kv.list(`${Gt}${e}:`,r)).map(i=>me(i.value))}async saveChat(e){this.assertOpen();let t=e.id;t&&await this.kv.set([{key:`${$t}${t}`,value:qt(e)}]);}async getChat(e){this.assertOpen();let r=(await this.kv.get([`${$t}${e}`])).get(`${$t}${e}`);return r===void 0?void 0:me(r)}async listChats(e){this.assertOpen();let t=await this.kv.list($t),r=[];for(let s of t){let i=me(s.value),o=i.archived===true;e?.archived===true&&!o||e?.archived===false&&o||r.push(i);}return r}async saveContact(e){this.assertOpen(),await this.kv.set([{key:`${Kt}${e.id}`,value:qt(e)}]);}async getContact(e){this.assertOpen();let r=(await this.kv.get([`${Kt}${e}`])).get(`${Kt}${e}`);return r===void 0?void 0:me(r)}async listContacts(){return this.assertOpen(),(await this.kv.list(Kt)).map(t=>me(t.value))}async savePresence(e,t){this.assertOpen(),await this.kv.set([{key:`${_n}${e}`,value:qt(t)}]);}async getPresence(e){this.assertOpen();let r=(await this.kv.get([`${_n}${e}`])).get(`${_n}${e}`);return r===void 0?void 0:me(r)}async saveScheduledJob(e){this.assertOpen(),await this.kv.set([{key:`${Ln}${e.id}`,value:qt(e),sortKey:e.fireAt}]);}async listScheduledJobs(){return this.assertOpen(),(await this.kv.list(Ln)).map(t=>me(t.value))}async deleteScheduledJob(e){this.assertOpen(),await this.kv.del([`${Ln}${e}`]);}async deleteMessage(e){this.assertOpen(),await this.kv.del([Rn(e)]);}async pruneMessages(e){this.assertOpen();let t=await this.kv.list(Gt,{}),r=new Map;for(let i of t){let o=zu(i.key);if(e.chatFilter&&!e.chatFilter(o))continue;let a=r.get(o)??[];a.push({key:i.key,ts:i.sortKey??0}),r.set(o,a);}let s=[];for(let i of r.values()){i.sort((o,a)=>a.ts-o.ts);for(let o=0;o<i.length;o++){let a=i[o];(e.olderThan!==void 0&&a.ts<e.olderThan||e.maxPerChat!==void 0&&o>=e.maxPerChat)&&s.push(a.key);}}return s.length>0&&await this.kv.del(s),s.length}bind(e){if(this.assertOpen(),this.boundSocket?.ev.off)for(let[o,a]of this.listeners)this.boundSocket.ev.off(o,a);this.listeners.clear(),this.boundSocket=e;let t=(...o)=>{let a=o[0]?.messages;if(Array.isArray(a))for(let d of a)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveChat(d).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let d of a)this.saveContact(d).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let d of Object.keys(a.presences)){let c=a.presences[d];c&&this.savePresence(d,c).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("chats.upsert",r),this.listeners.set("contacts.upsert",s),this.listeners.set("presence.update",i);for(let[o,a]of this.listeners)e.ev.on(o,a);}async clear(){this.assertOpen();for(let e of Vu)await this.kv.clear(e);}async reopen(){this.closed=false,this.kv.reopen();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);this.listeners.clear(),this.boundSocket=void 0,this.kv.close();}}assertOpen(){if(this.closed)throw new g("STORE_CLOSED","ConvexMessageStore is closed")}};var Yu=(n,e)=>{if(e<=0)throw new RangeError("chunk size must be positive");let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t};Object.defineProperty(exports,"areJidsSameUser",{enumerable:true,get:function(){return au.areJidsSameUser}});Object.defineProperty(exports,"getDevice",{enumerable:true,get:function(){return au.getDevice}});Object.defineProperty(exports,"isJidBroadcast",{enumerable:true,get:function(){return au.isJidBroadcast}});Object.defineProperty(exports,"isJidGroup",{enumerable:true,get:function(){return au.isJidGroup}});Object.defineProperty(exports,"isJidNewsletter",{enumerable:true,get:function(){return au.isJidNewsletter}});Object.defineProperty(exports,"isLidUser",{enumerable:true,get:function(){return au.isLidUser}});Object.defineProperty(exports,"isPnUser",{enumerable:true,get:function(){return au.isPnUser}});Object.defineProperty(exports,"jidDecode",{enumerable:true,get:function(){return au.jidDecode}});Object.defineProperty(exports,"jidEncode",{enumerable:true,get:function(){return au.jidEncode}});Object.defineProperty(exports,"jidNormalizedUser",{enumerable:true,get:function(){return au.jidNormalizedUser}});exports.AudioProcessor=we;exports.AutoDeleteSweeper=Mt;exports.AutoRejectCallModule=bt;exports.BufferConverter=R;exports.BusinessModule=mt;exports.ChatModule=ut;exports.Client=_o;exports.CloudModule=Nt;exports.CloudTransport=Je;exports.CommandRegistry=gt;exports.CommunityModule=ct;exports.ContactModule=pt;exports.ConvexAuthStore=$o;exports.ConvexMessageStore=zo;exports.DEFAULT_CLEAR_AUTH_REASONS=pr;exports.DEFAULT_GRAPH_VERSION=Mn;exports.DocumentProcessor=Xt;exports.EditBuilder=st;exports.FFMPEG_CONSTANTS=P;exports.FFmpegProcessor=he;exports.FileAuthStore=It;exports.FileManager=se;exports.GroupModule=ot;exports.HTML_APP_MAX_BYTES=as;exports.ImageProcessor=V;exports.Media=ve;exports.MemoryAuthStore=Lo;exports.MemoryMessageStore=fn;exports.MessageBuilder=ae;exports.MimeValidator=q;exports.NewsletterModule=dt;exports.PostgresAuthStore=jo;exports.PostgresMessageStore=Jo;exports.PresenceModule=wt;exports.PrivacyModule=at;exports.ProfileModule=lt;exports.RateLimiter=be;exports.RedisAuthStore=qo;exports.RedisMessageStore=Ho;exports.SELF_ONLY_PROTOCOL_TYPES=Hi;exports.SafeHtml=ee;exports.Scheduler=vt;exports.SqliteAuthStore=Uo;exports.SqliteMessageStore=Ko;exports.StickerProcessor=Ne;exports.TaskQueue=yt;exports.TypedEventEmitter=vn;exports.VideoProcessor=X;exports.ZaileysAutomationError=N;exports.ZaileysBuilderError=p;exports.ZaileysCloudError=C;exports.ZaileysCommandError=j;exports.ZaileysDomainError=L;exports.ZaileysProviderError=_t;exports.ZaileysStoreError=g;exports.adoptLogger=mr;exports.attachCommandDispatcher=tr;exports.buildMessageContext=dr;exports.checkGuards=er;exports.chunk=Yu;exports.computeStaticId=ui;exports.computeUniqueId=li;exports.configureMediaLimits=_r;exports.createAuthGuard=qi;exports.createConnectionStateMachine=Ji;exports.createLogger=sl;exports.createOperationGuard=ir;exports.createPairingFlow=$i;exports.createReconnectStrategy=Gi;exports.createWebhookHandler=Mr;exports.definePlugin=zs;exports.deleteMessage=Vn;exports.detectFileType=$;exports.detectMimeFromBuffer=Re;exports.dropSpoofedSelfOnly=zi;exports.epochSecondsToMs=pi;exports.escapeHtml=ss;exports.extractLinks=di;exports.ffmpegTransform=Q;exports.forwardMessage=zn;exports.generateId=zt;exports.genericPrune=Zs;exports.getMediaLimits=Rr;exports.html=Na;exports.htmlJson=La;exports.initializeFFmpeg=Ht;exports.isFatalDisconnect=xt;exports.isJid=it;exports.isLidJid=dn;exports.isPnJid=ei;exports.isRateLimited=pn;exports.jidToPhone=Lh;exports.loadMedia=B;exports.makeCacheableAuthStore=Fi;exports.mapDisconnectReason=Ui;exports.matchesUser=cn;exports.normalizeJid=je;exports.normalizePhoneNumber=zc;exports.parseCommand=Qn;exports.parseMexUsers=fu;exports.phoneToJid=rc;exports.pinMessage=an;exports.printQrToTerminal=Ki;exports.rawHtml=_a;exports.reactToMessage=Hn;exports.renderQrInTerminal=Xc;exports.resetCooldowns=Cd;exports.resolveExecutable=Er;exports.resolveUsername=Yn;exports.runBroadcast=or;exports.runMiddleware=Xn;exports.sameUser=ar;exports.senderDeviceOf=mi;exports.shouldClearAuth=ji;exports.shouldReconnect=Ly;exports.signalKeyStoreFromAuthStore=Wi;exports.validateCloudOptions=yr;exports.validateE164=Yc;
|