zaileys 4.0.4 → 4.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,18 +1,19 @@
1
- 'use strict';var Di=require('baileys'),se=require('node:fs/promises'),url=require('node:url'),os$1=require('node:os'),we=require('node:path'),child_process=require('node:child_process'),jimp=require('jimp'),Qr=require('node-webpmux'),crypto=require('node:crypto'),fs$1=require('node:fs'),Gs=require('qrcode-terminal'),Ys=require('pino');require('node:stream');var events=require('node:events');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Di__default=/*#__PURE__*/_interopDefault(Di);var se__default=/*#__PURE__*/_interopDefault(se);var we__default=/*#__PURE__*/_interopDefault(we);var Qr__default=/*#__PURE__*/_interopDefault(Qr);var Gs__default=/*#__PURE__*/_interopDefault(Gs);var Ys__default=/*#__PURE__*/_interopDefault(Ys);var qr=(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 m=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 w={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"}},$t="ffmpeg",Vt="ffprobe",qt=false,gt=async(n=false)=>{if(!(n||qt)){qt=true;try{let e=(await import('@ffmpeg-installer/ffmpeg')).default;if(e?.path){$t=e.path;let t=we__default.default.dirname(e.path),r=process.platform==="win32"?";":":",s=process.env.PATH??"";s.split(r).includes(t)||(process.env.PATH=`${t}${r}${s}`);}}catch{}try{let e=(await import('@ffprobe-installer/ffprobe')).default;e?.path&&(Vt=e.path);}catch{}}},Le=()=>Date.now().toString(36)+Math.random().toString(36).slice(2,8),P=async n=>{let{fileTypeFromBuffer:e}=await import('file-type');return e(n)},W=class{static generateUniqueId(){return `${Date.now()}_${Math.random().toString(36).slice(2,11)}`}static createTempPath(e,t){return we__default.default.join(os$1.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>se__default.default.unlink(t)));}static async safeReadFile(e){try{return await se__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await se__default.default.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},S=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 se__default.default.stat(e).then(t=>t.isFile()).catch(()=>!1))return await se__default.default.readFile(e)}catch{}return Buffer.from(e,"base64")}static async fromUrl(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let r=await t.arrayBuffer();return Buffer.from(r)}catch(t){throw new Error(`Failed to fetch URL: ${t instanceof Error?t.message:String(t)}`)}}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"}},C=class{static validate(e,t){if(!e?.mime?.startsWith(t))throw new Error(`Invalid file type: expected ${t}*, got ${e?.mime||"unknown"}`)}static isMedia(e){return e.startsWith(w.MIME.IMAGE)||e.startsWith(w.MIME.VIDEO)}static isAnimated(e){return e===w.MIME.GIF||e.startsWith(w.MIME.VIDEO)}},J=class{static async process(e){return await gt(),new Promise((t,r)=>{let s=["-y","-i",e.input,...e.options,e.output],i=child_process.spawn($t,s,{stdio:"ignore"});i.on("close",async o=>{if(o===0)try{await e.onEnd(),t();}catch(a){r(a);}else try{let a=new Error(`FFmpeg exited with code ${o}`);await e.onError(a),r(a);}catch(a){r(a);}}),i.on("error",async o=>{try{await e.onError(o);}finally{r(o);}});})}static async getDuration(e){return new Promise((t,r)=>{let s=child_process.spawn(Vt,["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),i="";s.stdout.on("data",o=>i+=o.toString()),s.on("close",o=>{o===0?t(parseFloat(i.trim())||0):r(new Error(`ffprobe exited with code ${o}`));}),s.on("error",r);})}};var Gr=3e4,Gt="application/octet-stream",Hr=async n=>n.byteLength===0?Gt:(await P(n))?.mime??Gt,ie=async n=>({buffer:n,mime:await Hr(n),size:n.byteLength}),Ht=async(n,e)=>{let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{let s=await fetch(n,{signal:t.signal});if(!s.ok)throw new m("MEDIA_LOAD_FAILED",`fetch ${n} failed with status ${s.status}`,{cause:s.status});return Buffer.from(await s.arrayBuffer())}catch(s){throw s instanceof m?s:new m("MEDIA_LOAD_FAILED",`fetch ${n} failed: ${s.message}`,{cause:s})}finally{clearTimeout(r);}},zt=async n=>{try{return await se.readFile(n)}catch(e){throw new m("MEDIA_LOAD_FAILED",`read ${n} failed: ${e.message}`,{cause:e})}},zr=n=>n.startsWith("http://")||n.startsWith("https://"),T=async(n,e)=>{await gt();let t=Gr;return Buffer.isBuffer(n)?ie(n):n instanceof URL?n.protocol==="file:"?ie(await zt(url.fileURLToPath(n))):ie(await Ht(n.toString(),t)):zr(n)?ie(await Ht(n,t)):ie(await zt(n))};var Q=async(n,e)=>{let{buffer:t}=await T(n),r={image:t};return e?.caption!==void 0&&(r.caption=e.caption),e?.viewOnce!==void 0&&(r.viewOnce=e.viewOnce),r};var ee=async(n,e)=>{let{buffer:t,mime:r}=await T(n);if(!r.startsWith("video/"))throw new m("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),s};var Yt=2,Zt=30,Yr=async n=>{if(n.type==="image")return Q(n.src,n.caption!==void 0?{caption:n.caption}:void 0);if(n.type==="video")return ee(n.src,n.caption!==void 0?{caption:n.caption}:void 0);throw new m("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(n.type)}`)},Xt=async(n,e,t,r)=>{if(!Array.isArray(t)||t.length<Yt)throw new m("INVALID_OPTIONS",`album() requires a minimum of ${Yt} items`);if(t.length>Zt)throw new m("INVALID_OPTIONS",`album() accepts a maximum of ${Zt} items`);let s=0,i=0;for(let l of t)if(l.type==="image")s+=1;else if(l.type==="video")i+=1;else throw new m("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(l.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 c;try{c=await n.sendMessage(e,o,a);}catch(l){throw new m("SEND_FAILED","album parent send rejected",{cause:l})}let d=c?.key;if(!d)throw new m("SEND_FAILED","album parent returned no message key");let u=0;for(let l of t){let y=await Yr(l);y.albumParentKey=d;try{await n.sendMessage(e,y);}catch(f){throw new m("SEND_FAILED","album child send rejected",{cause:{parentKey:d,index:u,error:f}})}u+=1;}return d};var _=async(n,e,t,r,s)=>{let i=r.replace(/[^a-z0-9]+/gi,"_").toLowerCase(),o=W.createTempPath(`${i}_in`,e),a=W.createTempPath(`${i}_out`,t);await W.safeWriteFile(o,n);try{let c=typeof s=="function"?await s(o):s;return await J.process({input:o,output:a,options:c,onEnd:async()=>{},onError:async()=>{}}),await W.safeReadFile(a)}catch(c){throw new Error(`${r} failed: ${c instanceof Error?c.message:String(c)}`)}finally{await W.cleanup([o,a]);}};var _e=64,Qt=8e3,$=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 S.toBuffer(e);C.validate(await P(r),w.MIME.AUDIO);let s=await S.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 _(r,s,t==="opus"?"ogg":"mp3",`${t.toUpperCase()} conversion`,i)}static async waveform(e){let t=await S.toBuffer(e),r=await S.getExtension(t),s=await _(t,r,"tmp","Waveform generation",["-vn","-ac","1","-ar",String(Qt),"-f","s16le"]),i=Math.floor(s.length/2);return {waveform:this.computeWaveform(s),seconds:Math.max(1,Math.round(i/Qt))}}static computeWaveform(e){let t=Math.floor(e.length/2),r=new Uint8Array(_e);if(t===0)return r;let s=Math.max(1,Math.floor(t/_e)),i=[];for(let a=0;a<_e;a++){let c=0,d=0;for(let u=0;u<s;u++){let l=(a*s+u)*2;l+1<e.length&&(c+=Math.abs(e.readInt16LE(l)),d+=1);}i.push(d>0?c/d:0);}let o=Math.max(...i)||1;for(let a=0;a<_e;a++)r[a]=Math.floor(i[a]/o*100);return r}};var Zr=["-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"],N=class{static async toMp4(e){let t=await S.toBuffer(e);C.validate(await P(t),w.MIME.VIDEO);let r=await S.getExtension(t);return _(t,r,"mp4","Video re-encoding",Zr)}static async thumbnail(e){let t=await S.toBuffer(e);C.validate(await P(t),w.MIME.VIDEO);let r=await S.getExtension(t),s=w.THUMBNAIL.SIZE;return (await _(t,r,"jpg","Thumbnail generation",async o=>{let a=await J.getDuration(o);return ["-ss",Math.max(0,a*.1).toString(),"-vframes","1","-s",`${s}x${s}`]})).toString("base64")}static async duration(e){return J.getDuration(e)}};var te=null,en=false;async function Xr(){if(en)return te;en=true;let n=e=>{typeof e=="function"&&(te=e);};try{n(qr("sharp"));}catch{te=null;}if(!te)try{let e=await import('sharp');n(e.default??e);}catch{te=null;}return te}function tn(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 c=0;c<n;c++){let d=false;if(e==="circle"){let u=c-r,l=a-s;d=u*u+l*l<=r*r;}else if(e==="rounded"){let u=c>=i&&c<n-i&&a>=0&&a<n,l=c>=0&&c<n&&a>=i&&a<n-i,y=false;for(let f of o){let g=c-f[0],h=a-f[1];if(g*g+h*h<=i*i){y=true;break}}d=u||l||y;}else if(e==="oval"){let u=(c-r)/(n/2),l=(a-s)/(n/3);d=u*u+l*l<=1;}t[a*n+c]=d?255:0;}return t}var ht=class{sharp;constructor(e){this.sharp=e;}async thumbnail(e){let t=this.sharp,r=t(e).resize(w.THUMBNAIL.SIZE,w.THUMBNAIL.SIZE,{fit:"cover"});return (await r.metadata()).format==="gif"&&(r=t(e,{pages:1}).resize(w.THUMBNAIL.SIZE,w.THUMBNAIL.SIZE)),(await r.jpeg({quality:w.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}async resize(e,t,r){return this.sharp(e).resize(t,r,{fit:"cover"}).png().toBuffer()}async toJpeg(e){let t=this.sharp,r=await S.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=w.STICKER.SIZE,o=s(e).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}});if(r!=="default"){let a=Buffer.from(tn(i,r)),c=s(a,{raw:{width:i,height:i,channels:1}});o=o.joinChannel(await c.png().toBuffer());}return o.webp({quality:t}).toBuffer()}},yt=class{async thumbnail(e){let t=w.THUMBNAIL.SIZE,r=await jimp.Jimp.fromBuffer(e);r.cover({w:t,h:t});let s=await r.getBuffer("image/jpeg",{quality:w.THUMBNAIL.QUALITY});return Buffer.from(s).toString("base64")}async resize(e,t,r){let s=await jimp.Jimp.fromBuffer(e);s.cover({w:t,h:r});let i=await s.getBuffer("image/png");return Buffer.from(i)}async toJpeg(e){let t=await S.toBuffer(e);try{let s=await(await jimp.Jimp.fromBuffer(t)).getBuffer("image/jpeg");return Buffer.from(s)}catch{return t}}async resizeForSticker(e,t,r="default"){let s=w.STICKER.SIZE,i=await jimp.Jimp.fromBuffer(e);if(i.contain({w:s,h:s}),r!=="default"){let c=tn(s,r),d=new jimp.Jimp({width:s,height:s,color:255});for(let u=0;u<s;u++)for(let l=0;l<s;l++)c[u*s+l]===255&&d.setPixelColor(4294967295,l,u);i.mask(d);}let o=Buffer.from(await i.getBuffer("image/png")),a=Math.max(1,Math.min(100,t));return _(o,"png","webp","Jimp WebP conversion",["-vcodec","libwebp","-q:v",`${a}`,"-preset","default"])}},ae=null;async function Ne(){if(ae)return ae;let n=await Xr();return n?ae=new ht(n):(console.warn("\x1B[33m%s\x1B[0m","[media-process] Jimp is slow. For faster performance, run: npm install sharp"),ae=new yt),ae}var x=class{static async thumbnail(e){return (await Ne()).thumbnail(e)}static async resize(e,t,r){return (await Ne()).resize(e,t,r)}static async toJpeg(e){return (await Ne()).toJpeg(e)}static async resizeForSticker(e,t,r="default"){return (await Ne()).resizeForSticker(e,t,r)}};var De=class{static async create(e,t){try{let r=await S.toBuffer(e),s=await P(r);if(!s)throw new Error("Unable to detect file type");let i=t?.quality||w.STICKER.DEFAULT_QUALITY,o=C.isAnimated(s.mime),a=t?.shape||"default",c=s.mime==="image/webp"?r:o?await this.processAnimated(r,s.mime,i):await x.resizeForSticker(r,i,a),d=this.createExifMetadata(t),u=new Qr__default.default.Image;await u.load(c),u.exif=d;let l=await u.save(null);return Buffer.isBuffer(l)?l:Buffer.from(l)}catch(r){throw new Error(`Sticker creation failed: ${r instanceof Error?r.message:String(r)}`)}}static createExifMetadata(e){let t={"sticker-pack-id":Le(),"sticker-pack-name":e?.packageName||"Zaileys Library","sticker-pack-publisher":e?.authorName||"https://github.com/zeative/zaileys",emojis:["\u{1F913}"],"android-app-store-link":"https://play.google.com/store/apps/details?id=com.marsvard.stickermakerforwhatsapp","ios-app-store-link":"https://itunes.apple.com/app/sticker-maker-studio/id1443326857"},r=Buffer.from([73,73,42,0,8,0,0,0,1,0,65,87,7,0,0,0,0,0,22,0,0,0]),s=Buffer.from(JSON.stringify(t),"utf8"),i=Buffer.concat([r,s]);return i.writeUIntLE(s.length,14,4),i}static async processAnimated(e,t,r){let s=w.STICKER.SIZE,i=w.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 _(e,this.getExtension(t),"webp","Animated sticker processing",async c=>{let d=w.STICKER.MAX_DURATION;try{d=Math.min(await N.duration(c),w.STICKER.MAX_DURATION);}catch{console.warn("Using default duration:",w.STICKER.MAX_DURATION);}return ["-vcodec libwebp",`-vf ${o}`,`-q:v ${a}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${d}`,`-compression_level ${w.STICKER.COMPRESSION_LEVEL}`]})}static getExtension(e){return e===w.MIME.GIF?"gif":e.startsWith(w.MIME.VIDEO)?"mp4":"tmp"}};var Be=class{static async create(e){try{let t=await S.toBuffer(e),r=await P(t);if(!r)throw new Error("Unable to detect file type");let s;return r.mime.startsWith(w.MIME.VIDEO)?s=await N.thumbnail(t):C.isMedia(r.mime)?s=await x.thumbnail(t):s="",{document:t,mimetype:r.mime,ext:r.ext,fileName:Le(),jpegThumbnail:s}}catch(t){throw new Error(`Document creation failed: ${t instanceof Error?t.message:String(t)}`)}}};var V=class{input;constructor(e){this.input=e;}get audio(){return {toOpus:()=>$.toOpus(this.input),toMp3:()=>$.toMp3(this.input),convert:(e="opus")=>$.convert(this.input,e),waveform:()=>$.waveform(this.input)}}get video(){return {toMp4:()=>N.toMp4(this.input),thumbnail:()=>N.thumbnail(this.input)}}get image(){return {toJpeg:()=>x.toJpeg(this.input),thumbnail:async()=>{let e=await S.toBuffer(this.input);return x.thumbnail(e)},resize:async(e,t)=>{let r=await S.toBuffer(this.input);return x.resize(r,e,t)}}}get sticker(){return {create:e=>De.create(this.input,e)}}get document(){return {create:()=>Be.create(this.input)}}get thumbnail(){return {get:async()=>{let e=await S.toBuffer(this.input),t=await P(e);if(!t||!C.isMedia(t.mime))throw new Error("Invalid media type: expected image or video");return t.mime.startsWith(w.MIME.VIDEO)?N.thumbnail(this.input):x.thumbnail(e)}}}async toBuffer(){return S.toBuffer(this.input)}};var nn=async(n,e)=>{let{buffer:t}=await T(n),r;try{r=await new V(t).audio.toOpus();}catch(o){throw new m("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 V(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 rn=10,R="__zaileysRelayMessage",wt="__zaileysHeaderMedia",U=n=>typeof n=="string"&&n.length>0,es=n=>{let e=n.text;if(!U(e)||e.trim().length===0)throw new m("INVALID_OPTIONS","button text must be a non-empty string");return e},ts=(n,e)=>{let t=n.type??"reply";if(t==="location"){let s=n.text;return {name:"send_location",buttonParamsJson:JSON.stringify(U(s)?{display_text:s}:{})}}let r=es(n);if(t==="reply"){let s=n.id;if(!U(s))throw new m("INVALID_OPTIONS","reply button requires a non-empty id");if(e.has(s))throw new m("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(!U(s))throw new m("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,webview_interaction:i})}}if(t==="copy"){let s=n.code;if(!U(s))throw new m("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(!U(s))throw new m("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:U(s)?s:r})}}if(t==="address"){let s=n.id;return {name:"address_message",buttonParamsJson:JSON.stringify({display_text:r,id:U(s)?s:r})}}throw new m("INVALID_OPTIONS",`unknown button type: ${String(t)}`)},ns=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):""},St=n=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","buttons() requires at least one button");if(n.length>rn)throw new m("INVALID_OPTIONS",`buttons() accepts at most ${rn} buttons`);let e=new Set;return n.map(t=>ts(t,e))},Fe=(n,e)=>{let t=St(n),r={body:{text:e?.text&&e.text.length>0?e.text:" "},nativeFlowMessage:{buttons:t,messageParamsJson:ns(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?{[R]:{interactiveMessage:r},[wt]:s}:{[R]:{interactiveMessage:r}}};var sn=10,vt="__zaileysCardsMedia",on=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","carousel() requires at least one card");if(n.length>sn)throw new m("INVALID_OPTIONS",`carousel() accepts at most ${sn} cards`);let t=[],r=n.map((o,a)=>{let c={body:{text:o.body&&o.body.length>0?o.body:" "}};o.buttons&&o.buttons.length>0&&(c.nativeFlowMessage={buttons:St(o.buttons),messageParamsJson:""}),o.footer&&o.footer.length>0&&(c.footer={text:o.footer});let d=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||d)&&(c.header={title:o.title??"",subtitle:o.subtitle??"",hasMediaAttachment:d!==void 0}),d&&t.push({...d,index:a}),c}),s={body:{text:e?.text&&e.text.length>0?e.text:" "},carouselMessage:{cards:r}};return t.length>0?{[R]:{interactiveMessage:s},[vt]:t}:{[R]:{interactiveMessage:s}}};var ss=n=>{let e=[],t="",r=0,s=1,i=0,o=0,a=[];for(let c=0;c<n.length;c++)if(n[c]==="["&&n[c-1]!=="\\")a.push(c);else if(n[c]==="]"&&(n[c+1]==="("||n[c+1]==="<")){let d=a.pop();if(d==null)continue;let u=n[c+1],l=u==="("?")":">",y=u==="<",f=c+2,g=1;for(;f<n.length&&g>0;)n[f]===u&&n[f-1]!=="\\"?g++:n[f]===l&&n[f-1]!=="\\"&&g--,f++;if(g>0)continue;let h=n.slice(d+1,c).trim(),A=n.slice(c+2,f-1).trim(),v,X;if(y){let[Re="",dt="",lt="",ut="",pt=""]=h.split("|").map(mt=>mt.trim());v=`zaileys_LATEX_${o++}`,X=`{{${v}}}${Re||"image"}{{/${v}}}`,e.push({type:"latex",ie:{key:v,text:Re,url:A,width:dt,height:lt,font_height:ut,padding:pt}});}else h?(v=`zaileys_HYPERLINK_${i++}`,X=`{{${v}}}${A}{{/${v}}}`,e.push({type:"hyperlink",ie:{key:v,text:h,url:A}})):(v=`zaileys_CITATION_${s-1}`,X=`{{${v}}}${A}{{/${v}}}`,e.push({type:"citation",ie:{key:v,reference_id:String(s++),url:A}}));t+=n.slice(r,d)+X,r=f,c=f-1;}return t+=n.slice(r),{text:t,ie:e}},is=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"}}),os=n=>{if(!Array.isArray(n)||n.length===0||!n.every(i=>Array.isArray(i)))throw new m("INVALID_OPTIONS","table must be a non-empty array of string rows");let[e,...t]=n,r=Math.max(e.length,...t.map(i=>i.length)),s=i=>[...i,...Array(r-i.length).fill("")];return [{is_header:true,cells:s(e)},...t.map(i=>({is_header:false,cells:s(i)}))]},as={0:"DEFAULT",1:"KEYWORD",2:"METHOD",3:"STR",4:"NUMBER",5:"COMMENT"},We=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"]),cs={javascript:We,js:We,typescript:We,ts:We},ds=(n,e)=>{let t=cs[e.toLowerCase()]??new Set,r=[],s=(o,a)=>{if(!o)return;let c=r[r.length-1];c&&c.highlightType===a?c.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,c=o;for(i++;i<n.length;)if(n[i]==="\\"&&i+1<n.length)i+=2;else if(n[i]===c){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 c=n.slice(a,i),d=0;if(t.has(c))d=1;else {let u=i;for(;u<n.length&&/\s/.test(n[u]);)u++;n[u]==="("&&(d=2);}s(c,d);continue}s(o,0),i++;}return r},k=(n,e)=>({view_model:{[Array.isArray(e)?"primitives":"primitive"]:e,__typename:`GenAI${n}LayoutViewModel`}}),ls="https://github.com/zeative/zaileys",an=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","text({ rich: true }) requires non-empty markdown content");let t=[],r=[];for(let o of n)if(o.type==="text"){let a=ss(o.text),c=is(a);r.push({messageType:2,messageText:a.text}),t.push(k("Single",{text:a.text,...c.length>0?{inline_entities:c}:{},__typename:"GenAIMarkdownTextUXPrimitive"}));}else if(o.type==="code"){let a=o.language??"plaintext",c=ds(o.content,a);r.push({messageType:5,codeMetadata:{codeLanguage:a,codeBlocks:c}}),t.push(k("Single",{language:a,code_blocks:c.map(d=>({content:d.codeContent,type:as[d.highlightType]})),__typename:"GenAICodeUXPrimitive"}));}else if(o.type==="table"){let a=os(o.rows);r.push({messageType:4,tableMetadata:{title:"",rows:a.map(c=>({items:c.cells,...c.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 m("INVALID_OPTIONS","image requires at least one url");r.push({messageType:1,gridImageMetadata:{gridImageUrl:{imagePreviewUrl:a[0]},imageUrls:a.map(c=>({imagePreviewUrl:c,imageHighResUrl:c,sourceUrl:ls}))}});for(let c of a)t.push(k("Single",{media:{url:c,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 m("INVALID_OPTIONS","video requires at least one url");r.push({messageType:2,messageText:"[ CANNOT_LOAD_VIDEO - zaileys ]"});for(let c of a)t.push(k("Single",{media:{url:c,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),c=a?o.products:[o.products];if(c.length===0)throw new m("INVALID_OPTIONS","product requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_PRODUCT - zaileys ]"});let d=c.map(u=>({title:u.title,brand:u.brand??"",price:u.price??"",sale_price:u.salePrice??"",product_url:u.url??"",image:{url:u.image??""},additional_images:[{url:u.icon??""}],__typename:"GenAIProductItemCardPrimitive"}));t.push(a?k("HScroll",d):k("Single",d[0]));}else if(o.type==="reels"){let a=Array.isArray(o.reels)?o.reels:[o.reels];if(a.length===0)throw new m("INVALID_OPTIONS","reels requires at least one item");r.push({messageType:9,contentItemsMetadata:{contentType:1,itemsMetadata:a.map(c=>({reelItem:{title:c.username??"",profileIconUrl:c.profileUrl??"",thumbnailUrl:c.thumbnail??"",videoUrl:c.url??""}}))}}),t.push(k("HScroll",a.map(c=>({reels_url:c.url??"",thumbnail_url:c.thumbnail??"",creator:c.username??c.title??"",avatar_url:c.profileUrl??"",reels_title:c.title??"",likes_count:c.likes??0,shares_count:c.shares??0,view_count:c.views??0,reel_source:c.source??"IG",is_verified:!!c.verified,__typename:"GenAIReelPrimitive"}))));}else if(o.type==="post"){let a=Array.isArray(o.posts)?o.posts:[o.posts];if(a.length===0)throw new m("INVALID_OPTIONS","post requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_POST - zaileys ]"}),t.push(k("HScroll",a.map(c=>({title:c.title??"",subtitle:c.subtitle??"",username:c.username??"",profile_picture_url:c.profileUrl??"",is_verified:!!c.verified,thumbnail_url:c.thumbnail??"",post_caption:c.caption??"",likes_count:c.likes??0,comments_count:c.comments??0,shares_count:c.shares??0,post_url:c.url??"",post_deeplink:c.deeplink??"",source_app:c.source??"INSTAGRAM",footer_label:c.footer??"",footer_icon:c.icon??"",is_carousel:a.length>1,orientation:c.orientation??"LANDSCAPE",post_type:c.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 m("INVALID_OPTIONS","suggest requires at least one prompt");t.push(k("ActionRow",a.map(c=>({prompt_text:c,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,c])=>({source_type:"THIRD_PARTY",source_display_name:c??"",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 {[R]:i}};var us=/^:::([a-zA-Z]+)\s*$/,ps=/^:::\s*$/,cn=/^```(\w*)\s*$/,dn=/^!\[[^\]]*\]\(([^)]+)\)\s*$/,ms=/^\s*\|?\s*:?-{2,}[\s|:-]*$/,Ue=n=>n.split("|").map(e=>e.trim()),At=n=>{let e={};for(let t of Ue(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},G=n=>{if(n===void 0||n.trim().length===0)return;let e=Number(n);return Number.isNaN(e)?void 0:e},un=n=>n==="true"||n==="1"||n==="yes",ln=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())},fs=n=>{let e=At(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},gs=n=>{let e=At(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=G(e.likes);r!==void 0&&(t.likes=r);let s=G(e.shares);s!==void 0&&(t.shares=s);let i=G(e.views);return i!==void 0&&(t.views=i),e.source&&(t.source=e.source),"verified"in e&&(t.verified=un(e.verified)),t},hs=n=>{let e=At(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=G(e.likes);r!==void 0&&(t.likes=r);let s=G(e.comments);s!==void 0&&(t.comments=s);let i=G(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=un(e.verified)),t},ys=(n,e)=>{let t=e.map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(r=>r.length>0);if(n==="suggest"){let r=t.flatMap(s=>Ue(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=>Ue(o)[0]??"").filter(o=>o.length>0);if(r.length===0)return null;let s=G(Ue(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(fs).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(gs);return r.length>0?{type:"reels",reels:r}:null}if(n==="post"){let r=t.map(hs);return r.length>0?{type:"post",posts:r}:null}return null},pn=n=>{let e=n.replace(/\r\n/g,`
1
+ 'use strict';var Yi=require('baileys'),oe=require('node:fs/promises'),url=require('node:url'),os$1=require('node:os'),ve=require('node:path'),child_process=require('node:child_process'),jimp=require('jimp'),ss=require('node-webpmux'),crypto=require('node:crypto'),fs$1=require('node:fs'),Xs=require('qrcode-terminal'),ti=require('pino');require('node:stream');var events=require('node:events');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Yi__default=/*#__PURE__*/_interopDefault(Yi);var oe__default=/*#__PURE__*/_interopDefault(oe);var ve__default=/*#__PURE__*/_interopDefault(ve);var ss__default=/*#__PURE__*/_interopDefault(ss);var Xs__default=/*#__PURE__*/_interopDefault(Xs);var ti__default=/*#__PURE__*/_interopDefault(ti);var Hr=(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 m=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 S={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"}},zt="ffmpeg",Yt="ffprobe",Gt=false,St=async(n=false)=>{if(!(n||Gt)){Gt=true;try{let e=(await import('@ffmpeg-installer/ffmpeg')).default;if(e?.path){zt=e.path;let t=ve__default.default.dirname(e.path),r=process.platform==="win32"?";":":",s=process.env.PATH??"";s.split(r).includes(t)||(process.env.PATH=`${t}${r}${s}`);}}catch{}try{let e=(await import('@ffprobe-installer/ffprobe')).default;e?.path&&(Yt=e.path);}catch{}}},_e=()=>Date.now().toString(36)+Math.random().toString(36).slice(2,8),P=async n=>{let{fileTypeFromBuffer:e}=await import('file-type');return e(n)},j=class{static generateUniqueId(){return `${Date.now()}_${Math.random().toString(36).slice(2,11)}`}static createTempPath(e,t){return ve__default.default.join(os$1.tmpdir(),`${e}_${this.generateUniqueId()}.${t}`)}static async cleanup(e){await Promise.allSettled(e.map(t=>oe__default.default.unlink(t)));}static async safeReadFile(e){try{return await oe__default.default.readFile(e)}catch{throw new Error(`Failed to read file: ${e}`)}}static async safeWriteFile(e,t){try{await oe__default.default.writeFile(e,t);}catch{throw new Error(`Failed to write file: ${e}`)}}},v=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 oe__default.default.stat(e).then(t=>t.isFile()).catch(()=>!1))return await oe__default.default.readFile(e)}catch{}return Buffer.from(e,"base64")}static async fromUrl(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let r=await t.arrayBuffer();return Buffer.from(r)}catch(t){throw new Error(`Failed to fetch URL: ${t instanceof Error?t.message:String(t)}`)}}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"}},b=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(S.MIME.IMAGE)||e.startsWith(S.MIME.VIDEO)}static isAnimated(e){return e===S.MIME.GIF||e.startsWith(S.MIME.VIDEO)}},V=class{static async process(e){return await St(),new Promise((t,r)=>{let s=["-y","-i",e.input,...e.options,e.output],i=child_process.spawn(zt,s,{stdio:"ignore"});i.on("close",async o=>{if(o===0)try{await e.onEnd(),t();}catch(a){r(a);}else try{let a=new Error(`FFmpeg exited with code ${o}`);await e.onError(a),r(a);}catch(a){r(a);}}),i.on("error",async o=>{try{await e.onError(o);}finally{r(o);}});})}static async getDuration(e){return new Promise((t,r)=>{let s=child_process.spawn(Yt,["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),i="";s.stdout.on("data",o=>i+=o.toString()),s.on("close",o=>{o===0?t(parseFloat(i.trim())||0):r(new Error(`ffprobe exited with code ${o}`));}),s.on("error",r);})}};var Xr=3e4,Zt="application/octet-stream",Qr=async n=>n.byteLength===0?Zt:(await P(n))?.mime??Zt,ae=async n=>({buffer:n,mime:await Qr(n),size:n.byteLength}),Xt=async(n,e)=>{let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{let s=await fetch(n,{signal:t.signal});if(!s.ok)throw new m("MEDIA_LOAD_FAILED",`fetch ${n} failed with status ${s.status}`,{cause:s.status});return Buffer.from(await s.arrayBuffer())}catch(s){throw s instanceof m?s:new m("MEDIA_LOAD_FAILED",`fetch ${n} failed: ${s.message}`,{cause:s})}finally{clearTimeout(r);}},Qt=async n=>{try{return await oe.readFile(n)}catch(e){throw new m("MEDIA_LOAD_FAILED",`read ${n} failed: ${e.message}`,{cause:e})}},es=n=>n.startsWith("http://")||n.startsWith("https://"),k=async(n,e)=>{await St();let t=Xr;return Buffer.isBuffer(n)?ae(n):n instanceof URL?n.protocol==="file:"?ae(await Qt(url.fileURLToPath(n))):ae(await Xt(n.toString(),t)):es(n)?ae(await Xt(n,t)):ae(await Qt(n))};var te=async(n,e)=>{let{buffer:t}=await k(n),r={image:t};return e?.caption!==void 0&&(r.caption=e.caption),e?.viewOnce!==void 0&&(r.viewOnce=e.viewOnce),r};var ne=async(n,e)=>{let{buffer:t,mime:r}=await k(n);if(!r.startsWith("video/"))throw new m("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),s};var en=2,tn=30,ts=async n=>{if(n.type==="image")return te(n.src,n.caption!==void 0?{caption:n.caption}:void 0);if(n.type==="video")return ne(n.src,n.caption!==void 0?{caption:n.caption}:void 0);throw new m("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(n.type)}`)},nn=async(n,e,t,r)=>{if(!Array.isArray(t)||t.length<en)throw new m("INVALID_OPTIONS",`album() requires a minimum of ${en} items`);if(t.length>tn)throw new m("INVALID_OPTIONS",`album() accepts a maximum of ${tn} items`);let s=0,i=0;for(let l of t)if(l.type==="image")s+=1;else if(l.type==="video")i+=1;else throw new m("INVALID_OPTIONS",`album() item type must be 'image' or 'video', got ${String(l.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 c;try{c=await n.sendMessage(e,o,a);}catch(l){throw new m("SEND_FAILED","album parent send rejected",{cause:l})}let d=c?.key;if(!d)throw new m("SEND_FAILED","album parent returned no message key");let u=0;for(let l of t){let y=await ts(l);y.albumParentKey=d;try{await n.sendMessage(e,y);}catch(f){throw new m("SEND_FAILED","album child send rejected",{cause:{parentKey:d,index:u,error:f}})}u+=1;}return d};var _=async(n,e,t,r,s)=>{let i=r.replace(/[^a-z0-9]+/gi,"_").toLowerCase(),o=j.createTempPath(`${i}_in`,e),a=j.createTempPath(`${i}_out`,t);await j.safeWriteFile(o,n);try{let c=typeof s=="function"?await s(o):s;return await V.process({input:o,output:a,options:c,onEnd:async()=>{},onError:async()=>{}}),await j.safeReadFile(a)}catch(c){throw new Error(`${r} failed: ${c instanceof Error?c.message:String(c)}`)}finally{await j.cleanup([o,a]);}};var De=64,rn=8e3,G=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 v.toBuffer(e);b.validate(await P(r),S.MIME.AUDIO);let s=await v.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 _(r,s,t==="opus"?"ogg":"mp3",`${t.toUpperCase()} conversion`,i)}static async waveform(e){let t=await v.toBuffer(e),r=await v.getExtension(t),s=await _(t,r,"tmp","Waveform generation",["-vn","-ac","1","-ar",String(rn),"-f","s16le"]),i=Math.floor(s.length/2);return {waveform:this.computeWaveform(s),seconds:Math.max(1,Math.round(i/rn))}}static computeWaveform(e){let t=Math.floor(e.length/2),r=new Uint8Array(De);if(t===0)return r;let s=Math.max(1,Math.floor(t/De)),i=[];for(let a=0;a<De;a++){let c=0,d=0;for(let u=0;u<s;u++){let l=(a*s+u)*2;l+1<e.length&&(c+=Math.abs(e.readInt16LE(l)),d+=1);}i.push(d>0?c/d:0);}let o=Math.max(...i)||1;for(let a=0;a<De;a++)r[a]=Math.floor(i[a]/o*100);return r}};var ns=["-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"],D=class{static async toMp4(e){let t=await v.toBuffer(e);b.validate(await P(t),S.MIME.VIDEO);let r=await v.getExtension(t);return _(t,r,"mp4","Video re-encoding",ns)}static async thumbnail(e){let t=await v.toBuffer(e);b.validate(await P(t),S.MIME.VIDEO);let r=await v.getExtension(t),s=S.THUMBNAIL.SIZE;return (await _(t,r,"jpg","Thumbnail generation",async o=>{let a=await V.getDuration(o);return ["-ss",Math.max(0,a*.1).toString(),"-vframes","1","-s",`${s}x${s}`]})).toString("base64")}static async duration(e){return V.getDuration(e)}};var re=null,sn=false;async function rs(){if(sn)return re;sn=true;let n=e=>{typeof e=="function"&&(re=e);};try{n(Hr("sharp"));}catch{re=null;}if(!re)try{let e=await import('sharp');n(e.default??e);}catch{re=null;}return re}function on(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 c=0;c<n;c++){let d=false;if(e==="circle"){let u=c-r,l=a-s;d=u*u+l*l<=r*r;}else if(e==="rounded"){let u=c>=i&&c<n-i&&a>=0&&a<n,l=c>=0&&c<n&&a>=i&&a<n-i,y=false;for(let f of o){let g=c-f[0],h=a-f[1];if(g*g+h*h<=i*i){y=true;break}}d=u||l||y;}else if(e==="oval"){let u=(c-r)/(n/2),l=(a-s)/(n/3);d=u*u+l*l<=1;}t[a*n+c]=d?255:0;}return t}var vt=class{sharp;constructor(e){this.sharp=e;}async thumbnail(e){let t=this.sharp,r=t(e).resize(S.THUMBNAIL.SIZE,S.THUMBNAIL.SIZE,{fit:"cover"});return (await r.metadata()).format==="gif"&&(r=t(e,{pages:1}).resize(S.THUMBNAIL.SIZE,S.THUMBNAIL.SIZE)),(await r.jpeg({quality:S.THUMBNAIL.QUALITY}).toBuffer()).toString("base64")}async resize(e,t,r){return this.sharp(e).resize(t,r,{fit:"cover"}).png().toBuffer()}async toJpeg(e){let t=this.sharp,r=await v.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=S.STICKER.SIZE,o=s(e).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}});if(r!=="default"){let a=Buffer.from(on(i,r)),c=s(a,{raw:{width:i,height:i,channels:1}});o=o.joinChannel(await c.png().toBuffer());}return o.webp({quality:t}).toBuffer()}},At=class{async thumbnail(e){let t=S.THUMBNAIL.SIZE,r=await jimp.Jimp.fromBuffer(e);r.cover({w:t,h:t});let s=await r.getBuffer("image/jpeg",{quality:S.THUMBNAIL.QUALITY});return Buffer.from(s).toString("base64")}async resize(e,t,r){let s=await jimp.Jimp.fromBuffer(e);s.cover({w:t,h:r});let i=await s.getBuffer("image/png");return Buffer.from(i)}async toJpeg(e){let t=await v.toBuffer(e);try{let s=await(await jimp.Jimp.fromBuffer(t)).getBuffer("image/jpeg");return Buffer.from(s)}catch{return t}}async resizeForSticker(e,t,r="default"){let s=S.STICKER.SIZE,i=await jimp.Jimp.fromBuffer(e);if(i.contain({w:s,h:s}),r!=="default"){let c=on(s,r),d=new jimp.Jimp({width:s,height:s,color:255});for(let u=0;u<s;u++)for(let l=0;l<s;l++)c[u*s+l]===255&&d.setPixelColor(4294967295,l,u);i.mask(d);}let o=Buffer.from(await i.getBuffer("image/png")),a=Math.max(1,Math.min(100,t));return _(o,"png","webp","Jimp WebP conversion",["-vcodec","libwebp","-q:v",`${a}`,"-preset","default"])}},de=null;async function Be(){if(de)return de;let n=await rs();return n?de=new vt(n):(console.warn("\x1B[33m%s\x1B[0m","[media-process] Jimp is slow. For faster performance, run: npm install sharp"),de=new At),de}var x=class{static async thumbnail(e){return (await Be()).thumbnail(e)}static async resize(e,t,r){return (await Be()).resize(e,t,r)}static async toJpeg(e){return (await Be()).toJpeg(e)}static async resizeForSticker(e,t,r="default"){return (await Be()).resizeForSticker(e,t,r)}};var Fe=class{static async create(e,t){try{let r=await v.toBuffer(e),s=await P(r);if(!s)throw new Error("Unable to detect file type");let i=t?.quality||S.STICKER.DEFAULT_QUALITY,o=b.isAnimated(s.mime),a=t?.shape||"default",c=s.mime==="image/webp"?r:o?await this.processAnimated(r,s.mime,i):await x.resizeForSticker(r,i,a),d=this.createExifMetadata(t),u=new ss__default.default.Image;await u.load(c),u.exif=d;let l=await u.save(null);return Buffer.isBuffer(l)?l:Buffer.from(l)}catch(r){throw new Error(`Sticker creation failed: ${r instanceof Error?r.message:String(r)}`)}}static createExifMetadata(e){let t={"sticker-pack-id":_e(),"sticker-pack-name":e?.packageName||"Zaileys Library","sticker-pack-publisher":e?.authorName||"https://github.com/zeative/zaileys",emojis:["\u{1F913}"],"android-app-store-link":"https://play.google.com/store/apps/details?id=com.marsvard.stickermakerforwhatsapp","ios-app-store-link":"https://itunes.apple.com/app/sticker-maker-studio/id1443326857"},r=Buffer.from([73,73,42,0,8,0,0,0,1,0,65,87,7,0,0,0,0,0,22,0,0,0]),s=Buffer.from(JSON.stringify(t),"utf8"),i=Buffer.concat([r,s]);return i.writeUIntLE(s.length,14,4),i}static async processAnimated(e,t,r){let s=S.STICKER.SIZE,i=S.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 _(e,this.getExtension(t),"webp","Animated sticker processing",async c=>{let d=S.STICKER.MAX_DURATION;try{d=Math.min(await D.duration(c),S.STICKER.MAX_DURATION);}catch{console.warn("Using default duration:",S.STICKER.MAX_DURATION);}return ["-vcodec libwebp",`-vf ${o}`,`-q:v ${a}`,"-loop 0","-preset default","-an","-vsync 0",`-t ${d}`,`-compression_level ${S.STICKER.COMPRESSION_LEVEL}`]})}static getExtension(e){return e===S.MIME.GIF?"gif":e.startsWith(S.MIME.VIDEO)?"mp4":"tmp"}};var We=class{static async create(e){try{let t=await v.toBuffer(e),r=await P(t);if(!r)throw new Error("Unable to detect file type");let s;return r.mime.startsWith(S.MIME.VIDEO)?s=await D.thumbnail(t):b.isMedia(r.mime)?s=await x.thumbnail(t):s="",{document:t,mimetype:r.mime,ext:r.ext,fileName:_e(),jpegThumbnail:s}}catch(t){throw new Error(`Document creation failed: ${t instanceof Error?t.message:String(t)}`)}}};var H=class{input;constructor(e){this.input=e;}get audio(){return {toOpus:()=>G.toOpus(this.input),toMp3:()=>G.toMp3(this.input),convert:(e="opus")=>G.convert(this.input,e),waveform:()=>G.waveform(this.input)}}get video(){return {toMp4:()=>D.toMp4(this.input),thumbnail:()=>D.thumbnail(this.input)}}get image(){return {toJpeg:()=>x.toJpeg(this.input),thumbnail:async()=>{let e=await v.toBuffer(this.input);return x.thumbnail(e)},resize:async(e,t)=>{let r=await v.toBuffer(this.input);return x.resize(r,e,t)}}}get sticker(){return {create:e=>Fe.create(this.input,e)}}get document(){return {create:()=>We.create(this.input)}}get thumbnail(){return {get:async()=>{let e=await v.toBuffer(this.input),t=await P(e);if(!t||!b.isMedia(t.mime))throw new Error("Invalid media type: expected image or video");return t.mime.startsWith(S.MIME.VIDEO)?D.thumbnail(this.input):x.thumbnail(e)}}}async toBuffer(){return v.toBuffer(this.input)}};var an=async(n,e)=>{let{buffer:t}=await k(n),r;try{r=await new H(t).audio.toOpus();}catch(o){throw new m("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 H(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 cn=10,L="__zaileysRelayMessage",Mt="__zaileysHeaderMedia",K=n=>typeof n=="string"&&n.length>0,is=n=>{let e=n.text;if(!K(e)||e.trim().length===0)throw new m("INVALID_OPTIONS","button text must be a non-empty string");return e},os=(n,e)=>{let t=n.type??"reply";if(t==="location"){let s=n.text;return {name:"send_location",buttonParamsJson:JSON.stringify(K(s)?{display_text:s}:{})}}let r=is(n);if(t==="reply"){let s=n.id;if(!K(s))throw new m("INVALID_OPTIONS","reply button requires a non-empty id");if(e.has(s))throw new m("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(!K(s))throw new m("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,webview_interaction:i})}}if(t==="copy"){let s=n.code;if(!K(s))throw new m("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(!K(s))throw new m("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:K(s)?s:r})}}if(t==="address"){let s=n.id;return {name:"address_message",buttonParamsJson:JSON.stringify({display_text:r,id:K(s)?s:r})}}throw new m("INVALID_OPTIONS",`unknown button type: ${String(t)}`)},as=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):""},Et=n=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","buttons() requires at least one button");if(n.length>cn)throw new m("INVALID_OPTIONS",`buttons() accepts at most ${cn} buttons`);let e=new Set;return n.map(t=>os(t,e))},Ue=(n,e)=>{let t=Et(n),r={body:{text:e?.text&&e.text.length>0?e.text:" "},nativeFlowMessage:{buttons:t,messageParamsJson:as(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?{[L]:{interactiveMessage:r},[Mt]:s}:{[L]:{interactiveMessage:r}}};var dn=10,Ct="__zaileysCardsMedia",ln=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","carousel() requires at least one card");if(n.length>dn)throw new m("INVALID_OPTIONS",`carousel() accepts at most ${dn} cards`);let t=[],r=n.map((o,a)=>{let c={body:{text:o.body&&o.body.length>0?o.body:" "}};o.buttons&&o.buttons.length>0&&(c.nativeFlowMessage={buttons:Et(o.buttons),messageParamsJson:""}),o.footer&&o.footer.length>0&&(c.footer={text:o.footer});let d=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||d)&&(c.header={title:o.title??"",subtitle:o.subtitle??"",hasMediaAttachment:d!==void 0}),d&&t.push({...d,index:a}),c}),s={body:{text:e?.text&&e.text.length>0?e.text:" "},carouselMessage:{cards:r}};return t.length>0?{[L]:{interactiveMessage:s},[Ct]:t}:{[L]:{interactiveMessage:s}}};var ds=n=>{let e=[],t="",r=0,s=1,i=0,o=0,a=[];for(let c=0;c<n.length;c++)if(n[c]==="["&&n[c-1]!=="\\")a.push(c);else if(n[c]==="]"&&(n[c+1]==="("||n[c+1]==="<")){let d=a.pop();if(d==null)continue;let u=n[c+1],l=u==="("?")":">",y=u==="<",f=c+2,g=1;for(;f<n.length&&g>0;)n[f]===u&&n[f-1]!=="\\"?g++:n[f]===l&&n[f-1]!=="\\"&&g--,f++;if(g>0)continue;let h=n.slice(d+1,c).trim(),M=n.slice(c+2,f-1).trim(),A,ee;if(y){let[Ne="",mt="",ft="",gt="",ht=""]=h.split("|").map(yt=>yt.trim());A=`zaileys_LATEX_${o++}`,ee=`{{${A}}}${Ne||"image"}{{/${A}}}`,e.push({type:"latex",ie:{key:A,text:Ne,url:M,width:mt,height:ft,font_height:gt,padding:ht}});}else h?(A=`zaileys_HYPERLINK_${i++}`,ee=`{{${A}}}${M}{{/${A}}}`,e.push({type:"hyperlink",ie:{key:A,text:h,url:M}})):(A=`zaileys_CITATION_${s-1}`,ee=`{{${A}}}${M}{{/${A}}}`,e.push({type:"citation",ie:{key:A,reference_id:String(s++),url:M}}));t+=n.slice(r,d)+ee,r=f,c=f-1;}return t+=n.slice(r),{text:t,ie:e}},ls=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"}}),us=n=>{if(!Array.isArray(n)||n.length===0||!n.every(i=>Array.isArray(i)))throw new m("INVALID_OPTIONS","table must be a non-empty array of string rows");let[e,...t]=n,r=Math.max(e.length,...t.map(i=>i.length)),s=i=>[...i,...Array(r-i.length).fill("")];return [{is_header:true,cells:s(e)},...t.map(i=>({is_header:false,cells:s(i)}))]},ps={0:"DEFAULT",1:"KEYWORD",2:"METHOD",3:"STR",4:"NUMBER",5:"COMMENT"},je=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"]),ms={javascript:je,js:je,typescript:je,ts:je},fs=(n,e)=>{let t=ms[e.toLowerCase()]??new Set,r=[],s=(o,a)=>{if(!o)return;let c=r[r.length-1];c&&c.highlightType===a?c.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,c=o;for(i++;i<n.length;)if(n[i]==="\\"&&i+1<n.length)i+=2;else if(n[i]===c){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 c=n.slice(a,i),d=0;if(t.has(c))d=1;else {let u=i;for(;u<n.length&&/\s/.test(n[u]);)u++;n[u]==="("&&(d=2);}s(c,d);continue}s(o,0),i++;}return r},I=(n,e)=>({view_model:{[Array.isArray(e)?"primitives":"primitive"]:e,__typename:`GenAI${n}LayoutViewModel`}}),gs="https://github.com/zeative/zaileys",un=(n,e)=>{if(!Array.isArray(n)||n.length===0)throw new m("INVALID_OPTIONS","text({ rich: true }) requires non-empty markdown content");let t=[],r=[];for(let o of n)if(o.type==="text"){let a=ds(o.text),c=ls(a);r.push({messageType:2,messageText:a.text}),t.push(I("Single",{text:a.text,...c.length>0?{inline_entities:c}:{},__typename:"GenAIMarkdownTextUXPrimitive"}));}else if(o.type==="code"){let a=o.language??"plaintext",c=fs(o.content,a);r.push({messageType:5,codeMetadata:{codeLanguage:a,codeBlocks:c}}),t.push(I("Single",{language:a,code_blocks:c.map(d=>({content:d.codeContent,type:ps[d.highlightType]})),__typename:"GenAICodeUXPrimitive"}));}else if(o.type==="table"){let a=us(o.rows);r.push({messageType:4,tableMetadata:{title:"",rows:a.map(c=>({items:c.cells,...c.is_header?{isHeading:true}:{}}))}}),t.push(I("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 m("INVALID_OPTIONS","image requires at least one url");r.push({messageType:1,gridImageMetadata:{gridImageUrl:{imagePreviewUrl:a[0]},imageUrls:a.map(c=>({imagePreviewUrl:c,imageHighResUrl:c,sourceUrl:gs}))}});for(let c of a)t.push(I("Single",{media:{url:c,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 m("INVALID_OPTIONS","video requires at least one url");r.push({messageType:2,messageText:"[ CANNOT_LOAD_VIDEO - zaileys ]"});for(let c of a)t.push(I("Single",{media:{url:c,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),c=a?o.products:[o.products];if(c.length===0)throw new m("INVALID_OPTIONS","product requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_PRODUCT - zaileys ]"});let d=c.map(u=>({title:u.title,brand:u.brand??"",price:u.price??"",sale_price:u.salePrice??"",product_url:u.url??"",image:{url:u.image??""},additional_images:[{url:u.icon??""}],__typename:"GenAIProductItemCardPrimitive"}));t.push(a?I("HScroll",d):I("Single",d[0]));}else if(o.type==="reels"){let a=Array.isArray(o.reels)?o.reels:[o.reels];if(a.length===0)throw new m("INVALID_OPTIONS","reels requires at least one item");r.push({messageType:9,contentItemsMetadata:{contentType:1,itemsMetadata:a.map(c=>({reelItem:{title:c.username??"",profileIconUrl:c.profileUrl??"",thumbnailUrl:c.thumbnail??"",videoUrl:c.url??""}}))}}),t.push(I("HScroll",a.map(c=>({reels_url:c.url??"",thumbnail_url:c.thumbnail??"",creator:c.username??c.title??"",avatar_url:c.profileUrl??"",reels_title:c.title??"",likes_count:c.likes??0,shares_count:c.shares??0,view_count:c.views??0,reel_source:c.source??"IG",is_verified:!!c.verified,__typename:"GenAIReelPrimitive"}))));}else if(o.type==="post"){let a=Array.isArray(o.posts)?o.posts:[o.posts];if(a.length===0)throw new m("INVALID_OPTIONS","post requires at least one item");r.push({messageType:2,messageText:"[ CANNOT_LOAD_POST - zaileys ]"}),t.push(I("HScroll",a.map(c=>({title:c.title??"",subtitle:c.subtitle??"",username:c.username??"",profile_picture_url:c.profileUrl??"",is_verified:!!c.verified,thumbnail_url:c.thumbnail??"",post_caption:c.caption??"",likes_count:c.likes??0,comments_count:c.comments??0,shares_count:c.shares??0,post_url:c.url??"",post_deeplink:c.deeplink??"",source_app:c.source??"INSTAGRAM",footer_label:c.footer??"",footer_icon:c.icon??"",is_carousel:a.length>1,orientation:c.orientation??"LANDSCAPE",post_type:c.postType??"VIDEO",__typename:"GenAIPostPrimitive"}))));}else if(o.type==="tip")r.push({messageType:2,messageText:o.text}),t.push(I("Single",{text:o.text,__typename:"GenAIMetadataTextPrimitive"}));else {let a=Array.isArray(o.prompts)?o.prompts:[o.prompts];if(a.length===0)throw new m("INVALID_OPTIONS","suggest requires at least one prompt");t.push(I("ActionRow",a.map(c=>({prompt_text:c,prompt_type:"SUGGESTED_PROMPT",__typename:"GenAIFollowUpSuggestionPillPrimitive"}))));}e?.footer&&e.footer.length>0&&t.push(I("Single",{text:e.footer,__typename:"GenAIMetadataTextPrimitive"}));let s=(e?.sources??[]).map(([o,a,c])=>({source_type:"THIRD_PARTY",source_display_name:c??"",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 {[L]:i}};var hs=/^:::([a-zA-Z]+)\s*$/,ys=/^:::\s*$/,pn=/^```(\w*)\s*$/,mn=/^!\[[^\]]*\]\(([^)]+)\)\s*$/,ws=/^\s*\|?\s*:?-{2,}[\s|:-]*$/,Ke=n=>n.split("|").map(e=>e.trim()),bt=n=>{let e={};for(let t of Ke(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},z=n=>{if(n===void 0||n.trim().length===0)return;let e=Number(n);return Number.isNaN(e)?void 0:e},gn=n=>n==="true"||n==="1"||n==="yes",fn=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())},Ss=n=>{let e=bt(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},vs=n=>{let e=bt(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=z(e.likes);r!==void 0&&(t.likes=r);let s=z(e.shares);s!==void 0&&(t.shares=s);let i=z(e.views);return i!==void 0&&(t.views=i),e.source&&(t.source=e.source),"verified"in e&&(t.verified=gn(e.verified)),t},As=n=>{let e=bt(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=z(e.likes);r!==void 0&&(t.likes=r);let s=z(e.comments);s!==void 0&&(t.comments=s);let i=z(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=gn(e.verified)),t},Ms=(n,e)=>{let t=e.map(r=>r.replace(/^[-*]\s*/,"").trim()).filter(r=>r.length>0);if(n==="suggest"){let r=t.flatMap(s=>Ke(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=>Ke(o)[0]??"").filter(o=>o.length>0);if(r.length===0)return null;let s=z(Ke(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(Ss).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(vs);return r.length>0?{type:"reels",reels:r}:null}if(n==="post"){let r=t.map(As);return r.length>0?{type:"post",posts:r}:null}return null},hn=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=us.exec(o);if(a){s();let l=[];for(i++;i<e.length&&!ps.test(e[i]);)l.push(e[i]),i++;i++;let y=ys(a[1].toLowerCase(),l);y&&t.push(y);continue}let c=cn.exec(o);if(c){s();let l=[];for(i++;i<e.length&&!cn.test(e[i]);)l.push(e[i]),i++;i++;let y=c[1]&&c[1].length>0?c[1]:void 0;t.push(y?{type:"code",language:y,content:l.join(`
6
+ `).trim();o.length>0&&t.push({type:"text",text:o}),r=[];},i=0;for(;i<e.length;){let o=e[i],a=hs.exec(o);if(a){s();let l=[];for(i++;i<e.length&&!ys.test(e[i]);)l.push(e[i]),i++;i++;let y=Ms(a[1].toLowerCase(),l);y&&t.push(y);continue}let c=pn.exec(o);if(c){s();let l=[];for(i++;i<e.length&&!pn.test(e[i]);)l.push(e[i]),i++;i++;let y=c[1]&&c[1].length>0?c[1]:void 0;t.push(y?{type:"code",language:y,content:l.join(`
7
7
  `)}:{type:"code",content:l.join(`
8
- `)});continue}let d=e[i+1];if(o.includes("|")&&d!==void 0&&d.includes("|")&&ms.test(d)){s();let l=[ln(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)l.push(ln(e[i])),i++;t.push({type:"table",rows:l});continue}let u=dn.exec(o);if(u){s();let l=[u[1]];for(i++;i<e.length;){let y=dn.exec(e[i]);if(!y)break;l.push(y[1]),i++;}t.push({type:"image",url:l.length===1?l[0]:l});continue}r.push(o),i++;}return s(),t};var mn=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new m("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var fn=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new m("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await T(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var gn=10,hn=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new m("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new m("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 m("INVALID_OPTIONS","each list section requires at least one row");let c=a.rows.map(d=>{if(typeof d.id!="string"||d.id.length===0)throw new m("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof d.title!="string"||d.title.trim().length===0)throw new m("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(d.id))throw new m("INVALID_OPTIONS",`duplicate list row id: ${d.id}`);return t.add(d.id),e+=1,{header:"",title:d.title,description:d.description??"",id:d.id}});return {title:a.title,highlight_label:"",rows:c}});if(e>gn)throw new m("INVALID_OPTIONS",`list() accepts at most ${gn} 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}),{[R]:{interactiveMessage:i}}};var yn=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new m("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 m("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 wn=2,Sn=12,vn=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new m("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<wn)throw new m("INVALID_OPTIONS",`poll() requires a minimum of ${wn} options`);if(e.length>Sn)throw new m("INVALID_OPTIONS",`poll() accepts a maximum of ${Sn} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new m("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new m("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var An=async(n,e)=>{let{buffer:t}=await T(n),r;try{r=await new V(t).sticker.create();}catch(i){throw new m("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var Mn=3,En=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new m("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new m("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>Mn)throw new m("INVALID_OPTIONS",`template() accepts at most ${Mn} buttons`);let t={text:`${n.header&&n.header.length>0?`*${n.header}*
8
+ `)});continue}let d=e[i+1];if(o.includes("|")&&d!==void 0&&d.includes("|")&&ws.test(d)){s();let l=[fn(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)l.push(fn(e[i])),i++;t.push({type:"table",rows:l});continue}let u=mn.exec(o);if(u){s();let l=[u[1]];for(i++;i<e.length;){let y=mn.exec(e[i]);if(!y)break;l.push(y[1]),i++;}t.push({type:"image",url:l.length===1?l[0]:l});continue}r.push(o),i++;}return s(),t};var yn=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new m("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var wn=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new m("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await k(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var Sn=10,vn=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new m("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new m("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 m("INVALID_OPTIONS","each list section requires at least one row");let c=a.rows.map(d=>{if(typeof d.id!="string"||d.id.length===0)throw new m("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof d.title!="string"||d.title.trim().length===0)throw new m("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(d.id))throw new m("INVALID_OPTIONS",`duplicate list row id: ${d.id}`);return t.add(d.id),e+=1,{header:"",title:d.title,description:d.description??"",id:d.id}});return {title:a.title,highlight_label:"",rows:c}});if(e>Sn)throw new m("INVALID_OPTIONS",`list() accepts at most ${Sn} 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}),{[L]:{interactiveMessage:i}}};var An=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new m("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 m("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 Mn=2,En=12,Cn=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new m("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Mn)throw new m("INVALID_OPTIONS",`poll() requires a minimum of ${Mn} options`);if(e.length>En)throw new m("INVALID_OPTIONS",`poll() accepts a maximum of ${En} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new m("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new m("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var bn=async(n,e)=>{let{buffer:t}=await k(n),r;try{r=await new H(t).sticker.create();}catch(i){throw new m("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var Pn=3,Tn=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new m("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new m("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>Pn)throw new m("INVALID_OPTIONS",`template() accepts at most ${Pn} 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),Fe(n.buttons,t)};var je=n=>{if(typeof n!="string"||n.trim().length===0)throw new m("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Cn=(n,e)=>({recipient:n,...e?{resolveRecipient:e}:{}});var vs=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],j=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r){return new n(e,Cn(t,r))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=an(pn(e),t):this.internal.content=je(e),this}image(e,t){return this.internal.pendingContent=Q(e,t),this}video(e,t){return this.internal.pendingContent=ee(e,t),this}audio(e,t){return this.internal.pendingContent=nn(e,t),this}document(e,t){return this.internal.pendingContent=fn(e,t),this}sticker(e,t){return this.internal.pendingContent=An(e,t),this}buttons(e,t){return this.internal.content=Fe(e,t),this}carousel(e,t){return this.internal.content=on(e,t),this}list(e){return this.internal.content=hn(e),this}poll(e,t,r){return this.internal.content=vn(e,t,r),this}location(e,t,r){return this.internal.content=yn(e,t,r),this}contact(e){return this.internal.content=mn(e),this}template(e){return this.internal.content=En(e),this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new m("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 m("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new m("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}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new m("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.albumItems){let d={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(d.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(d.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(d.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(d.disappearingSeconds=this.internal.disappearingSeconds),Xt(this.socket,this.internal.recipient,this.internal.albumItems,d)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new m("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[R];if(i!==void 0){let d=s[wt],u=s[vt];return this.sendRelay(i,d,u)}let o=this.internal.content;this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds);let c;try{c=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(d){throw new m("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new m("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await T(t.src),s=await Di.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 sendRelay(e,t,r){let s=this.socket.relayMessage;if(typeof s!="function")throw new m("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let l=e.interactiveMessage?.header;t!==void 0&&l&&await this.uploadHeaderMedia(l,t);let y=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&y)for(let f of r){let g=y[f.index]?.header;g&&await this.uploadHeaderMedia(g,f);}}catch(l){throw new m("SEND_FAILED","interactive media upload failed",{cause:l})}let o={userJid:this.socket.user?.id??""},a=this.internal.quoted;a!==void 0&&a.message!=null&&(o.quoted=a);let c=Di.generateWAMessageFromContent(this.internal.recipient,e,o);if(typeof c.key?.id!="string")throw new m("SEND_FAILED","failed to generate relay message key");let u="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:c.key.id,additionalNodes:vs}:{messageId:c.key.id};try{await s(this.internal.recipient,c.message,u);}catch(l){throw new m("SEND_FAILED","socket relayMessage rejected",{cause:l})}return c.key}};var ce=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=je(e),this}image(e,t){return this.pendingContent=Q(e,t),this}video(e,t){return this.pendingContent=ee(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 m("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new m("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 m("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new m("SEND_FAILED","socket returned no message key");return r.key}};var Pn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new m("INVALID_OPTIONS","message key is missing remoteJid");return e},bn=n=>{if(!n?.key)throw new m("SEND_FAILED","socket returned no message key");return n.key},Mt=async(n,e,t={})=>{let r=Pn(e),i=t.forEveryone??true?e:{...e,fromMe:true};await n.sendMessage(r,{delete:i});},Et=async(n,e,t)=>{let r=Pn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return bn(s)},Ct=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new m("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return bn(i)};var As=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Ke=n=>As.test(n),Pt=async(n,e,t,r=Ms)=>{if(Ke(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 c=(await n.onWhatsApp(e))?.find(d=>d.exists&&d.jid);if(!c)throw new m("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,c.jid),c.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Ms=new Map;var E=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 de=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new E("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}async create(e,t){return this.requireSocket().groupCreate(e,t)}async addMember(e,t){let r=await this.requireSocket().groupParticipantsUpdate(e,t,"add");return this.mapParticipants(r)}async removeMember(e,t){let r=await this.requireSocket().groupParticipantsUpdate(e,t,"remove");return this.mapParticipants(r)}async promote(e,t){let r=await this.requireSocket().groupParticipantsUpdate(e,t,"promote");return this.mapParticipants(r)}async demote(e,t){let r=await 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 E("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new E("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.requireSocket().groupAcceptInvite(e);if(!t)throw new E("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);}};var le=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new E("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);}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);}};var ue=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new E("NOT_CONNECTED","client not connected");return e}async create(e,t){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.requireSocket().newsletterFollow(e);}async unfollow(e){await this.requireSocket().newsletterUnfollow(e);}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new E("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);}};var pe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new E("NOT_CONNECTED","client not connected");return e}async create(e,t){return this.requireSocket().communityCreate(e,t)}async createGroup(e,t,r){return 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.requireSocket().communityAcceptInvite(e)}};var M=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 Es=n=>{let e=n[0];return e==="{"||e==="["},Cs=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Ps=n=>n===" "||n===" "||n===`
11
- `||n==="\r",bs=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let c=n[a];if(s){t+=c,s=false,i=true,o=false;continue}if(c==="\\"&&r!==null){s=true;continue}if(r!==null){c===r?r=null:t+=c,o=false;continue}if((c==='"'||c==="'")&&o){r=c,i=true,o=false;continue}if(Ps(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Ts=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},ks=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function bt(n,e){let t=Ts(n,e);if(t===null)return ks(n);let r=n.slice(t.length),s=bs(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 c=s[a];if(c!==void 0){if(c.startsWith("--")){let d=c.slice(2);if(d.length===0){i.args.push(c);continue}let u=d.indexOf("=");if(u!==-1){let y=d.slice(0,u),f=d.slice(u+1);i.flags[y]=f;continue}let l=s[a+1];l!==void 0&&!l.startsWith("--")?(i.flags[d]=l,a+=1):i.flags[d]=true;continue}if(!o&&Es(c)){let d=Cs(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var Is=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new M("INVALID_COMMAND_NAME","empty command segment in spec");return e},qe=n=>n.join(" "),me=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new M("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>Is(a)),s=r[0],i=r.slice(1).map(a=>qe(a)),o={name:qe(s),aliases:i,parts:s,handler:t};for(let a of r){let c=qe(a);if(this.paths.has(c))throw new M("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(qe(a),o),a.length>this.maxDepth&&(this.maxDepth=a.length);this.defs.push(o);}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)}}}list(){return [...this.defs]}};async function Tt(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new M("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(c){throw s.error=c,s.thrown=true,c}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(c){throw s.thrown||c instanceof M?c:new M("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function kt(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=bt(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0)return;let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},c=n.buildContext(a,s);Promise.resolve(Tt(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let u=d instanceof M?d:new M("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(u,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var b=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 Os=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),fe=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new b("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new b("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new b("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??Os;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 xs={maxRetries:0,backoffMs:()=>0},Rs=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ge=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??xs,this.sleep=t.sleep??Rs;}add(e){return 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 execute(e){let t=0;for(;;)try{return await e()}catch(r){if(t>=this.retry.maxRetries)throw r;t+=1,await this.sleep(this.retry.backoffMs(t));}}};var Ls=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function It(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 fe({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},u=c?new ge({concurrency:1,retry:c},d):void 0,l=n.length,y=0;for(let f of n){await a.acquire(f);let g=()=>e(t.sendTo(f)).then(()=>{});try{u?await u.add(g):await g(),s.sent.push(f),y+=1,r.onProgress?.(y,l,f,!0);}catch(h){s.failed.push({jid:f,error:Ls(h)}),y+=1,r.onProgress?.(y,l,f,false);}}return s}var he=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new b("NOT_CONNECTED","client not connected");return e}async update(e,t){let r=this.requireSocket();try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new b("PRESENCE_FAILED",`presence update '${e}' failed`,{cause:s})}}scheduleClear(e,t){let r=this.getSocket();if(!r)return;let s=setTimeout(()=>{r.sendPresenceUpdate("paused",e).catch(()=>{});},t);typeof s.unref=="function"&&s.unref();}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 Ns={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},Ds=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",ye=class{store;sendSnapshot;now;timer;logger;memory=new Map;timers=new Map;constructor(e){this.store=e.store,this.sendSnapshot=e.sendSnapshot,this.now=e.now??(()=>Date.now()),this.timer=e.timer??Ns,this.logger=e.logger;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new b("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)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()),r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),this.memory.delete(e.id),Ds(e.payload))try{await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed");}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={sendMessage:async(i,o,a)=>(t=a?{recipient:i,content:o,options:a}:{recipient:i,content:o},{key:{remoteJid:i,id:"scheduled-snapshot",fromMe:true}})},s=j.create(r,"");try{await e(s);}catch(i){throw new b("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:i})}if(!t)throw new b("SCHEDULE_INVALID","scheduled builder produced no content");return t}};var H="[zaileys]",Bs="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 kn(n){switch(n.kind){case "connecting":return `${H} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${H} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${H} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${H} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${H} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
12
- ${H} ${Bs}`:t}case "disconnect":return n.willReconnect?null:`${H} Disconnected (${n.reason}).`;default:return null}}var Tn=false,Fs=["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:"],Ws=n=>typeof n[0]=="string"&&Fs.some(e=>n[0].startsWith(e));function In(){if(Tn)return;Tn=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{Ws(r)||t(...r);};};n("info"),n("warn"),n("error");}var p=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 js="./.zaileys/auth",Ks=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),Se=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",$e=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??js;}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,Di.BufferJSON.reviver);}catch(o){if(Se(o))return;throw new p("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});for(let o of Object.keys(s)){let a=s[o],c=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(c).catch(d=>{if(!Se(d))throw new p("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,Di.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(!Se(i))throw new p("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen(),await fs$1.promises.rm(this.basePath,{recursive:true,force:true});},close:async()=>{this.closed=true;}};creds={readCreds:async()=>{this.assertOpen();try{let e=await fs$1.promises.readFile(this.credsPath(),"utf8");return JSON.parse(e,Di.BufferJSON.reviver)}catch(e){if(Se(e))return;throw new p("STORE_READ_FAILED","failed to read creds.json",{cause:e})}},writeCreds:async e=>{this.assertOpen(),await fs$1.promises.mkdir(this.basePath,{recursive:true}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,Di.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!Se(e))throw new p("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return we__default.default.join(this.basePath,"creds.json")}signalDir(e){return we__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return we__default.default.join(this.signalDir(e),`${Ks(t)}.json`)}async atomicWrite(e,t){let r=we__default.default.join(we__default.default.dirname(e),`tmp-${crypto.randomBytes(8).toString("hex")}`);try{await fs$1.promises.writeFile(r,t,"utf8"),await fs$1.promises.rename(r,e);}catch(s){throw await fs$1.promises.unlink(r).catch(()=>{}),new p("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","FileAuthStore is closed")}};function On(n,e){let t=n.signal,s=Di.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 c={},d={};for(let u of a)d[u]=null;c[o]=d,await s.set(c);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close()};return {creds:n.creds,signal:i}}function xn(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);},clear:async()=>{await n.clear();}}}function Rn(n){switch(n){case Di.DisconnectReason.loggedOut:return "logged-out";case Di.DisconnectReason.forbidden:return "forbidden";case Di.DisconnectReason.connectionLost:return "connection-lost";case Di.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case Di.DisconnectReason.connectionClosed:return "connection-closed";case Di.DisconnectReason.connectionReplaced:return "connection-replaced";case Di.DisconnectReason.badSession:return "bad-session";case Di.DisconnectReason.unavailableService:return "unavailable-service";case Di.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function ve(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Ln(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function Hd(n){return !ve(n)}var Js=/[\s\-()+]/g;function $s(n){return typeof n!="string"?"":n.replace(Js,"")}function Vs(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=$s(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 _n(n){let e=Vs(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 Hs(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{Gs__default.default.generate(n,{small:true},t=>e(t));})}async function Nn(n,e=t=>{process.stdout.write(t);}){let t=await Hs(n);e(t+`
13
- `);}var Ae={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:1e3,maxDelayMs:6e4,jitterFactor:.2};function Dn(n,e){let t=n?.enabled??Ae.enabled,r=n?.maxAttempts??Ae.maxAttempts,s=n?.initialDelayMs??Ae.initialDelayMs,i=n?.maxDelayMs??Ae.maxDelayMs,o=n?.jitterFactor??Ae.jitterFactor,a=e?.random??Math.random,c=0;return {next:l=>{if(!t||ve(l))return null;let y=c+1;if(y>r)return null;c=y;let f=Math.pow(2,y-1),g=Math.min(i,s*f),h=1+(a()*2-1)*o,A=g*h,v=Math.min(i,Math.max(0,A));return {attempt:y,delayMs:Math.round(v)}},reset:()=>{c=0;},get attempts(){return c}}}var zs={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 Bn(n="idle"){let e=n,t=new Set,r=s=>zs[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 Ot=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Ve=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=Ot(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(Ot(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=(...c)=>{let u=c[0]?.messages;if(Array.isArray(u))for(let l of u)this.saveMessage(l).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d){let l=this.messages.get(Ot(u.key));if(l){let y={...l,...u.update};this.saveMessage(y).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveChat(u).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d){let y={...this.chats.get(u.id)??{},...u};this.saveChat(y).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveContact(u).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let u of Object.keys(d.presences)){let l=d.presences[u];l&&this.savePresence(u,l).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[c,d]of this.listeners)e.ev.on(c,d);}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()}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","MemoryMessageStore is closed")}};var Zs=["silent","fatal","error","warn","info","debug","trace"];function Xs(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":Zs.includes(e)?e:"silent"}function Qs(n={}){let e=Xs(n.level),t=Ys__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Fn=["debug","info","warn","error","fatal"];function ei(n){if(n===null||typeof n!="object")return false;for(let e of Fn)if(typeof n[e]!="function")return false;return true}function Me(){}function ti(n){let e={debug:Me,info:Me,warn:Me,error:Me,fatal:Me};for(let t of Fn){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function xt(n,e){return n===void 0?e??Qs():ei(n)?n:ti(n)}var ol=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),Wn=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var ni=new Set(["offer","ringing"]),ri=new Set(["timeout","reject","accept","terminate"]),Un=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},jn=n=>typeof n.id!="string"||n.id.length===0||!ni.has(n.status)?null:{kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Un(n.date),status:n.status},Kn=n=>typeof n.id!="string"||n.id.length===0||!ri.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Un(n.date),status:n.status};var I=n=>typeof n=="string"&&n.length>0,si=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},qn=(n,e,t)=>n.filter(r=>I(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return I(i)&&(s.participantAlt=i),I(e)&&(s.authorPn=e),I(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),Jn=n=>I(n?.id)?{groupId:n.id,update:si(n),timestamp:Date.now()}:null,$n=n=>{if(!I(n?.groupId)||!I(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 I(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},ii=new Set(["add","invite","invite-link"]),oi=new Set(["remove","leave"]),Vn=n=>{if(!I(n?.id)||!ii.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=qn(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 I(n.author)&&(t.by=n.author),t},Gn=n=>{if(!I(n?.id)||!oi.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=qn(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 I(n.author)&&(t.by=n.author),t};var Ee=n=>typeof n!="string"||n.length===0?null:Di.jidNormalizedUser(n),K=n=>typeof n=="string"&&n.length>0?n:void 0,di=["@s.whatsapp.net","@c.us"],li=n=>n.endsWith("@lid"),ui=n=>di.some(e=>n.endsWith(e)),D=(n,e)=>{if(!n)return null;let t=K(n.participant)??n.remoteJid,r=Ee(t);if(r===null)return null;let s=K(n.participantAlt)??K(n.remoteJidAlt),i=s!=null?Ee(s):null,o=K(n.participantUsername)??K(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true},c=i!==null?[r,i]:[r],d=c.find(li),u=c.find(ui);d!==void 0&&(a.lid=d),u!==void 0&&(a.pn=u),o!==void 0&&(a.username=o);let l=K(e);return l!==void 0&&(a.pushName=l),a},Hn=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=K(n.participant),r=K(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=D(s);return o&&(i.sender=o),i},Ge=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 Ce=n=>Di.isJidGroup(n)===true,He=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};var pi=["quick_reply","cta_url","cta_call","button_click"],mi=["list_select","single_select"],F=n=>typeof n=="string"&&n.length>0,Yn=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return D(n.key,e)},Zn=n=>He(n.messageTimestamp)??0,Xn=(n,e)=>{if(!F(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}},ze=(n,e)=>{for(let t of e){let r=n[t];if(F(r))return r}},Qn=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&F(r.selectedButtonId))return Rt(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&F(s.selectedId))return Rt(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&F(i.name)&&pi.includes(i.name)){let o=Xn(i.paramsJson,e.logger);if(!o)return null;let a=ze(o,["id","button_id"]);return a===void 0?null:Rt(n,a,ze(o,["display_text"])??null)}return null},Rt=(n,e,t)=>{let r=Yn(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Zn(n)};return F(t)&&(s.buttonText=t),s},er=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(F(s))return zn(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&F(i.name)&&mi.includes(i.name)){let o=Xn(i.paramsJson,e.logger);if(!o)return null;let a=ze(o,["row_id","id"]);return a===void 0?null:zn(n,a,ze(o,["title"])??null)}return null},zn=(n,e,t)=>{let r=Yn(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Zn(n)};return F(t)&&(s.title=t),s};var fi=new Set(["available","unavailable","composing","recording","paused"]),gi=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,tr=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},Lt=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:gi(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},nr=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"||!fi.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Pe=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 yi=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},wi=n=>{let e=`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`,t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},Si=n=>{let e=Di.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"},vi=n=>n.trim().endsWith("?"),Ai=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Mi=(n,e)=>{if(e.length===0)return false;let t;try{t=Di.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return Di.jidNormalizedUser(r)===t}catch{return r===n}})},Ei=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.includes(e):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},_t=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ce(e),r={uniqueId:wi(n.key),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId,roomId:t?e:null,senderId:n.sender.pn??n.sender.jid,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderDevice:Si(n.sender.jid),timestamp:typeof n.message.messageTimestamp=="number"?n.message.messageTimestamp*1e3:0,text:n.text,mentions:n.mentions,links:yi(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isQuestion:vi(n.text),isPrefix:Ai(n.text,n.prefixes),isTagMe:Mi(n.selfJid,n.mentions),isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isSpam:false,isHideTags:false,isStatusMention:false,isGroupStatusMention:false,isStory:false,roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:Ei(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(r.media=n.media),r};var Ci={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Pi=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Ci[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},sr=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Pi(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")}},ir=(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 Te={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},cr=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},be=n=>{let e=n.message;if(e==null)return null;if(typeof e.conversation=="string"&&e.conversation.length>0)return e.conversation;let t=e.extendedTextMessage;return t!=null&&typeof t.text=="string"&&t.text.length>0?t.text:null},Nt=n=>{let e=n.message;if(e==null)return null;let t=e.extendedTextMessage?.contextInfo;if(t!=null)return t;for(let r of Object.values(Te)){let s=e[r];if(s!=null&&typeof s=="object"){let i=s.contextInfo;if(i!=null)return i}}return null},bi=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Te[e]];return r==null||typeof r!="object"?null:r},Ti=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(Te)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},ki=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,ar=n=>{if(n==null)return "text";for(let e of Object.values(Te))if(n[e]!=null)return e.replace("Message","");return "text"},Ii=async(n,e,t)=>{try{if(n==null||n.quotedMessage==null)return null;let r=n.stanzaId;if(typeof r!="string"||r.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let d=await e.resolveQuoted(r,t);if(d!=null&&d.message!=null){let u=be(d)??"",l=ne(d,e,ar(d.message),u);if(l!==null)return l}}let s=Hn(n);if(s===null||typeof s.key.id!="string"||s.key.id.length===0)return null;let i=s.key.remoteJid;if(typeof i!="string"||i.length===0)return null;let o=n.quotedMessage,a=Object.assign({key:s.key,message:o??null},s.sender?.pushName!=null?{pushName:s.sender.pushName}:{}),c=be(a)??"";return ne(a,e,ar(o),c)}catch{return null}},ne=(n,e,t,r,s)=>{let i=n.key;if(i==null)return null;let o=D(i,n.pushName??void 0);if(o===null)return null;let a=cr(i);if(a.length===0)return null;let c=Nt(n),d=Ce(a),u=a.endsWith("@broadcast"),l=a.endsWith("@newsletter"),y=c?.isForwarded===true||(c?.forwardingScore??0)>0,f=Ti(n),g=ki(n,c),h=e.channelId??"",A=e.receiverId??"",v=e.prefixes??[],X=()=>d&&e.resolveRoomName!=null?e.resolveRoomName(a):Promise.resolve(null),Re=e.resolveReceiverName??(()=>Promise.resolve(null)),dt=()=>Ii(c,e,a),lt=a.length>0?a:o.pn??o.jid,ut=(ft,Kr)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(lt,ft,Kr,n),pt=ft=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(i,ft),{mentionedJids:mt}=Ge(c),Ut={message:n,key:i,channelId:h,receiverId:A,selfJid:e.selfJid,text:r,chatType:t,sender:o,mentions:mt,isViewOnce:f,isEphemeral:g,isForwarded:y,isBroadcast:u,isNewsletter:l,prefixes:v,resolveRoomName:X,resolveReceiverName:Re,resolveReplied:dt,reply:ut,react:pt},jt=s!==void 0?{...Ut,media:s}:Ut;return _t(e.citationConfig!==void 0?{...jt,citationConfig:e.citationConfig}:jt)},dr=(n,e)=>{let t=be(n);return t===null?null:ne(n,e,"text",t)},ke=(n,e,t)=>{let r=bi(e,n);if(r===null)return null;let s=typeof r.caption=="string"?r.caption:"",i=n,o=sr(e,n,t.logger),a=ir(e,n,t.logger);return ne(e,t,i,s,{buffer:async()=>(await o()).buffer,stream:a})},lr=(n,e)=>ke("image",n,e),ur=(n,e)=>ke("video",n,e),pr=(n,e)=>ke("audio",n,e),mr=(n,e)=>ke("document",n,e),fr=(n,e)=>ke("sticker",n,e),Oi=(n,e)=>{try{return Di.jidNormalizedUser(n)===Di.jidNormalizedUser(e)}catch{return n===e}},gr=(n,e)=>{if(n.key==null)return null;let r=Nt(n),{mentionedJids:s}=Ge(r);if(s.length===0||!s.some(u=>Oi(u,e.selfJid)))return null;let o=n.message;if(o==null)return null;let a=be(n)??"",c="text";if(o!=null){let u=Object.values(Te);for(let l of u)if(o[l]!=null){c=l.replace("Message","");break}}let d=ne(n,e,c,a);return d===null?null:{...d,mentionedJids:s,selfJid:e.selfJid}},hr=(n,e)=>{let t=n.key;if(t==null)return null;let r=cr(t);if(r.length===0||!Ce(r))return null;let{mentionAll:s}=Ge(Nt(n));if(!s||n.message==null)return null;let o=be(n)??"",a=ne(n,e,"text",o);return a===null?null:{...a,isMentionAll:true,selfJid:e.selfJid}};var z=(n,e)=>{let t=He(n);return t===null?e:t},xi=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;return typeof s=="string"?s:""},Ri=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],wr=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=D(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:z(t.senderTimestampMs,0)}},Sr=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Di.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=D(n.key,e.pushName);return s===null?null:{key:r,newContent:xi(t.editedMessage),editedAt:z(n.update.messageTimestamp,0),sender:s}},vr=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Di.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=D(n.key,e.pushName);if(s===null)return null;let i=Ee(n.key.remoteJid),o=Ee(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:z(n.update.messageTimestamp,0)}},Ar=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=D(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;return i?{pollKey:i,selectedOptions:Ri(t.vote?.selectedOptions),voter:s,timestamp:z(t.senderTimestampMs,z(n.update.messageTimestamp,0))}:null}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:z(r.senderTimestampMs,z(n.update.messageTimestamp,0))}:null}return null};var Ye=n=>Array.isArray(n)?n:[],Li=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function Mr(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?f=>{let g=s.get(f);if(g!==void 0)return g;let h=t.groupMetadata;if(h==null)return Promise.resolve(null);let A=h(f).then(v=>v?.subject??null).catch(()=>null);return s.set(f,A),A}:void 0,o={selfJid:t.selfJid,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},c={selfJid:t.selfJid},d=(f,g)=>{let h=(...A)=>{try{g(A[0]);}catch(v){t.logger?.warn(v,`inbound pipeline: handler for ${f} threw`);}};e.ev.on(f,h),r.push(()=>e.ev.off(f,h));},u=f=>{l(()=>dr(f,o),g=>n.emit("text",g)),l(()=>lr(f,o),g=>n.emit("image",g)),l(()=>ur(f,o),g=>n.emit("video",g)),l(()=>pr(f,o),g=>n.emit("audio",g)),l(()=>mr(f,o),g=>n.emit("document",g)),l(()=>fr(f,o),g=>n.emit("sticker",g)),l(()=>gr(f,o),g=>n.emit("mention",g)),l(()=>hr(f,o),g=>n.emit("mention-all",g)),l(()=>Qn(f,a),g=>n.emit("button-click",g)),l(()=>er(f,a),g=>n.emit("list-select",g));},l=(f,g)=>{let h;try{h=f();}catch(A){t.logger?.warn(A,"inbound pipeline: decoder threw");return}h!=null&&g(h);};d("messages.upsert",f=>{let g=Wn(f);for(let h of g.messages)t.ignoreMe===!0&&h.key?.fromMe===!0||u(h);}),d("messages.update",f=>{for(let g of Ye(f))l(()=>Sr(g,c),h=>n.emit("edit",h)),l(()=>vr(g,c),h=>n.emit("delete",h)),l(()=>Ar(g,c),h=>n.emit("poll-vote",h));}),d("messages.reaction",f=>{for(let g of Ye(f))l(()=>wr(g,c),h=>n.emit("reaction",h));}),d("groups.update",f=>{for(let g of Ye(f))l(()=>Jn(g),h=>n.emit("group-update",h));}),d("group-participants.update",f=>{let g=f;l(()=>Vn(g),h=>n.emit("group-join",h)),l(()=>Gn(g),h=>n.emit("group-leave",h));}),d("group.member-tag.update",f=>{l(()=>$n(f),g=>n.emit("member-tag",g));}),d("call",f=>{for(let g of Ye(f))l(()=>jn(g),h=>n.emit("call-incoming",h)),l(()=>Kn(g),h=>n.emit("call-ended",h));}),d("messaging-history.status",f=>{l(()=>tr(f),g=>n.emit("history-sync",g));}),d("presence.update",f=>{let g=(()=>{try{return nr(f)}catch(h){return t.logger?.warn(h,"inbound pipeline: decodePresence threw"),[]}})();for(let h of g)n.emit("presence",h);}),d("connection.update",f=>{let g=Li(f);g!==null&&l(()=>Lt({source:"connection-update",reachoutTimeLock:g}),h=>n.emit("limited",h));}),d("message-capping.update",f=>{l(()=>Lt({source:"message-capping",capInfo:f}),g=>n.emit("limited",g));}),d("newsletter.reaction",f=>{l(()=>Pe({source:"reaction",payload:f}),g=>n.emit("newsletter",g));}),d("newsletter.view",f=>{l(()=>Pe({source:"view",payload:f}),g=>n.emit("newsletter",g));}),d("newsletter-participants.update",f=>{l(()=>Pe({source:"participants",payload:f}),g=>n.emit("newsletter",g));}),d("newsletter-settings.update",f=>{l(()=>Pe({source:"settings",payload:f}),g=>n.emit("newsletter",g));});let y=false;return {detach(){if(!y){y=true;for(let f of r)f();r.length=0;}}}}var Ze=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=Ni,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Ni=Symbol("zaileys.typed-ee.tag");var Fi="default",Wi="qr",Ui=6e4,Cr=class extends Ze{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=Bn();reconnectStrategy;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;waVersion;versionWarming;constructor(e={}){super({logger:xt(e.logger)}),this.sessionId=e.sessionId??Fi,this.logger=xt(e.logger),this.authType=e.authType??Wi,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&In(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new $e({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Ve,this.reconnectStrategy=Dn(this.reconnectOptions),this.commandPrefixes=ji(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(t=>this.emitAutoConnectError(t));}catch(t){this.emitAutoConnectError(t);}});});}warmVersion(){if(this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof Di.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=Di.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=kn(e);t&&process.stderr.write(`${t}
14
- `);}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 state(){return this.machine.state}get socket(){return this._socket}get group(){return this._group??=new de(()=>this._socket)}get privacy(){return this._privacy??=new le(()=>this._socket)}get newsletter(){return this._newsletter??=new ue(()=>this._socket)}get community(){return this._community??=new pe(()=>this._socket)}get presence(){return this._presence??=new he(()=>this._socket)}async broadcast(e,t,r){return this.requireSocket(),It(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ye({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(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 Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";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=On(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=xn(this.auth.signal,this.logger),s={markOnlineOnConnect:false,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger},i=Di__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{this.connectResolve=a,this.connectReject=c;});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??Di.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}async disconnect(){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._scheduler?.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.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");}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 me).register(e,t),this.attachCommandsIfReady(),this}use(e){return this.commandMiddleware.push(e),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=kt({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r)});}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.send(o).text(s,i).reply(t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new M("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.requireSocket();return Ke(e)?j.create(t,e):j.create(t,e,r=>this.resolveRecipient(r))}edit(e){return new ce(this.requireSocket(),e)}async delete(e,t){await Mt(this.requireSocket(),e,t);}async react(e,t){return Et(this.requireSocket(),e,t)}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return Ct(r,this.store,e,s)}resolveRecipient(e){return Pt(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new m("INVALID_OPTIONS","client not connected");return this._socket}attachEmitterLogger(){this.logger;}wireSocket(e){let t=s=>{this.handleConnectionUpdate(s);},r=s=>{let i=this.creds?Object.assign(this.creds,s):s;this.creds=i,this.auth.creds.writeCreds(i).catch(o=>{this.logger.warn(o,"auth.creds.writeCreds failed");});};e.ev.on("connection.update",t),e.ev.on("creds.update",r),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.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;this.pairingRequested=true,this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let t=_n({phoneNumber:this.phoneNumber}),r=this._socket;if(!r)return;let s=await t.requestCode(r);this.logStatus({kind:"pairing-code",code:s.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:s.code,expiresAt:s.expiresAt});}catch(t){this.logger.warn(t,"pairing-code request failed");}return}if(this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Nn(e);}catch(t){this.logger.warn(t,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:Date.now()+Ui});}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,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=Mr(this,t,{selfJid:typeof e.id=="string"?e.id:"",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),sendReply:async(s,i,o,a)=>await this.send(s).text(i,o).reply(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"));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}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{return null}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=Ki(e?.error),r=Rn(t),s=false;if(Ln(r)){try{await this.auth.signal.clear();}catch(i){this.logger.warn(i,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(i){this.logger.warn(i,"auth.creds.deleteCreds failed (post-close)");}}if(!ve(r)){let i=this.reconnectStrategy.next(r);if(i!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let o=this.credsLoadedAtConnect&&!this.openedThisRun&&i.attempt>=2&&!this.credsHintShown;o&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:i.attempt,delayMs:i.delayMs,reason:r,invalidCredsSuspected:o}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:i.attempt,delayMs:i.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(a=>{this.logger.warn(a,"reconnect attempt failed");});},i.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 i of this.listenerCleanup)i.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function ji(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function Ki(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 Pr=class{credsBlob;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;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new p("STORE_CLOSED","MemoryAuthStore is closed")}};var Xe=null,qi=async()=>{if(Xe)return Xe;try{return Xe=(await import('better-sqlite3')).default,Xe}catch(n){throw new p("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Dt="default",Tr=500,kr=n=>Array.from({length:n},()=>"?").join(","),Ir=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Or=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Dt);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Dt,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Dt);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Ir(t,Tr)){let o=kr(i.length),c=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let d of c)r[d.id]=this.parseBlob(d.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let c=e[a];if(c)for(let d of Object.keys(c)){let u=c[d];u===null?i.push({type:a,id:d}):u!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(u)});}}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=kr(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Ir(t,Tr))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 p("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new p("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 qi(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new p("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;
15
- 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 p("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,Di.BufferJSON.replacer),"utf8")}catch(t){throw new p("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,Di.BufferJSON.reviver)}catch(t){throw new p("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var et,Ji=async()=>(et||(et=import('pg').catch(n=>{throw et=void 0,new p("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),et),$i="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",Vi="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",xr=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new p("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new p("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}async ensureReady(){if(this.closed)throw new p("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 Ji(),r=t.Pool??t.default?.Pool;if(!r)throw new p("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query($i),await e.query(Vi);}catch(t){throw new p("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,c)=>`$${c+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 c=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(c.toString("utf8"),Di.BufferJSON.reviver);}return s}catch(i){throw i instanceof p?i:new p("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 c=o[a];if(c===null)r.push({kind:"delete",type:String(i),id:a});else if(c!==void 0){let d=Buffer.from(JSON.stringify(c,Di.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:d});}}}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 p("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 p("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 p("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{}}};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,Di.BufferJSON.reviver)}catch(t){throw t instanceof p?t:new p("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,Di.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 p("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 p("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var Gi="zaileys",Hi=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],zi=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Rr=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new p("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new p("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??Gi,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 c=i[a];c!=null&&(o[t[a]]=JSON.parse(c,Di.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 c=o[a],d=this.signalKey(i,a),u=this.indexKey(i);c===null?(r.del(d),r.sRem(u,a)):c!==void 0&&(r.set(d,JSON.stringify(c,Di.BufferJSON.replacer)),r.sAdd(u,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 Hi){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();}};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,Di.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,Di.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));}};credsKey(){return `${this.namespace}:auth:creds`}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 p("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 zi(r)?new p("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new p("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 p("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new p("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new p("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 p("STORE_CLOSED","RedisAuthStore is closed")}};var Yi="zaileys",Ie={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Zi=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},re=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new p("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new p("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??Yi,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(Ie.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(Ie.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(Ie.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ie.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(Ie.list,s))??[]}close(){this.closed=true,this.client=void 0;}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 Zi(r)?new p("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new p("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 p("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new p("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","Convex store is closed")}};var rt="creds",Xi="signal:",Oe=(n,e)=>`${Xi}${n}:${e}`,Lr=class{creds;signal;kv;constructor(e){this.kv=new re(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([rt])).get(rt);return s===void 0?void 0:JSON.parse(s,Di.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:rt,value:JSON.stringify(r,Di.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([rt]);}},this.signal={async read(r,s){let i=s.map(c=>Oe(r,c)),o=await t.get(i),a={};for(let c of s){let d=o.get(Oe(r,c));a[c]=d===void 0?void 0:JSON.parse(d,Di.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 c of Object.keys(a)){let d=a[c];d==null?i.push(Oe(o,c)):s.push({key:Oe(o,c),value:JSON.stringify(d,Di.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=>Oe(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var st=null,Qi=async()=>{if(st)return st;try{return st=(await import('better-sqlite3')).default,st}catch(n){throw new p("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},it=n=>{try{return Buffer.from(JSON.stringify(n,Di.BufferJSON.replacer),"utf8")}catch(e){throw new p("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},Y=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,Di.BufferJSON.reviver)}catch(e){throw new p("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},_r=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;constructor(e){this.options=e;}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,it(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?Y(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=>Y(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,it(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?Y(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>Y(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,it(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?Y(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>Y(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,it(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?Y(r.data):void 0}bind(e){if(this.closed)throw new p("STORE_CLOSED","SqliteMessageStore is closed");this.boundSocket=e;let t=(...o)=>{let c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).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 p("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}async ensureReady(){if(this.closed)throw new p("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 Qi(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new p("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 (
10
+ `:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),Ue(n.buttons,t)};var qe=n=>{if(typeof n!="string"||n.trim().length===0)throw new m("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var kn=(n,e)=>({recipient:n,...e?{resolveRecipient:e}:{}});var bs=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],q=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r){return new n(e,kn(t,r))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=un(hn(e),t):this.internal.content=qe(e),this}image(e,t){return this.internal.pendingContent=te(e,t),this}video(e,t){return this.internal.pendingContent=ne(e,t),this}audio(e,t){return this.internal.pendingContent=an(e,t),this}document(e,t){return this.internal.pendingContent=wn(e,t),this}sticker(e,t){return this.internal.pendingContent=bn(e,t),this}buttons(e,t){return this.internal.content=Ue(e,t),this}carousel(e,t){return this.internal.content=ln(e,t),this}list(e){return this.internal.content=vn(e),this}poll(e,t,r){return this.internal.content=Cn(e,t,r),this}location(e,t,r){return this.internal.content=An(e,t,r),this}contact(e){return this.internal.content=yn(e),this}template(e){return this.internal.content=Tn(e),this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new m("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 m("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new m("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}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new m("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.albumItems){let d={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(d.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(d.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(d.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(d.disappearingSeconds=this.internal.disappearingSeconds),nn(this.socket,this.internal.recipient,this.internal.albumItems,d)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new m("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[L];if(i!==void 0){let d=s[Mt],u=s[Ct];return this.sendRelay(i,d,u)}let o=this.internal.content;this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds);let c;try{c=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(d){throw new m("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new m("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await k(t.src),s=await Yi.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 sendRelay(e,t,r){let s=this.socket.relayMessage;if(typeof s!="function")throw new m("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let l=e.interactiveMessage?.header;t!==void 0&&l&&await this.uploadHeaderMedia(l,t);let y=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&y)for(let f of r){let g=y[f.index]?.header;g&&await this.uploadHeaderMedia(g,f);}}catch(l){throw new m("SEND_FAILED","interactive media upload failed",{cause:l})}let o={userJid:this.socket.user?.id??""},a=this.internal.quoted;a!==void 0&&a.message!=null&&(o.quoted=a);let c=Yi.generateWAMessageFromContent(this.internal.recipient,e,o);if(typeof c.key?.id!="string")throw new m("SEND_FAILED","failed to generate relay message key");let u="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:c.key.id,additionalNodes:bs}:{messageId:c.key.id};try{await s(this.internal.recipient,c.message,u);}catch(l){throw new m("SEND_FAILED","socket relayMessage rejected",{cause:l})}return c.key}};var le=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=qe(e),this}image(e,t){return this.pendingContent=te(e,t),this}video(e,t){return this.pendingContent=ne(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 m("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new m("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 m("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new m("SEND_FAILED","socket returned no message key");return r.key}};var In=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new m("INVALID_OPTIONS","message key is missing remoteJid");return e},On=n=>{if(!n?.key)throw new m("SEND_FAILED","socket returned no message key");return n.key},Pt=async(n,e,t={})=>{let r=In(e),i=t.forEveryone??true?e:{...e,fromMe:true};await n.sendMessage(r,{delete:i});},Tt=async(n,e,t)=>{let r=In(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return On(s)},kt=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new m("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return On(i)};var Ps=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Je=n=>Ps.test(n),It=async(n,e,t,r=Ts)=>{if(Je(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 c=(await n.onWhatsApp(e))?.find(d=>d.exists&&d.jid);if(!c)throw new m("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,c.jid),c.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Ts=new Map;var C=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 ue=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new C("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}async create(e,t){return this.requireSocket().groupCreate(e,t)}async addMember(e,t){let r=await this.requireSocket().groupParticipantsUpdate(e,t,"add");return this.mapParticipants(r)}async removeMember(e,t){let r=await this.requireSocket().groupParticipantsUpdate(e,t,"remove");return this.mapParticipants(r)}async promote(e,t){let r=await this.requireSocket().groupParticipantsUpdate(e,t,"promote");return this.mapParticipants(r)}async demote(e,t){let r=await 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 C("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new C("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.requireSocket().groupAcceptInvite(e);if(!t)throw new C("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);}};var pe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new C("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);}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);}};var me=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new C("NOT_CONNECTED","client not connected");return e}async create(e,t){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.requireSocket().newsletterFollow(e);}async unfollow(e){await this.requireSocket().newsletterUnfollow(e);}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new C("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);}};var fe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new C("NOT_CONNECTED","client not connected");return e}async create(e,t){return this.requireSocket().communityCreate(e,t)}async createGroup(e,t,r){return 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.requireSocket().communityAcceptInvite(e)}};var E=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 ks=n=>{let e=n[0];return e==="{"||e==="["},Is=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},Os=n=>n===" "||n===" "||n===`
11
+ `||n==="\r",Rs=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let c=n[a];if(s){t+=c,s=false,i=true,o=false;continue}if(c==="\\"&&r!==null){s=true;continue}if(r!==null){c===r?r=null:t+=c,o=false;continue}if((c==='"'||c==="'")&&o){r=c,i=true,o=false;continue}if(Os(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},xs=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},Ls=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function Ot(n,e){let t=xs(n,e);if(t===null)return Ls(n);let r=n.slice(t.length),s=Rs(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 c=s[a];if(c!==void 0){if(c.startsWith("--")){let d=c.slice(2);if(d.length===0){i.args.push(c);continue}let u=d.indexOf("=");if(u!==-1){let y=d.slice(0,u),f=d.slice(u+1);i.flags[y]=f;continue}let l=s[a+1];l!==void 0&&!l.startsWith("--")?(i.flags[d]=l,a+=1):i.flags[d]=true;continue}if(!o&&ks(c)){let d=Is(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var Ns=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new E("INVALID_COMMAND_NAME","empty command segment in spec");return e},$e=n=>n.join(" "),ge=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new E("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>Ns(a)),s=r[0],i=r.slice(1).map(a=>$e(a)),o={name:$e(s),aliases:i,parts:s,handler:t};for(let a of r){let c=$e(a);if(this.paths.has(c))throw new E("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set($e(a),o),a.length>this.maxDepth&&(this.maxDepth=a.length);this.defs.push(o);}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)}}}list(){return [...this.defs]}};async function Rt(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new E("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(c){throw s.error=c,s.thrown=true,c}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(c){throw s.thrown||c instanceof E?c:new E("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function xt(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=Ot(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0)return;let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},c=n.buildContext(a,s);Promise.resolve(Rt(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let u=d instanceof E?d:new E("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(u,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var T=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 _s=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),he=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new T("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new T("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new T("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??_s;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 Ds={maxRetries:0,backoffMs:()=>0},Bs=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ye=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??Ds,this.sleep=t.sleep??Bs;}add(e){return 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 execute(e){let t=0;for(;;)try{return await e()}catch(r){if(t>=this.retry.maxRetries)throw r;t+=1,await this.sleep(this.retry.backoffMs(t));}}};var Fs=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function Lt(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 he({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},u=c?new ye({concurrency:1,retry:c},d):void 0,l=n.length,y=0;for(let f of n){await a.acquire(f);let g=()=>e(t.sendTo(f)).then(()=>{});try{u?await u.add(g):await g(),s.sent.push(f),y+=1,r.onProgress?.(y,l,f,!0);}catch(h){s.failed.push({jid:f,error:Fs(h)}),y+=1,r.onProgress?.(y,l,f,false);}}return s}var we=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new T("NOT_CONNECTED","client not connected");return e}async update(e,t){let r=this.requireSocket();try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new T("PRESENCE_FAILED",`presence update '${e}' failed`,{cause:s})}}scheduleClear(e,t){let r=this.getSocket();if(!r)return;let s=setTimeout(()=>{r.sendPresenceUpdate("paused",e).catch(()=>{});},t);typeof s.unref=="function"&&s.unref();}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 Us={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},js=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",Se=class{store;sendSnapshot;now;timer;logger;memory=new Map;timers=new Map;constructor(e){this.store=e.store,this.sendSnapshot=e.sendSnapshot,this.now=e.now??(()=>Date.now()),this.timer=e.timer??Us,this.logger=e.logger;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new T("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)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()),r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),this.memory.delete(e.id),js(e.payload))try{await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed");}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={sendMessage:async(i,o,a)=>(t=a?{recipient:i,content:o,options:a}:{recipient:i,content:o},{key:{remoteJid:i,id:"scheduled-snapshot",fromMe:true}})},s=q.create(r,"");try{await e(s);}catch(i){throw new T("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:i})}if(!t)throw new T("SCHEDULE_INVALID","scheduled builder produced no content");return t}};var Y="[zaileys]",Ks="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 xn(n){switch(n.kind){case "connecting":return `${Y} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${Y} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${Y} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${Y} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${Y} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
12
+ ${Y} ${Ks}`:t}case "disconnect":return n.willReconnect?null:`${Y} Disconnected (${n.reason}).`;default:return null}}var Rn=false,qs=["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:"],Js=n=>typeof n[0]=="string"&&qs.some(e=>n[0].startsWith(e));function Ln(){if(Rn)return;Rn=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{Js(r)||t(...r);};};n("info"),n("warn"),n("error");}var p=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 Vs="./.zaileys/auth",Gs=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),Ae=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",Ge=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??Vs;}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,Yi.BufferJSON.reviver);}catch(o){if(Ae(o))return;throw new p("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});for(let o of Object.keys(s)){let a=s[o],c=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(c).catch(d=>{if(!Ae(d))throw new p("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,Yi.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(!Ae(i))throw new p("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen(),await fs$1.promises.rm(this.basePath,{recursive:true,force:true});},close:async()=>{this.closed=true;}};creds={readCreds:async()=>{this.assertOpen();try{let e=await fs$1.promises.readFile(this.credsPath(),"utf8");return JSON.parse(e,Yi.BufferJSON.reviver)}catch(e){if(Ae(e))return;throw new p("STORE_READ_FAILED","failed to read creds.json",{cause:e})}},writeCreds:async e=>{this.assertOpen(),await fs$1.promises.mkdir(this.basePath,{recursive:true}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,Yi.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!Ae(e))throw new p("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return ve__default.default.join(this.basePath,"creds.json")}signalDir(e){return ve__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return ve__default.default.join(this.signalDir(e),`${Gs(t)}.json`)}async atomicWrite(e,t){let r=ve__default.default.join(ve__default.default.dirname(e),`tmp-${crypto.randomBytes(8).toString("hex")}`);try{await fs$1.promises.writeFile(r,t,"utf8"),await fs$1.promises.rename(r,e);}catch(s){throw await fs$1.promises.unlink(r).catch(()=>{}),new p("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","FileAuthStore is closed")}};function Nn(n,e){let t=n.signal,s=Yi.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 c={},d={};for(let u of a)d[u]=null;c[o]=d,await s.set(c);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close()};return {creds:n.creds,signal:i}}function _n(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);},clear:async()=>{await n.clear();}}}function Dn(n){switch(n){case Yi.DisconnectReason.loggedOut:return "logged-out";case Yi.DisconnectReason.forbidden:return "forbidden";case Yi.DisconnectReason.connectionLost:return "connection-lost";case Yi.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case Yi.DisconnectReason.connectionClosed:return "connection-closed";case Yi.DisconnectReason.connectionReplaced:return "connection-replaced";case Yi.DisconnectReason.badSession:return "bad-session";case Yi.DisconnectReason.unavailableService:return "unavailable-service";case Yi.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Me(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Bn(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function cl(n){return !Me(n)}var zs=/[\s\-()+]/g;function Ys(n){return typeof n!="string"?"":n.replace(zs,"")}function Zs(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=Ys(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 Fn(n){let e=Zs(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 Qs(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{Xs__default.default.generate(n,{small:true},t=>e(t));})}async function Wn(n,e=t=>{process.stdout.write(t);}){let t=await Qs(n);e(t+`
13
+ `);}var Ee={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:1e3,maxDelayMs:6e4,jitterFactor:.2};function Un(n,e){let t=n?.enabled??Ee.enabled,r=n?.maxAttempts??Ee.maxAttempts,s=n?.initialDelayMs??Ee.initialDelayMs,i=n?.maxDelayMs??Ee.maxDelayMs,o=n?.jitterFactor??Ee.jitterFactor,a=e?.random??Math.random,c=0;return {next:l=>{if(!t||Me(l))return null;let y=c+1;if(y>r)return null;c=y;let f=Math.pow(2,y-1),g=Math.min(i,s*f),h=1+(a()*2-1)*o,M=g*h,A=Math.min(i,Math.max(0,M));return {attempt:y,delayMs:Math.round(A)}},reset:()=>{c=0;},get attempts(){return c}}}var ei={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 jn(n="idle"){let e=n,t=new Set,r=s=>ei[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 Nt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,He=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=Nt(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(Nt(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=(...c)=>{let u=c[0]?.messages;if(Array.isArray(u))for(let l of u)this.saveMessage(l).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d){let l=this.messages.get(Nt(u.key));if(l){let y={...l,...u.update};this.saveMessage(y).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveChat(u).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d){let y={...this.chats.get(u.id)??{},...u};this.saveChat(y).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveContact(u).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let u of Object.keys(d.presences)){let l=d.presences[u];l&&this.savePresence(u,l).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[c,d]of this.listeners)e.ev.on(c,d);}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()}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","MemoryMessageStore is closed")}};var ni=["silent","fatal","error","warn","info","debug","trace"];function ri(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":ni.includes(e)?e:"silent"}function si(n={}){let e=ri(n.level),t=ti__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Kn=["debug","info","warn","error","fatal"];function ii(n){if(n===null||typeof n!="object")return false;for(let e of Kn)if(typeof n[e]!="function")return false;return true}function Ce(){}function oi(n){let e={debug:Ce,info:Ce,warn:Ce,error:Ce,fatal:Ce};for(let t of Kn){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function _t(n,e){return n===void 0?e??si():ii(n)?n:oi(n)}var vl=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),qn=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var ai=new Set(["offer","ringing"]),ci=new Set(["timeout","reject","accept","terminate"]),Jn=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},$n=n=>typeof n.id!="string"||n.id.length===0||!ai.has(n.status)?null:{kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Jn(n.date),status:n.status},Vn=n=>typeof n.id!="string"||n.id.length===0||!ci.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:Jn(n.date),status:n.status};var O=n=>typeof n=="string"&&n.length>0,di=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},Gn=(n,e,t)=>n.filter(r=>O(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return O(i)&&(s.participantAlt=i),O(e)&&(s.authorPn=e),O(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),Hn=n=>O(n?.id)?{groupId:n.id,update:di(n),timestamp:Date.now()}:null,zn=n=>{if(!O(n?.groupId)||!O(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 O(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},li=new Set(["add","invite","invite-link"]),ui=new Set(["remove","leave"]),Yn=n=>{if(!O(n?.id)||!li.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Gn(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 O(n.author)&&(t.by=n.author),t},Zn=n=>{if(!O(n?.id)||!ui.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Gn(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 O(n.author)&&(t.by=n.author),t};var be=n=>typeof n!="string"||n.length===0?null:Yi.jidNormalizedUser(n),J=n=>typeof n=="string"&&n.length>0?n:void 0,fi=["@s.whatsapp.net","@c.us"],gi=n=>n.endsWith("@lid"),hi=n=>fi.some(e=>n.endsWith(e)),B=(n,e)=>{if(!n)return null;let t=J(n.participant)??n.remoteJid,r=be(t);if(r===null)return null;let s=J(n.participantAlt)??J(n.remoteJidAlt),i=s!=null?be(s):null,o=J(n.participantUsername)??J(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true},c=i!==null?[r,i]:[r],d=c.find(gi),u=c.find(hi);d!==void 0&&(a.lid=d),u!==void 0&&(a.pn=u),o!==void 0&&(a.username=o);let l=J(e);return l!==void 0&&(a.pushName=l),a},Xn=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=J(n.participant),r=J(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=B(s);return o&&(i.sender=o),i},ze=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 Pe=n=>Yi.isJidGroup(n)===true,Ye=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};var yi=["quick_reply","cta_url","cta_call","button_click"],wi=["list_select","single_select"],W=n=>typeof n=="string"&&n.length>0,er=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return B(n.key,e)},tr=n=>Ye(n.messageTimestamp)??0,nr=(n,e)=>{if(!W(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}},Ze=(n,e)=>{for(let t of e){let r=n[t];if(W(r))return r}},rr=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&W(r.selectedButtonId))return Dt(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&W(s.selectedId))return Dt(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&W(i.name)&&yi.includes(i.name)){let o=nr(i.paramsJson,e.logger);if(!o)return null;let a=Ze(o,["id","button_id"]);return a===void 0?null:Dt(n,a,Ze(o,["display_text"])??null)}return null},Dt=(n,e,t)=>{let r=er(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:tr(n)};return W(t)&&(s.buttonText=t),s},sr=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(W(s))return Qn(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&W(i.name)&&wi.includes(i.name)){let o=nr(i.paramsJson,e.logger);if(!o)return null;let a=Ze(o,["row_id","id"]);return a===void 0?null:Qn(n,a,Ze(o,["title"])??null)}return null},Qn=(n,e,t)=>{let r=er(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:tr(n)};return W(t)&&(s.title=t),s};var Si=new Set(["available","unavailable","composing","recording","paused"]),vi=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,ir=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},Bt=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:vi(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},or=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"||!Si.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Te=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 Mi=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},Ei=n=>{let e=`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`,t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},Ci=n=>{let e=Yi.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"},bi=n=>n.trim().endsWith("?"),Pi=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Ti=(n,e)=>{if(e.length===0)return false;let t;try{t=Yi.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return Yi.jidNormalizedUser(r)===t}catch{return r===n}})},ki=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.includes(e):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},Ft=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Pe(e),r={uniqueId:Ei(n.key),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId,roomId:t?e:null,senderId:n.sender.pn??n.sender.jid,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderDevice:Ci(n.sender.jid),timestamp:typeof n.message.messageTimestamp=="number"?n.message.messageTimestamp*1e3:0,text:n.text,mentions:n.mentions,links:Mi(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isQuestion:bi(n.text),isPrefix:Pi(n.text,n.prefixes),isTagMe:Ti(n.selfJid,n.mentions),isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isSpam:false,isHideTags:false,isStatusMention:false,isGroupStatusMention:false,isStory:false,roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:ki(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(r.media=n.media),r};var Ii={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Oi=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Ii[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},cr=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Oi(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")}},dr=(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 ke={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},ur=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},w=n=>n!=null&&typeof n=="object"?n:null,U=n=>typeof n=="string"&&n.length>0?n:null,Ie=(...n)=>{for(let e of n){let t=U(e);if(t!=null)return t}return null},Ri=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage"],pr=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Ri){let i=w(w(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e},xi=n=>{let t=w(w(w(n.botForwardedMessage)?.message)?.richResponseMessage)??w(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=U(w(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
+ `).trim();return i.length>0?i:null},Li=n=>{let e=w(n.templateMessage),t=w(e?.hydratedTemplate)??w(e?.hydratedFourRowTemplate);return U(t?.hydratedContentText)},Ni=n=>Ie(w(n.pollCreationMessage)?.name,w(n.pollCreationMessageV2)?.name,w(n.pollCreationMessageV3)?.name),_i=n=>{let e=w(n.locationMessage)??w(n.liveLocationMessage);if(e==null)return null;let t=Ie(e.name,e.address);if(t!=null){let i=U(e.name),o=U(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},Di=n=>{let e=U(w(n.contactMessage)?.displayName);if(e!=null)return e;let t=w(n.contactsArrayMessage),r=U(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>U(w(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},mr=n=>Ie(n.conversation,w(n.extendedTextMessage)?.text,xi(n),U(w(w(n.interactiveMessage)?.body)?.text),w(n.buttonsMessage)?.contentText,w(n.listMessage)?.description,Li(n),Ni(n),_i(n),Di(n)),Bi=n=>Ie(w(n.buttonsResponseMessage)?.selectedDisplayText,w(n.buttonsResponseMessage)?.selectedButtonId,w(n.templateButtonReplyMessage)?.selectedDisplayText,w(n.templateButtonReplyMessage)?.selectedId,w(n.listResponseMessage)?.title,w(w(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,w(w(n.interactiveResponseMessage)?.body)?.text),Fi=n=>Ie(w(n.imageMessage)?.caption,w(n.videoMessage)?.caption,w(n.documentMessage)?.caption,w(n.documentMessage)?.fileName),Wi=n=>{let e=w(n.message);return e==null?null:mr(pr(e))},Qe=n=>{let e=w(n.message);if(e==null)return null;let t=pr(e);return mr(t)??Bi(t)??Fi(t)},Wt=n=>{let e=n.message;if(e==null)return null;let t=e.extendedTextMessage?.contextInfo;if(t!=null)return t;for(let r of Object.values(ke)){let s=e[r];if(s!=null&&typeof s=="object"){let i=s.contextInfo;if(i!=null)return i}}return null},Ui=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[ke[e]];return r==null||typeof r!="object"?null:r},ji=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(ke)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},Ki=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,lr=n=>{if(n==null)return "text";for(let e of Object.values(ke))if(n[e]!=null)return e.replace("Message","");return "text"},qi=async(n,e,t)=>{try{if(n==null||n.quotedMessage==null)return null;let r=n.stanzaId;if(typeof r!="string"||r.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let u=await e.resolveQuoted(r,t);if(u!=null&&u.message!=null){let l=Qe(u)??"",y=se(u,e,lr(u.message),l);if(y!==null)return y}}let s=Xn(n);if(s===null||typeof s.key.id!="string"||s.key.id.length===0)return null;let i=s.key.remoteJid;if(typeof i!="string"||i.length===0)return null;let o=s.key.participant;typeof o=="string"&&e.selfJid.length>0&&Yi.jidNormalizedUser(o)===Yi.jidNormalizedUser(e.selfJid)&&(s.key.fromMe=!0);let a=n.quotedMessage,c=Object.assign({key:s.key,message:a??null},s.sender?.pushName!=null?{pushName:s.sender.pushName}:{}),d=Qe(c)??"";return se(c,e,lr(a),d)}catch{return null}},se=(n,e,t,r,s)=>{let i=n.key;if(i==null)return null;let o=B(i,n.pushName??void 0);if(o===null)return null;let a=ur(i);if(a.length===0)return null;let c=Wt(n),d=Pe(a),u=a.endsWith("@broadcast"),l=a.endsWith("@newsletter"),y=c?.isForwarded===true||(c?.forwardingScore??0)>0,f=ji(n),g=Ki(n,c),h=e.channelId??"",M=e.receiverId??"",A=e.prefixes??[],ee=()=>d&&e.resolveRoomName!=null?e.resolveRoomName(a):Promise.resolve(null),Ne=e.resolveReceiverName??(()=>Promise.resolve(null)),mt=()=>qi(c,e,a),ft=a.length>0?a:o.pn??o.jid,gt=(wt,Gr)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(ft,wt,Gr,n),ht=wt=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(i,wt),{mentionedJids:yt}=ze(c),Jt={message:n,key:i,channelId:h,receiverId:M,selfJid:e.selfJid,text:r,chatType:t,sender:o,mentions:yt,isViewOnce:f,isEphemeral:g,isForwarded:y,isBroadcast:u,isNewsletter:l,prefixes:A,resolveRoomName:ee,resolveReceiverName:Ne,resolveReplied:mt,reply:gt,react:ht},$t=s!==void 0?{...Jt,media:s}:Jt;return Ft(e.citationConfig!==void 0?{...$t,citationConfig:e.citationConfig}:$t)},fr=(n,e)=>{let t=Wi(n);return t===null?null:se(n,e,"text",t)},Oe=(n,e,t)=>{let r=Ui(e,n);if(r===null)return null;let s=typeof r.caption=="string"?r.caption:"",i=n,o=cr(e,n,t.logger),a=dr(e,n,t.logger);return se(e,t,i,s,{buffer:async()=>(await o()).buffer,stream:a})},gr=(n,e)=>Oe("image",n,e),hr=(n,e)=>Oe("video",n,e),yr=(n,e)=>Oe("audio",n,e),wr=(n,e)=>Oe("document",n,e),Sr=(n,e)=>Oe("sticker",n,e),Ji=(n,e)=>{try{return Yi.jidNormalizedUser(n)===Yi.jidNormalizedUser(e)}catch{return n===e}},vr=(n,e)=>{if(n.key==null)return null;let r=Wt(n),{mentionedJids:s}=ze(r);if(s.length===0||!s.some(u=>Ji(u,e.selfJid)))return null;let o=n.message;if(o==null)return null;let a=Qe(n)??"",c="text";if(o!=null){let u=Object.values(ke);for(let l of u)if(o[l]!=null){c=l.replace("Message","");break}}let d=se(n,e,c,a);return d===null?null:{...d,mentionedJids:s,selfJid:e.selfJid}},Ar=(n,e)=>{let t=n.key;if(t==null)return null;let r=ur(t);if(r.length===0||!Pe(r))return null;let{mentionAll:s}=ze(Wt(n));if(!s||n.message==null)return null;let o=Qe(n)??"",a=se(n,e,"text",o);return a===null?null:{...a,isMentionAll:true,selfJid:e.selfJid}};var Z=(n,e)=>{let t=Ye(n);return t===null?e:t},$i=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;return typeof s=="string"?s:""},Vi=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],Er=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=B(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:Z(t.senderTimestampMs,0)}},Cr=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Yi.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=B(n.key,e.pushName);return s===null?null:{key:r,newContent:$i(t.editedMessage),editedAt:Z(n.update.messageTimestamp,0),sender:s}},br=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Yi.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=B(n.key,e.pushName);if(s===null)return null;let i=be(n.key.remoteJid),o=be(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:Z(n.update.messageTimestamp,0)}},Pr=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=B(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;return i?{pollKey:i,selectedOptions:Vi(t.vote?.selectedOptions),voter:s,timestamp:Z(t.senderTimestampMs,Z(n.update.messageTimestamp,0))}:null}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:Z(r.senderTimestampMs,Z(n.update.messageTimestamp,0))}:null}return null};var et=n=>Array.isArray(n)?n:[],Gi=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function Tr(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?f=>{let g=s.get(f);if(g!==void 0)return g;let h=t.groupMetadata;if(h==null)return Promise.resolve(null);let M=h(f).then(A=>A?.subject??null).catch(()=>null);return s.set(f,M),M}:void 0,o={selfJid:t.selfJid,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},c={selfJid:t.selfJid},d=(f,g)=>{let h=(...M)=>{try{g(M[0]);}catch(A){t.logger?.warn(A,`inbound pipeline: handler for ${f} threw`);}};e.ev.on(f,h),r.push(()=>e.ev.off(f,h));},u=f=>{l(()=>fr(f,o),g=>n.emit("text",g)),l(()=>gr(f,o),g=>n.emit("image",g)),l(()=>hr(f,o),g=>n.emit("video",g)),l(()=>yr(f,o),g=>n.emit("audio",g)),l(()=>wr(f,o),g=>n.emit("document",g)),l(()=>Sr(f,o),g=>n.emit("sticker",g)),l(()=>vr(f,o),g=>n.emit("mention",g)),l(()=>Ar(f,o),g=>n.emit("mention-all",g)),l(()=>rr(f,a),g=>n.emit("button-click",g)),l(()=>sr(f,a),g=>n.emit("list-select",g));},l=(f,g)=>{let h;try{h=f();}catch(M){t.logger?.warn(M,"inbound pipeline: decoder threw");return}h!=null&&g(h);};d("messages.upsert",f=>{let g=qn(f);for(let h of g.messages)t.ignoreMe===!0&&h.key?.fromMe===!0||u(h);}),d("messages.update",f=>{for(let g of et(f))l(()=>Cr(g,c),h=>n.emit("edit",h)),l(()=>br(g,c),h=>n.emit("delete",h)),l(()=>Pr(g,c),h=>n.emit("poll-vote",h));}),d("messages.reaction",f=>{for(let g of et(f))l(()=>Er(g,c),h=>n.emit("reaction",h));}),d("groups.update",f=>{for(let g of et(f))l(()=>Hn(g),h=>n.emit("group-update",h));}),d("group-participants.update",f=>{let g=f;l(()=>Yn(g),h=>n.emit("group-join",h)),l(()=>Zn(g),h=>n.emit("group-leave",h));}),d("group.member-tag.update",f=>{l(()=>zn(f),g=>n.emit("member-tag",g));}),d("call",f=>{for(let g of et(f))l(()=>$n(g),h=>n.emit("call-incoming",h)),l(()=>Vn(g),h=>n.emit("call-ended",h));}),d("messaging-history.status",f=>{l(()=>ir(f),g=>n.emit("history-sync",g));}),d("presence.update",f=>{let g=(()=>{try{return or(f)}catch(h){return t.logger?.warn(h,"inbound pipeline: decodePresence threw"),[]}})();for(let h of g)n.emit("presence",h);}),d("connection.update",f=>{let g=Gi(f);g!==null&&l(()=>Bt({source:"connection-update",reachoutTimeLock:g}),h=>n.emit("limited",h));}),d("message-capping.update",f=>{l(()=>Bt({source:"message-capping",capInfo:f}),g=>n.emit("limited",g));}),d("newsletter.reaction",f=>{l(()=>Te({source:"reaction",payload:f}),g=>n.emit("newsletter",g));}),d("newsletter.view",f=>{l(()=>Te({source:"view",payload:f}),g=>n.emit("newsletter",g));}),d("newsletter-participants.update",f=>{l(()=>Te({source:"participants",payload:f}),g=>n.emit("newsletter",g));}),d("newsletter-settings.update",f=>{l(()=>Te({source:"settings",payload:f}),g=>n.emit("newsletter",g));});let y=false;return {detach(){if(!y){y=true;for(let f of r)f();r.length=0;}}}}var tt=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=zi,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},zi=Symbol("zaileys.typed-ee.tag");var Xi="default",Qi="qr",eo=6e4,Ir=class extends tt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=jn();reconnectStrategy;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;waVersion;versionWarming;constructor(e={}){super({logger:_t(e.logger)}),this.sessionId=e.sessionId??Xi,this.logger=_t(e.logger),this.authType=e.authType??Qi,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&Ln(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ge({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new He,this.reconnectStrategy=Un(this.reconnectOptions),this.commandPrefixes=to(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(t=>this.emitAutoConnectError(t));}catch(t){this.emitAutoConnectError(t);}});});}warmVersion(){if(this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof Yi.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=Yi.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=xn(e);t&&process.stderr.write(`${t}
15
+ `);}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 state(){return this.machine.state}get socket(){return this._socket}get group(){return this._group??=new ue(()=>this._socket)}get privacy(){return this._privacy??=new pe(()=>this._socket)}get newsletter(){return this._newsletter??=new me(()=>this._socket)}get community(){return this._community??=new fe(()=>this._socket)}get presence(){return this._presence??=new we(()=>this._socket)}async broadcast(e,t,r){return this.requireSocket(),Lt(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Se({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}connect(){if(this.authType==="pairing"&&!this.phoneNumber)return Promise.reject(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 Promise.resolve();if(this._socket){for(let a of this.listenerCleanup)a.off();this.listenerCleanup=[],this._socket=void 0;}let e=this.machine.state==="reconnecting";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=Nn(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=_n(this.auth.signal,this.logger),s={markOnlineOnConnect:false,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger},i=Yi__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{this.connectResolve=a,this.connectReject=c;});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??Yi.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}async disconnect(){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._scheduler?.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.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");}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 ge).register(e,t),this.attachCommandsIfReady(),this}use(e){return this.commandMiddleware.push(e),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=xt({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("text",r),()=>this.off("text",r)},buildContext:(t,r)=>this.buildCommandContext(t,r)});}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.send(o).text(s,i).reply(t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new E("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.requireSocket();return Je(e)?q.create(t,e):q.create(t,e,r=>this.resolveRecipient(r))}edit(e){return new le(this.requireSocket(),e)}async delete(e,t){await Pt(this.requireSocket(),e,t);}async react(e,t){return Tt(this.requireSocket(),e,t)}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return kt(r,this.store,e,s)}resolveRecipient(e){return It(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new m("INVALID_OPTIONS","client not connected");return this._socket}attachEmitterLogger(){this.logger;}wireSocket(e){let t=s=>{this.handleConnectionUpdate(s);},r=s=>{let i=this.creds?Object.assign(this.creds,s):s;this.creds=i,this.auth.creds.writeCreds(i).catch(o=>{this.logger.warn(o,"auth.creds.writeCreds failed");});};e.ev.on("connection.update",t),e.ev.on("creds.update",r),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.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;this.pairingRequested=true,this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let t=Fn({phoneNumber:this.phoneNumber}),r=this._socket;if(!r)return;let s=await t.requestCode(r);this.logStatus({kind:"pairing-code",code:s.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:s.code,expiresAt:s.expiresAt});}catch(t){this.logger.warn(t,"pairing-code request failed");}return}if(this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Wn(e);}catch(t){this.logger.warn(t,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:Date.now()+eo});}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,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=Tr(this,t,{selfJid:typeof e.id=="string"?e.id:"",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),sendReply:async(s,i,o,a)=>await this.send(s).text(i,o).reply(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"));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}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{return null}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=no(e?.error),r=Dn(t),s=false;if(Bn(r)){try{await this.auth.signal.clear();}catch(i){this.logger.warn(i,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(i){this.logger.warn(i,"auth.creds.deleteCreds failed (post-close)");}}if(!Me(r)){let i=this.reconnectStrategy.next(r);if(i!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let o=this.credsLoadedAtConnect&&!this.openedThisRun&&i.attempt>=2&&!this.credsHintShown;o&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:i.attempt,delayMs:i.delayMs,reason:r,invalidCredsSuspected:o}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:i.attempt,delayMs:i.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(a=>{this.logger.warn(a,"reconnect attempt failed");});},i.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 i of this.listenerCleanup)i.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function to(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function no(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 Or=class{credsBlob;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;}};creds={readCreds:async()=>(this.assertOpen(),this.credsBlob),writeCreds:async e=>{this.assertOpen(),this.credsBlob=structuredClone(e);},deleteCreds:async()=>{this.assertOpen(),this.credsBlob=void 0;}};assertOpen(){if(this.closed)throw new p("STORE_CLOSED","MemoryAuthStore is closed")}};var nt=null,ro=async()=>{if(nt)return nt;try{return nt=(await import('better-sqlite3')).default,nt}catch(n){throw new p("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Ut="default",xr=500,Lr=n=>Array.from({length:n},()=>"?").join(","),Nr=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},_r=class{options;db=null;prepared=null;readyPromise=null;closed=false;constructor(e){this.options=e;}creds={readCreds:async()=>{let t=(await this.ensureReady()).readCreds.get(Ut);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Ut,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Ut);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Nr(t,xr)){let o=Lr(i.length),c=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let d of c)r[d.id]=this.parseBlob(d.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let c=e[a];if(c)for(let d of Object.keys(c)){let u=c[d];u===null?i.push({type:a,id:d}):u!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(u)});}}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=Lr(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Nr(t,xr))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 p("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new p("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 ro(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new p("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;
16
+ 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 p("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,Yi.BufferJSON.replacer),"utf8")}catch(t){throw new p("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,Yi.BufferJSON.reviver)}catch(t){throw new p("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var st,so=async()=>(st||(st=import('pg').catch(n=>{throw st=void 0,new p("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),st),io="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",oo="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",Dr=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new p("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new p("STORE_CONNECTION_FAILED","PostgresAuthStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}async ensureReady(){if(this.closed)throw new p("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 so(),r=t.Pool??t.default?.Pool;if(!r)throw new p("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(io),await e.query(oo);}catch(t){throw new p("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,c)=>`$${c+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 c=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(c.toString("utf8"),Yi.BufferJSON.reviver);}return s}catch(i){throw i instanceof p?i:new p("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 c=o[a];if(c===null)r.push({kind:"delete",type:String(i),id:a});else if(c!==void 0){let d=Buffer.from(JSON.stringify(c,Yi.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:d});}}}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 p("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 p("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 p("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{}}};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,Yi.BufferJSON.reviver)}catch(t){throw t instanceof p?t:new p("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,Yi.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 p("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 p("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var ao="zaileys",co=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],lo=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Br=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new p("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new p("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??ao,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 c=i[a];c!=null&&(o[t[a]]=JSON.parse(c,Yi.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 c=o[a],d=this.signalKey(i,a),u=this.indexKey(i);c===null?(r.del(d),r.sRem(u,a)):c!==void 0&&(r.set(d,JSON.stringify(c,Yi.BufferJSON.replacer)),r.sAdd(u,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 co){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();}};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,Yi.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,Yi.BufferJSON.replacer)));},deleteCreds:async()=>{this.assertOpen();let e=await this.ensureReady();await this.runWrite(()=>e.del(this.credsKey()));}};credsKey(){return `${this.namespace}:auth:creds`}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 p("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 lo(r)?new p("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new p("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 p("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new p("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new p("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 p("STORE_CLOSED","RedisAuthStore is closed")}};var uo="zaileys",Re={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},po=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},ie=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new p("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new p("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??uo,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(Re.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(Re.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(Re.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Re.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(Re.list,s))??[]}close(){this.closed=true,this.client=void 0;}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 po(r)?new p("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new p("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 p("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new p("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","Convex store is closed")}};var at="creds",mo="signal:",xe=(n,e)=>`${mo}${n}:${e}`,Fr=class{creds;signal;kv;constructor(e){this.kv=new ie(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([at])).get(at);return s===void 0?void 0:JSON.parse(s,Yi.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:at,value:JSON.stringify(r,Yi.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([at]);}},this.signal={async read(r,s){let i=s.map(c=>xe(r,c)),o=await t.get(i),a={};for(let c of s){let d=o.get(xe(r,c));a[c]=d===void 0?void 0:JSON.parse(d,Yi.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 c of Object.keys(a)){let d=a[c];d==null?i.push(xe(o,c)):s.push({key:xe(o,c),value:JSON.stringify(d,Yi.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=>xe(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var ct=null,fo=async()=>{if(ct)return ct;try{return ct=(await import('better-sqlite3')).default,ct}catch(n){throw new p("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},dt=n=>{try{return Buffer.from(JSON.stringify(n,Yi.BufferJSON.replacer),"utf8")}catch(e){throw new p("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},X=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,Yi.BufferJSON.reviver)}catch(e){throw new p("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Wr=class{options;db=null;prepared=null;readyPromise=null;closed=false;boundSocket;listeners=new Map;constructor(e){this.options=e;}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,dt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?X(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=>X(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,dt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?X(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>X(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,dt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?X(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>X(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,dt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?X(r.data):void 0}bind(e){if(this.closed)throw new p("STORE_CLOSED","SqliteMessageStore is closed");this.boundSocket=e;let t=(...o)=>{let c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).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 p("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}async ensureReady(){if(this.closed)throw new p("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 fo(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new p("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 (
16
17
  remote_jid TEXT NOT NULL,
17
18
  id TEXT NOT NULL,
18
19
  from_me INTEGER NOT NULL,
@@ -27,4 +28,4 @@ ${H} ${Bs}`:t}case "disconnect":return n.willReconnect?null:`${H} Disconnected (
27
28
  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(?, ?, ?)
28
29
  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(?, ?)
29
30
  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(?, ?)
30
- 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")};}};var ot,eo=async()=>(ot||(ot=import('pg').catch(n=>{throw ot=void 0,new p("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),ot),to=["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())"],Z=n=>n==null?n:typeof n=="string"?JSON.parse(n):n,Dr=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;boundSocket;listeners=new Map;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new p("STORE_CONNECTION_FAILED","PostgresMessageStore: provide either pool or connectionString, not both");if(!t&&!r)throw new p("STORE_CONNECTION_FAILED","PostgresMessageStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}assertOpen(){if(this.closed)throw new p("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 eo(),r=t.Pool??t.default?.Pool;if(!r)throw new p("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{for(let t of to)await e.query(t);}catch(t){throw new p("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)]);}catch(a){throw new p("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?Z(s.data):void 0}catch(r){throw r instanceof p?r:new p("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=>Z(a.data))}catch(o){throw new p("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)]);}catch(i){throw new p("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?Z(s.data):void 0}catch(r){throw new p("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=>Z(i.data))}catch(s){throw new p("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)]);}catch(r){throw new p("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?Z(s.data):void 0}catch(r){throw new p("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=>Z(r.data))}catch(t){throw new p("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)]);}catch(s){throw new p("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?Z(s.data):void 0}catch(r){throw new p("STORE_READ_FAILED","failed to read presence",{cause:r})}}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let u=c[0]?.messages;if(Array.isArray(u))for(let l of u)this.saveMessage(l).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.getMessage(u.key).then(l=>{if(!l)return;let y={...l,...u.update};return this.saveMessage(y)}).catch(()=>{});},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveChat(u).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.getChat(u.id).then(l=>{let y={...l??{},...u};return this.saveChat(y)}).catch(()=>{});},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveContact(u).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let u of Object.keys(d.presences)){let l=d.presences[u];l&&this.savePresence(u,l).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[c,d]of this.listeners)e.ev.on(c,d);}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 p("STORE_WRITE_FAILED","failed to clear message tables",{cause:r})}finally{t?.release();}}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 no="zaileys",ro=300,so=1e3,Br=n=>`${n.id??""}|${n.fromMe?1:0}`,io=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Fr=class{namespace;externalClient;url;ownedClient;ready;closed=false;boundSocket;listeners=new Map;constructor(e){if(e.client&&e.url)throw new p("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new p("STORE_CONNECTION_FAILED","RedisMessageStore requires either client or url");this.namespace=e.namespace??no,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,Di.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,Di.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=await this.runRead(()=>r.zRangeByScore(this.msgIndexKey(e),"-inf",i,{LIMIT:{offset:0,count:s+1024}}));if(o.length===0)return [];let c=[...o].reverse().slice(0,s),d=await this.runRead(()=>r.hmGet(this.msgDataKey(e),c)),u=[];for(let l of d)l!=null&&u.push(JSON.parse(l,Di.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,Di.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,Di.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 c of o)c!=null&&a.push(JSON.parse(c,Di.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,Di.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,Di.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,Di.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,Di.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,Di.BufferJSON.replacer),{EX:ro}));}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,Di.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 c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).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(),t=`${this.namespace}:*`,r=0;do{let s=await this.runRead(()=>e.scan(r,{MATCH:t,COUNT:so}));r=Number(s.cursor),s.keys.length>0&&await this.runWrite(()=>e.del(s.keys));}while(r!==0)}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;}}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 p("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 io(r)?new p("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new p("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 p("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new p("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new p("STORE_WRITE_FAILED","redis write failed",{cause:t})}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","RedisMessageStore is closed")}};var jr="msg:",at="chat:",ct="contact:",Bt="presence:",Ft="job:",oo=n=>`${n.id??""}|${n.fromMe?1:0}`,Wt=n=>`${jr}${n.remoteJid??""}:${oo(n)}`,xe=n=>JSON.stringify(n,Di.BufferJSON.replacer),q=n=>JSON.parse(n,Di.BufferJSON.reviver),Wr=class{kv;closed=false;boundSocket;listeners=new Map;constructor(e){this.kv=new re(e);}async saveMessage(e){this.assertOpen(),await this.kv.set([{key:Wt(e.key),value:xe(e),sortKey:Number(e.messageTimestamp??0)}]);}async getMessage(e){this.assertOpen();let r=(await this.kv.get([Wt(e)])).get(Wt(e));return r===void 0?void 0:q(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(`${jr}${e}:`,r)).map(i=>q(i.value))}async saveChat(e){this.assertOpen();let t=e.id;t&&await this.kv.set([{key:`${at}${t}`,value:xe(e)}]);}async getChat(e){this.assertOpen();let r=(await this.kv.get([`${at}${e}`])).get(`${at}${e}`);return r===void 0?void 0:q(r)}async listChats(e){this.assertOpen();let t=await this.kv.list(at),r=[];for(let s of t){let i=q(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:`${ct}${e.id}`,value:xe(e)}]);}async getContact(e){this.assertOpen();let r=(await this.kv.get([`${ct}${e}`])).get(`${ct}${e}`);return r===void 0?void 0:q(r)}async listContacts(){return this.assertOpen(),(await this.kv.list(ct)).map(t=>q(t.value))}async savePresence(e,t){this.assertOpen(),await this.kv.set([{key:`${Bt}${e}`,value:xe(t)}]);}async getPresence(e){this.assertOpen();let r=(await this.kv.get([`${Bt}${e}`])).get(`${Bt}${e}`);return r===void 0?void 0:q(r)}async saveScheduledJob(e){this.assertOpen(),await this.kv.set([{key:`${Ft}${e.id}`,value:xe(e),sortKey:e.fireAt}]);}async listScheduledJobs(){return this.assertOpen(),(await this.kv.list(Ft)).map(t=>q(t.value))}async deleteScheduledJob(e){this.assertOpen(),await this.kv.del([`${Ft}${e}`]);}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 c of a)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).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(),await this.kv.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);this.listeners.clear(),this.boundSocket=void 0,this.kv.close();}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","ConvexMessageStore is closed")}};var ao=(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};exports.AudioProcessor=$;exports.BufferConverter=S;exports.Client=Cr;exports.CommandRegistry=me;exports.CommunityModule=pe;exports.ConvexAuthStore=Lr;exports.ConvexMessageStore=Wr;exports.DocumentProcessor=Be;exports.EditBuilder=ce;exports.FFMPEG_CONSTANTS=w;exports.FFmpegProcessor=J;exports.FileAuthStore=$e;exports.FileManager=W;exports.GroupModule=de;exports.ImageProcessor=x;exports.Media=V;exports.MemoryAuthStore=Pr;exports.MemoryMessageStore=Ve;exports.MessageBuilder=j;exports.MimeValidator=C;exports.NewsletterModule=ue;exports.PostgresAuthStore=xr;exports.PostgresMessageStore=Dr;exports.PresenceModule=he;exports.PrivacyModule=le;exports.RateLimiter=fe;exports.RedisAuthStore=Rr;exports.RedisMessageStore=Fr;exports.SELF_ONLY_PROTOCOL_TYPES=ol;exports.Scheduler=ye;exports.SqliteAuthStore=Or;exports.SqliteMessageStore=_r;exports.StickerProcessor=De;exports.TaskQueue=ge;exports.TypedEventEmitter=Ze;exports.VideoProcessor=N;exports.ZaileysAutomationError=b;exports.ZaileysBuilderError=m;exports.ZaileysCommandError=M;exports.ZaileysDomainError=E;exports.ZaileysStoreError=p;exports.adoptLogger=xt;exports.attachCommandDispatcher=kt;exports.buildMessageContext=_t;exports.chunk=ao;exports.createConnectionStateMachine=Bn;exports.createLogger=Qs;exports.createPairingFlow=_n;exports.createReconnectStrategy=Dn;exports.deleteMessage=Mt;exports.detectFileType=P;exports.dropSpoofedSelfOnly=Wn;exports.ffmpegTransform=_;exports.forwardMessage=Ct;exports.generateId=Le;exports.initializeFFmpeg=gt;exports.isFatalDisconnect=ve;exports.isJid=Ke;exports.makeCacheableAuthStore=On;exports.mapDisconnectReason=Rn;exports.normalizePhoneNumber=$s;exports.parseCommand=bt;exports.printQrToTerminal=Nn;exports.reactToMessage=Et;exports.renderQrInTerminal=Hs;exports.resolveUsername=Pt;exports.runBroadcast=It;exports.runMiddleware=Tt;exports.shouldClearAuth=Ln;exports.shouldReconnect=Hd;exports.signalKeyStoreFromAuthStore=xn;exports.validateE164=Vs;
31
+ 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")};}};var lt,go=async()=>(lt||(lt=import('pg').catch(n=>{throw lt=void 0,new p("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),lt),ho=["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())"],Q=n=>n==null?n:typeof n=="string"?JSON.parse(n):n,jr=class{externalPool;connectionString;poolMax;ownedPool;resolvedPool;readyPromise;boundSocket;listeners=new Map;closed=false;constructor(e){let t=e.pool!==void 0,r=e.connectionString!==void 0;if(t&&r)throw new p("STORE_CONNECTION_FAILED","PostgresMessageStore: provide either pool or connectionString, not both");if(!t&&!r)throw new p("STORE_CONNECTION_FAILED","PostgresMessageStore: pool or connectionString is required");this.externalPool=e.pool,this.connectionString=e.connectionString,this.poolMax=e.max;}assertOpen(){if(this.closed)throw new p("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 go(),r=t.Pool??t.default?.Pool;if(!r)throw new p("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{for(let t of ho)await e.query(t);}catch(t){throw new p("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)]);}catch(a){throw new p("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?Q(s.data):void 0}catch(r){throw r instanceof p?r:new p("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=>Q(a.data))}catch(o){throw new p("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)]);}catch(i){throw new p("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?Q(s.data):void 0}catch(r){throw new p("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=>Q(i.data))}catch(s){throw new p("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)]);}catch(r){throw new p("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?Q(s.data):void 0}catch(r){throw new p("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=>Q(r.data))}catch(t){throw new p("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)]);}catch(s){throw new p("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?Q(s.data):void 0}catch(r){throw new p("STORE_READ_FAILED","failed to read presence",{cause:r})}}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let u=c[0]?.messages;if(Array.isArray(u))for(let l of u)this.saveMessage(l).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.getMessage(u.key).then(l=>{if(!l)return;let y={...l,...u.update};return this.saveMessage(y)}).catch(()=>{});},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveChat(u).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.getChat(u.id).then(l=>{let y={...l??{},...u};return this.saveChat(y)}).catch(()=>{});},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let u of d)this.saveContact(u).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let u of Object.keys(d.presences)){let l=d.presences[u];l&&this.savePresence(u,l).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[c,d]of this.listeners)e.ev.on(c,d);}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 p("STORE_WRITE_FAILED","failed to clear message tables",{cause:r})}finally{t?.release();}}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 yo="zaileys",wo=300,So=1e3,Kr=n=>`${n.id??""}|${n.fromMe?1:0}`,vo=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},qr=class{namespace;externalClient;url;ownedClient;ready;closed=false;boundSocket;listeners=new Map;constructor(e){if(e.client&&e.url)throw new p("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new p("STORE_CONNECTION_FAILED","RedisMessageStore requires either client or url");this.namespace=e.namespace??yo,this.externalClient=e.client,this.url=e.url;}async saveMessage(e){this.assertOpen();let t=await this.ensureReady(),r=e.key.remoteJid??"",s=Kr(e.key),i=Number(e.messageTimestamp??0),o=JSON.stringify(e,Yi.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),Kr(e)));if(s!=null)return JSON.parse(s,Yi.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=await this.runRead(()=>r.zRangeByScore(this.msgIndexKey(e),"-inf",i,{LIMIT:{offset:0,count:s+1024}}));if(o.length===0)return [];let c=[...o].reverse().slice(0,s),d=await this.runRead(()=>r.hmGet(this.msgDataKey(e),c)),u=[];for(let l of d)l!=null&&u.push(JSON.parse(l,Yi.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,Yi.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,Yi.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 c of o)c!=null&&a.push(JSON.parse(c,Yi.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,Yi.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,Yi.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,Yi.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,Yi.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,Yi.BufferJSON.replacer),{EX:wo}));}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,Yi.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 c=o[0]?.messages;if(Array.isArray(c))for(let d of c)this.saveMessage(d).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).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(),t=`${this.namespace}:*`,r=0;do{let s=await this.runRead(()=>e.scan(r,{MATCH:t,COUNT:So}));r=Number(s.cursor),s.keys.length>0&&await this.runWrite(()=>e.del(s.keys));}while(r!==0)}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;}}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 p("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 vo(r)?new p("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new p("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 p("STORE_CONNECTION_FAILED",`failed to connect to redis at ${this.url}`,{cause:r})}return this.ownedClient=t,t}async runRead(e){try{return await e()}catch(t){throw new p("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new p("STORE_WRITE_FAILED","redis write failed",{cause:t})}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","RedisMessageStore is closed")}};var Vr="msg:",ut="chat:",pt="contact:",jt="presence:",Kt="job:",Ao=n=>`${n.id??""}|${n.fromMe?1:0}`,qt=n=>`${Vr}${n.remoteJid??""}:${Ao(n)}`,Le=n=>JSON.stringify(n,Yi.BufferJSON.replacer),$=n=>JSON.parse(n,Yi.BufferJSON.reviver),Jr=class{kv;closed=false;boundSocket;listeners=new Map;constructor(e){this.kv=new ie(e);}async saveMessage(e){this.assertOpen(),await this.kv.set([{key:qt(e.key),value:Le(e),sortKey:Number(e.messageTimestamp??0)}]);}async getMessage(e){this.assertOpen();let r=(await this.kv.get([qt(e)])).get(qt(e));return r===void 0?void 0:$(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(`${Vr}${e}:`,r)).map(i=>$(i.value))}async saveChat(e){this.assertOpen();let t=e.id;t&&await this.kv.set([{key:`${ut}${t}`,value:Le(e)}]);}async getChat(e){this.assertOpen();let r=(await this.kv.get([`${ut}${e}`])).get(`${ut}${e}`);return r===void 0?void 0:$(r)}async listChats(e){this.assertOpen();let t=await this.kv.list(ut),r=[];for(let s of t){let i=$(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:`${pt}${e.id}`,value:Le(e)}]);}async getContact(e){this.assertOpen();let r=(await this.kv.get([`${pt}${e}`])).get(`${pt}${e}`);return r===void 0?void 0:$(r)}async listContacts(){return this.assertOpen(),(await this.kv.list(pt)).map(t=>$(t.value))}async savePresence(e,t){this.assertOpen(),await this.kv.set([{key:`${jt}${e}`,value:Le(t)}]);}async getPresence(e){this.assertOpen();let r=(await this.kv.get([`${jt}${e}`])).get(`${jt}${e}`);return r===void 0?void 0:$(r)}async saveScheduledJob(e){this.assertOpen(),await this.kv.set([{key:`${Kt}${e.id}`,value:Le(e),sortKey:e.fireAt}]);}async listScheduledJobs(){return this.assertOpen(),(await this.kv.list(Kt)).map(t=>$(t.value))}async deleteScheduledJob(e){this.assertOpen(),await this.kv.del([`${Kt}${e}`]);}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 c of a)this.saveMessage(c).catch(()=>{});},r=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveChat(c).catch(()=>{});},s=(...o)=>{let a=o[0];if(Array.isArray(a))for(let c of a)this.saveContact(c).catch(()=>{});},i=(...o)=>{let a=o[0];if(a?.presences)for(let c of Object.keys(a.presences)){let d=a.presences[c];d&&this.savePresence(c,d).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(),await this.kv.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);this.listeners.clear(),this.boundSocket=void 0,this.kv.close();}}assertOpen(){if(this.closed)throw new p("STORE_CLOSED","ConvexMessageStore is closed")}};var Mo=(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};exports.AudioProcessor=G;exports.BufferConverter=v;exports.Client=Ir;exports.CommandRegistry=ge;exports.CommunityModule=fe;exports.ConvexAuthStore=Fr;exports.ConvexMessageStore=Jr;exports.DocumentProcessor=We;exports.EditBuilder=le;exports.FFMPEG_CONSTANTS=S;exports.FFmpegProcessor=V;exports.FileAuthStore=Ge;exports.FileManager=j;exports.GroupModule=ue;exports.ImageProcessor=x;exports.Media=H;exports.MemoryAuthStore=Or;exports.MemoryMessageStore=He;exports.MessageBuilder=q;exports.MimeValidator=b;exports.NewsletterModule=me;exports.PostgresAuthStore=Dr;exports.PostgresMessageStore=jr;exports.PresenceModule=we;exports.PrivacyModule=pe;exports.RateLimiter=he;exports.RedisAuthStore=Br;exports.RedisMessageStore=qr;exports.SELF_ONLY_PROTOCOL_TYPES=vl;exports.Scheduler=Se;exports.SqliteAuthStore=_r;exports.SqliteMessageStore=Wr;exports.StickerProcessor=Fe;exports.TaskQueue=ye;exports.TypedEventEmitter=tt;exports.VideoProcessor=D;exports.ZaileysAutomationError=T;exports.ZaileysBuilderError=m;exports.ZaileysCommandError=E;exports.ZaileysDomainError=C;exports.ZaileysStoreError=p;exports.adoptLogger=_t;exports.attachCommandDispatcher=xt;exports.buildMessageContext=Ft;exports.chunk=Mo;exports.createConnectionStateMachine=jn;exports.createLogger=si;exports.createPairingFlow=Fn;exports.createReconnectStrategy=Un;exports.deleteMessage=Pt;exports.detectFileType=P;exports.dropSpoofedSelfOnly=qn;exports.ffmpegTransform=_;exports.forwardMessage=kt;exports.generateId=_e;exports.initializeFFmpeg=St;exports.isFatalDisconnect=Me;exports.isJid=Je;exports.makeCacheableAuthStore=Nn;exports.mapDisconnectReason=Dn;exports.normalizePhoneNumber=Ys;exports.parseCommand=Ot;exports.printQrToTerminal=Wn;exports.reactToMessage=Tt;exports.renderQrInTerminal=Qs;exports.resolveUsername=It;exports.runBroadcast=Lt;exports.runMiddleware=Rt;exports.shouldClearAuth=Bn;exports.shouldReconnect=cl;exports.signalKeyStoreFromAuthStore=_n;exports.validateE164=Zs;