zaileys 4.7.0 → 4.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -7,13 +7,13 @@
|
|
|
7
7
|
`)}:{type:"code",content:u.join(`
|
|
8
8
|
`)});continue}let d=e[i+1];if(o.includes("|")&&d!==void 0&&d.includes("|")&&mi.test(d)){s();let u=[qn(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(qn(e[i])),i++;t.push({type:"table",rows:u});continue}let l=Un.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let w=Un.exec(e[i]);if(!w)break;u.push(w[1]),i++;}t.push({type:"image",url:u.length===1?u[0]:u});continue}r.push(o),i++;}return s(),t};var $n=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new g("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var Gn=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new g("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await I(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var Vn=(n,e)=>{let t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))throw new g("INVALID_OPTIONS",`event() ${e} must be a valid Date or epoch ms`);return new Date(Math.floor(t.getTime()/1e3)*1e3)},Hn=n=>{if(n==null||typeof n.name!="string"||n.name.trim().length===0)throw new g("INVALID_OPTIONS","event() requires a non-empty name");return {event:{name:n.name,startDate:Vn(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:Vn(n.endAt,"endAt")}:{},...n.call!==void 0?{call:n.call}:{},...n.canceled!==void 0?{isCancelled:n.canceled}:{},...n.location!==void 0?{location:{degreesLatitude:n.location.latitude,degreesLongitude:n.location.longitude,...n.location.name!==void 0?{name:n.location.name}:{},...n.location.address!==void 0?{address:n.location.address}:{}}}:{}}}};var zn=n=>{if(n==null||typeof n.jid!="string"||!n.jid.endsWith("@g.us"))throw new g("INVALID_OPTIONS","groupInvite() requires a group jid ending in @g.us");if(typeof n.code!="string"||n.code.trim().length===0)throw new g("INVALID_OPTIONS","groupInvite() requires an invite code");let e={inviteCode:n.code,inviteExpiration:n.expiresAt??Math.floor(Date.now()/1e3)+3*86400,groupJid:n.jid,groupName:n.subject??"",caption:n.caption??""};return n.thumbnail!==void 0&&(e.jpegThumbnail=n.thumbnail),{[N]:{groupInviteMessage:e}}};var Yn=10,Zn=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new g("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new g("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 g("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 g("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof d.title!="string"||d.title.trim().length===0)throw new g("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(d.id))throw new g("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>Yn)throw new g("INVALID_OPTIONS",`list() accepts at most ${Yn} 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}),{[N]:{interactiveMessage:i}}};var Xn=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new g("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 g("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 Qn=2,er=12,tr=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new g("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Qn)throw new g("INVALID_OPTIONS",`poll() requires a minimum of ${Qn} options`);if(e.length>er)throw new g("INVALID_OPTIONS",`poll() accepts a maximum of ${er} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new g("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new g("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var nr=async n=>{if(n==null||typeof n.title!="string"||n.title.trim().length===0)throw new g("INVALID_OPTIONS","product() requires a non-empty title");if(typeof n.businessOwnerId!="string"||n.businessOwnerId.length===0)throw new g("INVALID_OPTIONS","product() requires businessOwnerId");let{buffer:e}=await I(n.image),t={productImage:e,title:n.title};n.productId!==void 0&&(t.productId=n.productId),n.description!==void 0&&(t.description=n.description),n.currency!==void 0&&(t.currencyCode=n.currency),n.price!==void 0&&(t.priceAmount1000=Math.round(n.price*1e3)),n.retailerId!==void 0&&(t.retailerId=n.retailerId),n.url!==void 0&&(t.url=n.url);let r={product:t,businessOwnerJid:n.businessOwnerId};return n.body!==void 0&&(r.body=n.body),n.footer!==void 0&&(r.footer=n.footer),r};var rr=async(n,e)=>{let{buffer:t}=await I(n),r;try{r=await new ee(t).sticker.create();}catch(i){throw new g("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var sr=3,ir=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new g("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new g("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>sr)throw new g("INVALID_OPTIONS",`template() accepts at most ${sr} 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),it(n.buttons,t)};var ct=n=>{if(typeof n!="string"||n.trim().length===0)throw new g("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var or=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var Mi=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],V=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,or(t,r,s))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=Wn(Jn(e),t):this.internal.content=ct(e),this}image(e,t){return this.internal.pendingContent=le(e,t),this}videoNote(e,t){return this.internal.pendingContent=X(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=X(e,t),this}audio(e,t){return this.internal.pendingContent=Dn(e,t),this}document(e,t){return this.internal.pendingContent=Gn(e,t),this}sticker(e,t){return this.internal.pendingContent=rr(e,t),this}buttons(e,t){return this.internal.content=it(e,t),this}carousel(e,t){return this.internal.content=Fn(e,t),this}list(e){return this.internal.content=Zn(e),this}poll(e,t,r){return this.internal.content=tr(e,t,r),this}location(e,t,r){return this.internal.content=Xn(e,t,r),this}contact(e){return this.internal.content=$n(e),this}template(e){return this.internal.content=ir(e),this}event(e){return this.internal.content=Hn(e),this}groupInvite(e){return this.internal.content=zn(e),this}product(e){return this.internal.pendingContent=nr(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new g("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 g("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new g("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 g("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),xn(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 g("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[N];if(i!==void 0){let d=s[$t],l=s[Vt];return this.sendRelay(i,d,l)}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 g("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new g("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await I(t.src),s=await aa.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 g("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let u=e.interactiveMessage?.header;t!==void 0&&u&&await this.uploadHeaderMedia(u,t);let w=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&w)for(let S of r){let v=w[S.index]?.header;v&&await this.uploadHeaderMedia(v,S);}}catch(u){throw new g("SEND_FAILED","interactive media upload failed",{cause:u})}let o={userJid:this.socket.user?.id??""},a=this.internal.quoted;a!==void 0&&a.message!=null&&(o.quoted=a);let c=aa.generateWAMessageFromContent(this.internal.recipient,e,o);if(typeof c.key?.id!="string")throw new g("SEND_FAILED","failed to generate relay message key");let l="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:c.key.id,additionalNodes:Mi}:{messageId:c.key.id};try{await s(this.internal.recipient,c.message,l);}catch(u){throw new g("SEND_FAILED","socket relayMessage rejected",{cause:u})}return this.internal.recordSent?.(c),c.key}};var Ae=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=ct(e),this}image(e,t){return this.pendingContent=le(e,t),this}video(e,t){return this.pendingContent=X(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 g("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new g("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 g("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new g("SEND_FAILED","socket returned no message key");return r.key}};var zt=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new g("INVALID_OPTIONS","message key is missing remoteJid");return e},Yt=n=>{if(!n?.key)throw new g("SEND_FAILED","socket returned no message key");return n.key},Zt=async(n,e,t={})=>{let r=zt(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new g("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},Xt=async(n,e,t)=>{let r=zt(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return Yt(s)},Qt=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new g("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return Yt(i)},dt=async(n,e,t,r={})=>{let s=zt(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return Yt(o)};var Si=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Pe=n=>Si.test(n),en=async(n,e,t,r=Ai)=>{if(Pe(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 g("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);}},Ai=new Map;var k=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 Ce=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new k("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var Ee=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("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 be=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new k("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var ke=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var Te=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Pi=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new k("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Oe=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){await this.requireSocket().chatModify({markRead:true,lastMessages:await this.last(e)},e);}async markUnread(e){await this.requireSocket().chatModify({markRead:false,lastMessages:await this.last(e)},e);}async star(e,t=true){let r=Pi(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var Ie=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var xe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var x=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 Ci=n=>{let e=n[0];return e==="{"||e==="["},Ei=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},bi=n=>n===" "||n===" "||n===`
|
|
10
|
+
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),it(n.buttons,t)};var ct=n=>{if(typeof n!="string"||n.trim().length===0)throw new g("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var or=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var Mi=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],V=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,or(t,r,s))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=Wn(Jn(e),t):this.internal.content=ct(e),this}image(e,t){return this.internal.pendingContent=le(e,t),this}videoNote(e,t){return this.internal.pendingContent=X(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=X(e,t),this}audio(e,t){return this.internal.pendingContent=Dn(e,t),this}document(e,t){return this.internal.pendingContent=Gn(e,t),this}sticker(e,t){return this.internal.pendingContent=rr(e,t),this}buttons(e,t){return this.internal.content=it(e,t),this}carousel(e,t){return this.internal.content=Fn(e,t),this}list(e){return this.internal.content=Zn(e),this}poll(e,t,r){return this.internal.content=tr(e,t,r),this}location(e,t,r){return this.internal.content=Xn(e,t,r),this}contact(e){return this.internal.content=$n(e),this}template(e){return this.internal.content=ir(e),this}event(e){return this.internal.content=Hn(e),this}groupInvite(e){return this.internal.content=zn(e),this}product(e){return this.internal.pendingContent=nr(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new g("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 g("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new g("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 g("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),xn(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 g("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[N];if(i!==void 0){let d=s[$t],l=s[Vt];return this.sendRelay(i,d,l)}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 g("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new g("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await I(t.src),s=await aa.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 g("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let u=e.interactiveMessage?.header;t!==void 0&&u&&await this.uploadHeaderMedia(u,t);let w=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&w)for(let S of r){let v=w[S.index]?.header;v&&await this.uploadHeaderMedia(v,S);}}catch(u){throw new g("SEND_FAILED","interactive media upload failed",{cause:u})}let o={userJid:this.socket.user?.id??""},a=this.internal.quoted;a!==void 0&&a.message!=null&&(o.quoted=a);let c=aa.generateWAMessageFromContent(this.internal.recipient,e,o);if(typeof c.key?.id!="string")throw new g("SEND_FAILED","failed to generate relay message key");let l="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:c.key.id,additionalNodes:Mi}:{messageId:c.key.id};try{await s(this.internal.recipient,c.message,l);}catch(u){throw new g("SEND_FAILED","socket relayMessage rejected",{cause:u})}return this.internal.recordSent?.(c),c.key}};var Ae=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=ct(e),this}image(e,t){return this.pendingContent=le(e,t),this}video(e,t){return this.pendingContent=X(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 g("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new g("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 g("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new g("SEND_FAILED","socket returned no message key");return r.key}};var zt=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new g("INVALID_OPTIONS","message key is missing remoteJid");return e},Yt=n=>{if(!n?.key)throw new g("SEND_FAILED","socket returned no message key");return n.key},Zt=async(n,e,t={})=>{let r=zt(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new g("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},Xt=async(n,e,t)=>{let r=zt(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return Yt(s)},Qt=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new g("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return Yt(i)},dt=async(n,e,t,r={})=>{let s=zt(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return Yt(o)};var Si=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Pe=n=>Si.test(n),en=async(n,e,t,r=Ai)=>{if(Pe(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 g("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);}},Ai=new Map;var k=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 Ce=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new k("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var Ee=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("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 be=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new k("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var ke=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var Te=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Pi=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new k("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Oe=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:true,lastMessages:t},e);}async markUnread(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:false,lastMessages:t},e);}async star(e,t=true){let r=Pi(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var Ie=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var xe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var x=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 Ci=n=>{let e=n[0];return e==="{"||e==="["},Ei=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},bi=n=>n===" "||n===" "||n===`
|
|
11
11
|
`||n==="\r",ki=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(bi(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Ti=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},Oi=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function tn(n,e){let t=Ti(n,e);if(t===null)return Oi(n);let r=n.slice(t.length),s=ki(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 l=d.indexOf("=");if(l!==-1){let w=d.slice(0,l),S=d.slice(l+1);i.flags[w]=S;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[d]=u,a+=1):i.flags[d]=true;continue}if(!o&&Ci(c)){let d=Ei(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var ar=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new x("INVALID_COMMAND_NAME","empty command segment in spec");return e},pe=n=>n.join(" "),Re=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new x("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>ar(a)),s=r[0],i=r.slice(1).map(a=>pe(a)),o={name:pe(s),aliases:i,parts:s,handler:t};for(let a of r){let c=pe(a);if(this.paths.has(c))throw new x("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(pe(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)}}}unregister(e){let t=e.split("|").map(o=>ar(o)),r=pe(t[0]),s=this.paths.get(r);if(s===void 0)return;for(let o of [s.parts,...s.aliases.map(a=>a.split(" "))])this.paths.delete(pe(o));let i=this.defs.indexOf(s);i>=0&&this.defs.splice(i,1),this.maxDepth=this.defs.reduce((o,a)=>Math.max(o,a.parts.length),1);}list(){return [...this.defs]}};async function nn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new x("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 x?c:new x("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function rn(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=tn(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(nn(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let l=d instanceof x?d:new x("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(l,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var cr=n=>n;var Le=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t){if(typeof e?.name!="string"||typeof e?.setup!="function"){this.logger?.warn({file:t},"plugin: invalid shape (need name + setup); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let r=[],s={client:this.host,logger:this.logger,pluginDir:We__default.default.dirname(t),command:(i,o)=>{this.host.command(i,o),r.push(()=>this.host.unregisterCommand(i));},use:i=>{this.host.use(i),r.push(()=>{this.host.unuse(i);});},on:(i,o)=>{let a=this.host.on(i,o);return r.push(a),a},once:(i,o)=>{let a=false,c=this.host.on(i,d=>{a||(a=true,c(),o(d));});return r.push(c),c}};try{let i=await e.setup(s);typeof i=="function"&&r.push(i);}catch(i){for(let o of [...r].reverse())try{await o();}catch{}this.logger?.error({err:i,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:r});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Li=/\.(ts|js|mjs|cjs)$/,Ni=/(\.d\.ts$|^_|[/\\]_)/;async function on(n,e,t){let r;try{r=await fs.promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=We__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await on(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function lr(n,e){try{let r=await import(url.pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"&&typeof s.setup=="function"?s:void 0}catch{return}}var Ne=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=We__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Li,this.ignore=e.options.ignore??Ni,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await on(this.dir,this.pattern,this.ignore);for(let t of e)await this.loadFile(t);this.watchEnabled&&this.startWatch();}async stop(){this.debounce&&clearTimeout(this.debounce),this.watcher?.close(),this.watcher=void 0,await this.flushChain,await this.registry.unloadAll(),this.fileToName.clear();}async loadFile(e){let t=await lr(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=fs.watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=We__default.default.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await fs.promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var O=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 Di=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ne=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new O("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new O("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new O("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??Di;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 _i={"group.create":6e4,"group.join":3e4,"group.participants":1e4,"group.update":3e3,"community.create":12e4,"community.join":3e4,"community.update":3e3,"newsletter.create":12e4,"newsletter.follow":2e3,"newsletter.update":3e3},Bi=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function an(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??Bi,i={..._i,...n.intervalsMs??{}},o=new Map,a=new Map,c=async(d,l)=>{let u=i[d]??0,w=o.get(d);if(w!==void 0&&u>0){let S=u-(r()-w);S>0&&await s(S);}return o.set(d,r()),l()};return {run(d,l){if(!t)return l();let w=(a.get(d)??Promise.resolve()).then(()=>c(d,l),()=>c(d,l));return a.set(d,w.then(()=>{},()=>{})),w}}}var Fi={maxRetries:0,backoffMs:()=>0},Wi=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),De=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??Fi,this.sleep=t.sleep??Wi;}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 ji=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function cn(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 ne({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},l=c?new De({concurrency:1,retry:c},d):void 0,u=n.length,w=0;for(let S of n){await a.acquire(S);let v=()=>e(t.sendTo(S)).then(()=>{});try{l?await l.add(v):await v(),s.sent.push(S),w+=1,r.onProgress?.(w,u,S,!0);}catch(C){s.failed.push({jid:S,error:ji(C)}),w+=1,r.onProgress?.(w,u,S,false);}}return s}var Ui=1e3,_e=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??Ui,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new Map;requireSocket(){let e=this.getSocket();if(!e)throw new O("NOT_CONNECTED","client not connected");return e}throttled(e,t){if(!this.throttleEnabled||this.minIntervalMs<=0)return false;let r=`${e}:${t??"global"}`,s=this.lastSent.get(r),i=this.now();return s!==void 0&&i-s<this.minIntervalMs?true:(this.lastSent.set(r,i),false)}async update(e,t){let r=this.requireSocket();if(!this.throttled(e,t))try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new O("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 Ki={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},Ji=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",Be=class{store;sendSnapshot;now;timer;logger;acquire;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??Ki,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new O("SCHEDULE_INVALID","scheduleAt requires a valid Date");let s=await this.evaluate(t),i=crypto.randomUUID(),o={id:i,fireAt:r,recipient:s.recipient,payload:s};return await this.persist(o),this.arm(o),{id:i,cancel:()=>{this.cancel(i);}}}async loadPending(){let e=this.store.listScheduledJobs;if(!e){for(let r of this.memory.values())this.timers.has(r.id)||this.arm(r);return}let t;try{t=await e.call(this.store);}catch(r){this.logger?.warn(r,"scheduler loadPending failed");return}for(let r of t)this.timers.has(r.id)||(this.memory.set(r.id,r),this.arm(r));}dispose(){for(let e of this.timers.values())this.timer.clear(e);this.timers.clear();}cancel(e){let t=this.timers.get(e);t!==void 0&&(this.timer.clear(t),this.timers.delete(e)),this.memory.delete(e),this.remove(e);}arm(e){let t=Math.max(0,e.fireAt-this.now()),r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),Ji(e.payload))try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed; retaining job for retry");return}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,c)=>{if(r+=1,r>1)throw new O("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=c?{recipient:o,content:a,options:c}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new O("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=V.create(s,"");try{await e(i);}catch(o){throw o instanceof O?o:new O("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new O("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function ur(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((c,d)=>Number(d.messageTimestamp??0)-Number(c.messageTimestamp??0));for(let c=0;c<a.length;c+=1){let d=a[c],l=Number(d.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&c>=e.maxPerChat;(u||w)&&(await n.deleteMessage(d.key),r+=1);}}return r}var Fe=class{store;options;logger;now;timer;running=false;warnedUnsupported=false;disabled=false;constructor(e){this.store=e.store,this.options=e.options,this.logger=e.logger,this.now=e.now??Date.now;}get active(){return this.options.maxAgeMs!==void 0||this.options.maxPerChat!==void 0}buildPruneOptions(){let e={};return this.options.maxAgeMs!==void 0&&(e.olderThan=Math.floor((this.now()-this.options.maxAgeMs)/1e3)),this.options.maxPerChat!==void 0&&(e.maxPerChat=this.options.maxPerChat),typeof this.options.chats=="function"&&(e.chatFilter=this.options.chats),e}async runOnce(){if(!this.active||this.disabled)return 0;let e=this.buildPruneOptions();return typeof this.store.pruneMessages=="function"?this.store.pruneMessages(e):typeof this.store.deleteMessage=="function"?ur(this.store,e):(this.disabled=true,this.warnedUnsupported||(this.warnedUnsupported=true,this.logger?.warn({code:"AUTO_DELETE_UNSUPPORTED"},"autoDelete: store implements neither pruneMessages nor deleteMessage; sweeper disabled")),0)}start(){if(!this.active||this.timer)return;let e=this.options.intervalMs??6e4;this.timer=setInterval(()=>{this.running||(this.running=true,this.runOnce().catch(t=>this.logger?.warn(t,"autoDelete sweep failed")).finally(()=>{this.running=false;}));},e),this.timer.unref?.();}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0);}};var $i={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Gi=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[$i[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},lt=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Gi(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")}},pr=(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 re="[zaileys]",Vi="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 gr(n){switch(n.kind){case "connecting":return `${re} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${re} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${re} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${re} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${re} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
|
|
12
12
|
${re} ${Vi}`:t}case "disconnect":return n.willReconnect?null:`${re} Disconnected (${n.reason}).`;default:return null}}var mr=false,Hi=["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:"],zi=n=>typeof n[0]=="string"&&Hi.some(e=>n[0].startsWith(e));function fr(){if(mr)return;mr=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{zi(r)||t(...r);};};n("info"),n("warn"),n("error");}var f=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 Zi="./.zaileys/auth",Xi=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),je=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",pt=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??Zi;}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.promises.readFile(i,"utf8");r[s]=JSON.parse(o,aa.BufferJSON.reviver);}catch(o){if(je(o))return;throw new f("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.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.promises.unlink(c).catch(d=>{if(!je(d))throw new f("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,aa.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.promises.unlink(s);}catch(i){if(!je(i))throw new f("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen(),await fs.promises.rm(this.basePath,{recursive:true,force:true});},close:async()=>{this.closed=true;}};creds={readCreds:async()=>{this.assertOpen();try{let e=await fs.promises.readFile(this.credsPath(),"utf8");return JSON.parse(e,aa.BufferJSON.reviver)}catch(e){if(je(e))return;throw new f("STORE_READ_FAILED","failed to read creds.json",{cause:e})}},writeCreds:async e=>{this.assertOpen(),await fs.promises.mkdir(this.basePath,{recursive:true}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,aa.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs.promises.unlink(this.credsPath());}catch(e){if(!je(e))throw new f("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),`${Xi(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.promises.writeFile(r,t,"utf8"),await fs.promises.rename(r,e);}catch(s){throw await fs.promises.unlink(r).catch(()=>{}),new f("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new f("STORE_CLOSED","FileAuthStore is closed")}};function hr(n,e){let t=n.signal,s=aa.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 l of a)d[l]=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 yr(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);},clear:async()=>{await n.clear();}}}var eo=429;function wr(n){if(n===eo)return "rate-limited";switch(n){case aa.DisconnectReason.loggedOut:return "logged-out";case aa.DisconnectReason.forbidden:return "forbidden";case aa.DisconnectReason.connectionLost:return "connection-lost";case aa.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case aa.DisconnectReason.connectionClosed:return "connection-closed";case aa.DisconnectReason.connectionReplaced:return "connection-replaced";case aa.DisconnectReason.badSession:return "bad-session";case aa.DisconnectReason.unavailableService:return "unavailable-service";case aa.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Ue(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function mt(n){return n==="rate-limited"}function vr(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function rp(n){return !Ue(n)}var gt={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},to=3e5;function Mr(n={}){let e=n.enabled??gt.enabled,t=n.maxQrAttempts??gt.maxQrAttempts,r=n.maxPairingAttempts??gt.maxPairingAttempts,s=n.pairingCooldownMs??gt.pairingCooldownMs,i=0,o=0,a=0,c=w=>w<=0?0:Math.min(s*w,to);return {evaluate:(w,S)=>{if(!e)return {allowed:true,waitMs:0,attempts:w==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(w==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let v=c(o),C=S-a;return o>0&&C<v?{allowed:false,reason:"cooldown",waitMs:v-C,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(w,S)=>{w==="pairing"?(o+=1,a=S):i+=1;},reset:()=>{i=0,o=0,a=0;},get enabled(){return e},get qrAttempts(){return i},get pairingAttempts(){return o}}}var no=/[\s\-()+]/g;function ro(n){return typeof n!="string"?"":n.replace(no,"")}function so(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=ro(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 Sr(n){let e=so(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 oo(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{io__default.default.generate(n,{small:true},t=>e(t));})}async function Ar(n,e=t=>{process.stdout.write(t);}){let t=await oo(n);e(t+`
|
|
13
13
|
`);}var me={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Pr(n,e){let t=n?.enabled??me.enabled,r=n?.maxAttempts??me.maxAttempts,s=n?.initialDelayMs??me.initialDelayMs,i=n?.maxDelayMs??me.maxDelayMs,o=n?.jitterFactor??me.jitterFactor,a=n?.rateLimitedDelayMs??me.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Ue(w))return null;let S=d+1;if(S>r)return null;if(d=S,mt(w))return {attempt:S,delayMs:a};let v=Math.pow(2,S-1),C=Math.min(i,s*v),y=1+(c()*2-1)*o,p=C*y,m=Math.min(i,Math.max(0,p));return {attempt:S,delayMs:Math.round(m)}},reset:()=>{d=0;},get attempts(){return d}}}var ao={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 Cr(n="idle"){let e=n,t=new Set,r=s=>ao[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 ft=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,ht=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=ft(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(ft(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 l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(ft(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=ft(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new f("STORE_CLOSED","MemoryMessageStore is closed")}};var lo=["silent","fatal","error","warn","info","debug","trace"];function uo(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":lo.includes(e)?e:"silent"}function po(n={}){let e=uo(n.level),t=co__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Er=["debug","info","warn","error","fatal"];function mo(n){if(n===null||typeof n!="object")return false;for(let e of Er)if(typeof n[e]!="function")return false;return true}function qe(){}function go(n){let e={debug:qe,info:qe,warn:qe,error:qe,fatal:qe};for(let t of Er){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function dn(n,e){return n===void 0?e??po():mo(n)?n:go(n)}var hp=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),br=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 fo=new Set(["offer","ringing"]),ho=new Set(["timeout","reject","accept","terminate"]),kr=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},Tr=n=>typeof n.id!="string"||n.id.length===0||!fo.has(n.status)?null:{kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:kr(n.date),status:n.status},Or=n=>typeof n.id!="string"||n.id.length===0||!ho.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:kr(n.date),status:n.status};var _=n=>typeof n=="string"&&n.length>0,yo=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},Ir=(n,e,t)=>n.filter(r=>_(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return _(i)&&(s.participantAlt=i),_(e)&&(s.authorPn=e),_(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),xr=n=>_(n?.id)?{groupId:n.id,update:yo(n),timestamp:Date.now()}:null,Rr=n=>{if(!_(n?.groupId)||!_(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 _(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},wo=new Set(["add","invite","invite-link"]),vo=new Set(["remove","leave"]),Lr=n=>{if(!_(n?.id)||!wo.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Ir(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 _(n.author)&&(t.by=n.author),t},Nr=n=>{if(!_(n?.id)||!vo.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Ir(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 _(n.author)&&(t.by=n.author),t};var ge=n=>typeof n!="string"||n.length===0?null:aa.jidNormalizedUser(n),H=n=>typeof n=="string"&&n.length>0?n:void 0,Ao=["@s.whatsapp.net","@c.us"],yt=n=>n.endsWith("@lid"),Dr=n=>Ao.some(e=>n.endsWith(e)),q=(n,e)=>{if(!n)return null;let t=H(n.participant)??n.remoteJid,r=ge(t);if(r===null)return null;let s=H(n.participantAlt)??H(n.remoteJidAlt),i=s!=null?ge(s):null,o=H(n.participantUsername)??H(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(yt),l=c.find(Dr);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=H(e);return u!==void 0&&(a.pushName=u),a},_r=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=H(n.participant),r=H(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=q(s);return o&&(i.sender=o),i},Ke=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 fe=n=>aa.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 Po=["quick_reply","cta_url","cta_call","button_click"],Co=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,Fr=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return q(n.key,e)},Wr=n=>he(n.messageTimestamp)??0,jr=(n,e)=>{if(!J(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}},wt=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},Ur=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return ln(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return ln(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Po.includes(i.name)){let o=jr(i.paramsJson,e.logger);if(!o)return null;let a=wt(o,["id","button_id"]);return a===void 0?null:ln(n,a,wt(o,["display_text"])??null)}return null},ln=(n,e,t)=>{let r=Fr(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Wr(n)};return J(t)&&(s.buttonText=t),s},qr=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return Br(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Co.includes(i.name)){let o=jr(i.paramsJson,e.logger);if(!o)return null;let a=wt(o,["row_id","id"]);return a===void 0?null:Br(n,a,wt(o,["title"])??null)}return null},Br=(n,e,t)=>{let r=Fr(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Wr(n)};return J(t)&&(s.title=t),s};var Eo=new Set(["available","unavailable","composing","recording","paused"]),bo=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,Kr=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},un=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:bo(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},Jr=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"||!Eo.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Je=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 Gr=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},$r=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},Vr=n=>($r(n).toString(16).padStart(8,"0")+$r(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),Hr=n=>Vr(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),zr=(n,e)=>Vr(`${n??""}|${e}`),Yr=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},Zr=n=>{let e=aa.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"},To=n=>n.trim().endsWith("?"),Oo=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Io=(n,e)=>{if(e.length===0)return false;let t;try{t=aa.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return aa.jidNormalizedUser(r)===t}catch{return r===n}})},xo=(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)}},Ro=0,Lo=14,No=1,Do=2,vt=n=>n!=null&&typeof n=="object"?n:null,_o=n=>{let e=vt(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false};let t=vt(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof vt(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Lo,isDeleted:r===Ro,isPinned:s===No,isUnPinned:s===Do,isBot:vt(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null}},pn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&fe(e),r=_o(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?aa.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(aa.jidNormalizedUser(e)):i,a={uniqueId:Hr(n.key),staticId:zr(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(aa.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderDevice:Zr(n.sender.deviceJid??n.sender.jid),timestamp:Yr(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Gr(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:To(n.text),isPrefix:Oo(n.text,n.prefixes),isTagMe:Io(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isStory:e==="status@broadcast",roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:xo(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var St={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Qr=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},h=n=>n!=null&&typeof n=="object"?n:null,M=n=>typeof n=="string"&&n.length>0?n:null,z=(...n)=>{for(let e of n){let t=M(e);if(t!=null)return t}return null},Bo=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage"],He=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Bo){let i=h(h(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e},es=n=>{let e=h(n.message);if(e==null)return n;let t=He(e);return t===e?n:{...n,message:t}},Fo=n=>{let t=h(h(h(n.botForwardedMessage)?.message)?.richResponseMessage)??h(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=M(h(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
|
|
14
14
|
`).trim();return i.length>0?i:null},Wo=n=>{let e=h(n.templateMessage),t=h(e?.hydratedTemplate)??h(e?.hydratedFourRowTemplate);return M(t?.hydratedContentText)},jo=n=>z(h(n.pollCreationMessage)?.name,h(n.pollCreationMessageV2)?.name,h(n.pollCreationMessageV3)?.name),Uo=n=>{let e=h(n.locationMessage)??h(n.liveLocationMessage);if(e==null)return null;let t=z(e.name,e.address);if(t!=null){let i=M(e.name),o=M(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},qo=n=>{let e=M(h(n.contactMessage)?.displayName);if(e!=null)return e;let t=h(n.contactsArrayMessage),r=M(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>M(h(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},ts=n=>z(n.conversation,h(n.extendedTextMessage)?.text,Fo(n),M(h(h(n.interactiveMessage)?.body)?.text),h(n.buttonsMessage)?.contentText,h(n.listMessage)?.description,Wo(n),jo(n),Uo(n),qo(n)),Ko=n=>z(h(n.buttonsResponseMessage)?.selectedDisplayText,h(n.buttonsResponseMessage)?.selectedButtonId,h(n.templateButtonReplyMessage)?.selectedDisplayText,h(n.templateButtonReplyMessage)?.selectedId,h(n.listResponseMessage)?.title,h(h(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,h(h(n.interactiveResponseMessage)?.body)?.text),Jo=n=>z(h(n.imageMessage)?.caption,h(n.videoMessage)?.caption,h(n.documentMessage)?.caption,h(n.documentMessage)?.fileName),T=n=>{if(typeof n=="number")return n;let e=he(n);return typeof e=="number"?e:null},$o=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],ns=n=>{let e=h(n.pollCreationMessage)??h(n.pollCreationMessageV2)??h(n.pollCreationMessageV3);if(e!=null){let p=Array.isArray(e.options)?e.options:[];return {type:"poll",name:M(e.name),options:p.map(m=>M(h(m)?.optionName)).filter(m=>m!=null),selectableCount:T(e.selectableOptionsCount)??0}}let t=h(n.contactMessage);if(t!=null)return {type:"contact",displayName:M(t.displayName),vcard:M(t.vcard),contacts:[{displayName:M(t.displayName),vcard:M(t.vcard)}]};let r=h(n.contactsArrayMessage);if(r!=null){let p=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:M(r.displayName),vcard:null,contacts:p.map(m=>({displayName:M(h(m)?.displayName),vcard:M(h(m)?.vcard)}))}}let s=h(n.locationMessage);if(s!=null)return {type:"location",latitude:T(s.degreesLatitude),longitude:T(s.degreesLongitude),name:M(s.name),address:M(s.address),accuracy:T(s.accuracyInMeters),speed:T(s.speedInMps),caption:M(s.comment)};let i=h(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:T(i.degreesLatitude),longitude:T(i.degreesLongitude),name:null,address:null,accuracy:T(i.accuracyInMeters),speed:T(i.speedInMps),caption:M(i.caption)};let o=h(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:T(o.expectedImageCount),expectedVideoCount:T(o.expectedVideoCount)};let a=h(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:M(a.groupJid),groupName:M(a.groupName),inviteCode:M(a.inviteCode),caption:M(a.caption),expiresAt:T(a.inviteExpiration)};let c=h(h(n.productMessage)?.product);if(h(n.productMessage)!=null){let p=M(h(n.productMessage)?.businessOwnerJid),m=T(c?.priceAmount1000);return {type:"product",productId:M(c?.productId),title:M(c?.title),description:M(c?.description),price:m!=null?m/1e3:null,currency:M(c?.currencyCode),retailerId:M(c?.retailerId),url:M(c?.url),businessOwnerId:p}}let d=h(n.orderMessage);if(d!=null){let p=T(d.totalAmount1000),m={1:"inquiry",2:"accepted",3:"declined"},A=d.status;return {type:"order",orderId:M(d.orderId),title:M(d.orderTitle),itemCount:T(d.itemCount),total:p!=null?p/1e3:null,currency:M(d.totalCurrencyCode),status:typeof A=="number"?m[A]??null:M(A),message:M(d.message)}}let l=h(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||h(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||h(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let p=h(l.node),m=T(p?.amount1000),A=h(p?.noteMessage);return {type:"payment",kind:l.kind,amount:m!=null?m/1e3:null,currency:M(p?.currencyCodeIso4217),note:z(A?.conversation,h(A?.extendedTextMessage)?.text),expiresAt:T(p?.expiryTimestamp)}}let u=h(n.eventMessage);if(u!=null){let p=h(u.location);return {type:"event",name:M(u.name),description:M(u.description),location:p!=null?z(p.name,p.address):null,startTime:T(u.startTime),endTime:T(u.endTime),isCanceled:u.isCanceled===true}}let w=h(n.buttonsMessage);if(w!=null){let p=Array.isArray(w.buttons)?w.buttons:[];return {type:"buttons",contentText:M(w.contentText),footerText:M(w.footerText),buttons:p.map(m=>({id:M(h(m)?.buttonId),text:M(h(h(m)?.buttonText)?.displayText)}))}}let S=h(n.listMessage);if(S!=null){let p=Array.isArray(S.sections)?S.sections:[];return {type:"list",title:M(S.title),description:M(S.description),buttonText:M(S.buttonText),sections:p.map(m=>{let A=Array.isArray(h(m)?.rows)?h(m).rows:[];return {title:M(h(m)?.title),rows:A.map(E=>({id:M(h(E)?.rowId),title:M(h(E)?.title),description:M(h(E)?.description)}))}})}}let v=h(n.interactiveMessage);if(v!=null){let p=h(v.nativeFlowMessage),m=Array.isArray(p?.buttons)?p.buttons:[];return {type:"interactive",title:M(h(v.header)?.title),body:M(h(v.body)?.text),footer:M(h(v.footer)?.text),buttons:m.map(A=>({name:M(h(A)?.name),params:M(h(A)?.buttonParamsJson)}))}}let C=h(n.templateMessage);if(C!=null){let p=h(C.hydratedTemplate)??h(C.hydratedFourRowTemplate),m=Array.isArray(p?.hydratedButtons)?p.hydratedButtons:[];return {type:"template",text:M(p?.hydratedContentText),buttons:m.map(A=>{let E=h(A),de=h(E?.quickReplyButton)??h(E?.urlButton)??h(E?.callButton);return {id:M(de?.id),text:M(de?.displayText)}})}}let y=h(n.extendedTextMessage);if(y!=null){let p=z(y.canonicalUrl,y.matchedText),m=M(y.title),A=M(y.description);if(p!=null&&(m!=null||A!=null))return {type:"link",url:p,title:m,description:A}}return null};var Ge=n=>{let e=h(n.message);if(e==null)return null;let t=He(e);return ts(t)??Ko(t)??Jo(t)},At=n=>{let e=h(es(n).message);if(e==null)return null;let t=h(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(St)){let s=e[r];if(s!=null&&typeof s=="object"){let i=s.contextInfo;if(i!=null)return i}}return null},Go=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[St[e]];return r==null||typeof r!="object"?null:r},Vo=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(St)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},Ho=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,se=n=>{let e=h(n);if(e==null)return "text";let t=He(e);for(let r of Object.values(St))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of $o)if(t[r]!=null)return s;return "text"},zo=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},Yo=async(n,e,t,r,s)=>{try{if(n==null||n.quotedMessage==null)return null;let i=n.stanzaId;if(typeof i!="string"||i.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let v=await e.resolveQuoted(i,t);if(v!=null&&v.message!=null){let C=Ge(v)??"",y=ie(v,e,se(v.message),C,Ve(v,e),s);if(y!==null)return y}}let o=_r(n);if(o===null||typeof o.key.id!="string"||o.key.id.length===0||(t.length>0&&(o.key.remoteJid=t),typeof o.key.remoteJid!="string"||o.key.remoteJid.length===0))return null;let a=o.key.participant,c=typeof a=="string"&&(e.selfJid.length>0&&Mt(a,e.selfJid)||e.selfLid!=null&&Mt(a,e.selfLid)),d=fe(t),l=o.sender?.pushName;c?(o.key.fromMe=!0,e.selfJid.length>0&&(o.key.participant=e.selfJid),e.selfLid!=null&&(o.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&(!d||zo(o.sender,r))&&(r.pn!=null&&(o.key.participant=r.pn),r.lid!=null&&(o.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,w=Object.assign({key:o.key,message:u??null},l!=null?{pushName:l}:{}),S=Ge(w)??"";return ie(w,e,se(u),S,Ve(w,e),s)}catch{return null}},rs=n=>Ke(At(n)).mentionedJids,Zo=n=>{try{return aa.jidNormalizedUser(n)}catch{return n}},ss=(n,e)=>n.map(t=>{let r=Zo(t);return e.lidMap?.get(r)??r}),Xr=n=>(n.split("@")[0]??"").split(":")[0]??"",Xo=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Xr(s),Xr(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},ie=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=q(o,n.pushName??void 0);if(a===null)return null;let c=Qr(o);if(c.length===0)return null;let d=At(n),l=fe(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),S=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=Vo(n),C=Ho(n,d),y=e.channelId??"",p=e.receiverId??"",m=e.prefixes??[],A=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),E=e.resolveReceiverName??(()=>Promise.resolve(null)),de=()=>Yo(d,e,c,a,A),Ft=c.length>0?c:a.pn??a.jid,Wt=(Ut,Ks)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(Ft,Ut,Ks,n),jt=Ut=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,Ut),Us=ss(Ke(d).mentionedJids,e),qs=Xo(r,e.lidMap),wn={message:n,key:o,channelId:y,receiverId:p,selfJid:e.selfJid,text:qs,chatType:t,sender:a,mentions:Us,isViewOnce:v,isEphemeral:C,isForwarded:S,isBroadcast:u,isNewsletter:w,prefixes:m,...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:A,resolveReceiverName:E,resolveReplied:de,reply:Wt,react:jt},vn=s!==void 0?{...wn,media:s}:wn;return pn(e.citationConfig!==void 0?{...vn,citationConfig:e.citationConfig}:vn)},Qo=["image","video","audio","document","sticker"],is=(n,e,t)=>{let r=es(n),s=Go(r,e);if(s===null)return null;let i=lt(r,e,t.logger),o=pr(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:T(s.fileLength),ptt:s.ptt===true,buffer:async()=>(await i()).buffer,stream:o}},Ve=(n,e)=>{let t=h(n.message);if(t==null)return;let r=se(n.message);return Qo.includes(r)?is(n,r,e)??void 0:ns(He(t))??void 0},os=(n,e)=>{if(h(n.message)==null)return null;let r=se(n.message),s=Ve(n,e),i=Ge(n)??"";return i===""&&s===void 0?null:ie(n,e,r,i,s)},as=(n,e)=>{let t=h(n.message);if(t==null)return null;let r=He(t),s=ts(r),i=ns(r)??void 0;return s===null&&i===void 0?null:ie(n,e,se(n.message),s??"",i)},ze=(n,e,t)=>{let r=is(e,n,t);return r===null?null:ie(e,t,n,r.caption??"",r)},cs=(n,e)=>ze("image",n,e),ds=(n,e)=>ze("video",n,e),ls=(n,e)=>ze("audio",n,e),us=(n,e)=>ze("document",n,e),ps=(n,e)=>ze("sticker",n,e),Mt=(n,e)=>{try{return aa.jidNormalizedUser(n)===aa.jidNormalizedUser(e)}catch{return n===e}},ms=(n,e)=>{if(n.key==null)return null;let r=At(n),s=Ke(r).mentionedJids;if(s.length===0)return null;let i=ss(s,e);if(!(i.some(u=>Mt(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Mt(u,e.selfLid)))||h(n.message)==null)return null;let c=Ge(n)??"",d=Ve(n,e),l=ie(n,e,se(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},gs=(n,e)=>{let t=n.key;if(t==null)return null;let r=Qr(t);if(r.length===0||!fe(r))return null;let{mentionAll:s}=Ke(At(n));if(!s||h(n.message)==null)return null;let o=Ge(n)??"",a=Ve(n,e),c=ie(n,e,se(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var oe=(n,e)=>{let t=he(n);return t===null?e:t},ea=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
|
|
15
15
|
`)}return ""},ta=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],hs=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=q(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:oe(t.senderTimestampMs,0)}},ys=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==aa.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=q(n.key,e.pushName);return s===null?null:{key:r,newContent:ea(t.editedMessage),editedAt:oe(n.update.messageTimestamp,0),sender:s}},ws=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==aa.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=q(n.key,e.pushName);if(s===null)return null;let i=ge(n.key.remoteJid),o=ge(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:oe(n.update.messageTimestamp,0)}},vs=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=q(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;return i?{pollKey:i,selectedOptions:ta(t.vote?.selectedOptions),voter:s,timestamp:oe(t.senderTimestampMs,oe(n.update.messageTimestamp,0))}:null}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:oe(r.senderTimestampMs,oe(n.update.messageTimestamp,0))}:null}return null};var Pt=n=>Array.isArray(n)?n:[],na=3e3,ra=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),sa=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function Ss(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let p=s.get(y);if(p!==void 0)return p;let m=t.groupMetadata;if(m==null)return Promise.resolve(null);let A=m(y).then(E=>E?.subject??null).catch(()=>null);return s.set(y,A),A}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid},d=(y,p)=>{let m=(...A)=>{try{p(A[0]);}catch(E){t.logger?.warn(E,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,m),r.push(()=>e.ev.off(y,m));},l=(y,p)=>{v(()=>os(y,p),m=>n.emit("message",m)),v(()=>as(y,p),m=>n.emit("text",m)),v(()=>cs(y,p),m=>n.emit("image",m)),v(()=>ds(y,p),m=>n.emit("video",m)),v(()=>ls(y,p),m=>n.emit("audio",m)),v(()=>us(y,p),m=>n.emit("document",m)),v(()=>ps(y,p),m=>n.emit("sticker",m)),v(()=>ms(y,p),m=>n.emit("mention",m)),v(()=>gs(y,p),m=>n.emit("mention-all",m)),v(()=>Ur(y,a),m=>n.emit("button-click",m)),v(()=>qr(y,a),m=>n.emit("list-select",m));},u=y=>{if(typeof y!="string"||y.length===0)return null;let p;try{p=aa.jidNormalizedUser(y);}catch{p=y;}return yt(p)?p:null},w=y=>{let p=new Set;for(let m of [y.key?.participant,y.key?.remoteJid,t.selfJid,...rs(y)]){let A=u(m);A!=null&&p.add(A);}return [...p]},S=async y=>{let p=t.resolveLidToPn;if(p==null||y.length===0)return;let m=new Map;return await Promise.all(y.map(async A=>{try{let E=await ra(Promise.resolve(p(A)),na);if(E!=null&&E.length>0)try{m.set(A,aa.jidNormalizedUser(E));}catch{m.set(A,E);}}catch(E){t.logger?.warn(E,"inbound pipeline: lid->pn resolve threw");}})),m.size>0?m:void 0},v=(y,p)=>{let m;try{m=y();}catch(A){t.logger?.warn(A,"inbound pipeline: decoder threw");return}m!=null&&p(m);};d("messages.upsert",y=>{let p=br(y);for(let m of p.messages){if(t.ignoreMe===!0&&m.key?.fromMe===!0)continue;let A=t.resolveLidToPn!=null?w(m):[];if(A.length===0){l(m,o);continue}S(A).then(E=>l(m,E!=null?{...o,lidMap:E}:o)).catch(E=>{t.logger?.warn(E,"inbound pipeline: deferred lid resolve emit failed"),l(m,o);});}}),d("messages.update",y=>{for(let p of Pt(y))v(()=>ys(p,c),m=>n.emit("edit",m)),v(()=>ws(p,c),m=>n.emit("delete",m)),v(()=>vs(p,c),m=>n.emit("poll-vote",m));}),d("messages.reaction",y=>{for(let p of Pt(y))v(()=>hs(p,c),m=>n.emit("reaction",m));}),d("groups.update",y=>{for(let p of Pt(y))v(()=>xr(p),m=>n.emit("group-update",m));}),d("group-participants.update",y=>{let p=y;v(()=>Lr(p),m=>n.emit("group-join",m)),v(()=>Nr(p),m=>n.emit("group-leave",m));}),d("group.member-tag.update",y=>{v(()=>Rr(y),p=>n.emit("member-tag",p));}),d("call",y=>{for(let p of Pt(y))v(()=>Tr(p),m=>n.emit("call-incoming",m)),v(()=>Or(p),m=>n.emit("call-ended",m));}),d("messaging-history.status",y=>{v(()=>Kr(y),p=>n.emit("history-sync",p));}),d("presence.update",y=>{let p=(()=>{try{return Jr(y)}catch(m){return t.logger?.warn(m,"inbound pipeline: decodePresence threw"),[]}})();for(let m of p)n.emit("presence",m);}),d("connection.update",y=>{let p=sa(y);p!==null&&v(()=>un({source:"connection-update",reachoutTimeLock:p}),m=>n.emit("limited",m));}),d("message-capping.update",y=>{v(()=>un({source:"message-capping",capInfo:y}),p=>n.emit("limited",p));}),d("newsletter.reaction",y=>{v(()=>Je({source:"reaction",payload:y}),p=>n.emit("newsletter",p));}),d("newsletter.view",y=>{v(()=>Je({source:"view",payload:y}),p=>n.emit("newsletter",p));}),d("newsletter-participants.update",y=>{v(()=>Je({source:"participants",payload:y}),p=>n.emit("newsletter",p));}),d("newsletter-settings.update",y=>{v(()=>Je({source:"settings",payload:y}),p=>n.emit("newsletter",p));});let C=false;return {detach(){if(!C){C=true;for(let y of r)y();r.length=0;}}}}var Ct=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=oa,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},oa=Symbol("zaileys.typed-ee.tag");var da="default",la="qr",Ps=6e4,Cs=class extends Ct{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=Cr();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;_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;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;constructor(e={}){super({logger:dn(e.logger)}),this.sessionId=e.sessionId??da,this.logger=dn(e.logger),this.authType=e.authType??la,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&fr(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new pt({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new ht,this.reconnectStrategy=Pr(this.reconnectOptions),this.authGuard=Mr(e.authGuard),this.operationGuard=an(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ne({perSec:t}):void 0,this.commandPrefixes=ua(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof aa.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=aa.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=gr(e);t&&process.stderr.write(`${t}
|
|
16
|
-
`);}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 Ce(()=>this._socket,this.operationGuard)}get privacy(){return this._privacy??=new Ee(()=>this._socket)}get newsletter(){return this._newsletter??=new be(()=>this._socket,this.operationGuard)}get community(){return this._community??=new ke(()=>this._socket,this.operationGuard)}get profile(){return this._profile??=new Te(()=>this._socket)}get chat(){return this._chat??=new Oe(()=>this._socket,async e=>{try{return (await this.store.listMessages(e,{limit:1})).filter(r=>r.key!=null).map(r=>({key:r.key,messageTimestamp:Number(r.messageTimestamp??0)}))}catch{return []}})}get contact(){return this._contact??=new Ie(()=>this._socket,e=>Pe(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this._business??=new xe(()=>this._socket)}get presence(){return this._presence??=new _e(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),cn(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Be({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}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";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=hr(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=yr(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:Ps,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a)},i=aa__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{let d=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{d?.(),a();},this.connectReject=u=>{l?.(u),c(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??aa.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.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,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 Re).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=rn({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 x("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(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return Pe(e)?V.create(t,e,void 0,r):V.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return new Ae(this.requireSocket(),e)}async delete(e,t){await Zt(this.requireSocket(),e,t);}async react(e,t){return Xt(this.requireSocket(),e,t)}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return Qt(r,this.store,e,s)}async pin(e,t){return dt(this.requireSocket(),e,true,t)}async unpin(e){return dt(this.requireSocket(),e,false)}async setDisappearing(e,t){let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}resolveRecipient(e){return en(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new g("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.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Sr({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let c=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:c.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:c.code,expiresAt:c.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Ar(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+Ps});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Ss(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.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")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Fe({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Le({client:this,logger:this.logger}),this.pluginLoader=new Ne({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(c=>o[r[c]]!=null);return a===void 0?null:lt(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=pa(e?.error),r=wr(t),s=false;if(vr(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(!Ue(r)&&!this.authExhausted){mt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");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 ua(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function pa(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 Es=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 f("STORE_CLOSED","MemoryAuthStore is closed")}};var Et=null,ma=async()=>{if(Et)return Et;try{return Et=(await import('better-sqlite3')).default,Et}catch(n){throw new f("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},gn="default",ks=500,Ts=n=>Array.from({length:n},()=>"?").join(","),Os=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Is=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(gn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(gn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(gn);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Os(t,ks)){let o=Ts(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 l=c[d];l===null?i.push({type:a,id:d}):l!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Ts(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Os(t,ks))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 f("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new f("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 ma(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new f("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
|
+
`);}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 Ce(()=>this._socket,this.operationGuard)}get privacy(){return this._privacy??=new Ee(()=>this._socket)}get newsletter(){return this._newsletter??=new be(()=>this._socket,this.operationGuard)}get community(){return this._community??=new ke(()=>this._socket,this.operationGuard)}get profile(){return this._profile??=new Te(()=>this._socket)}get chat(){return this._chat??=new Oe(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this._contact??=new Ie(()=>this._socket,e=>Pe(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this._business??=new xe(()=>this._socket)}get presence(){return this._presence??=new _e(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),cn(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Be({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}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";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=hr(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=yr(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:Ps,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a)},i=aa__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{let d=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{d?.(),a();},this.connectReject=u=>{l?.(u),c(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??aa.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.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,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 Re).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=rn({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 x("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(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return Pe(e)?V.create(t,e,void 0,r):V.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return new Ae(this.requireSocket(),e)}async delete(e,t){await Zt(this.requireSocket(),e,t);}async react(e,t){return Xt(this.requireSocket(),e,t)}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return Qt(r,this.store,e,s)}async pin(e,t){return dt(this.requireSocket(),e,true,t)}async unpin(e){return dt(this.requireSocket(),e,false)}async setDisappearing(e,t){let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}resolveRecipient(e){return en(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new g("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.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Sr({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let c=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:c.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:c.code,expiresAt:c.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Ar(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+Ps});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Ss(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.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")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Fe({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Le({client:this,logger:this.logger}),this.pluginLoader=new Ne({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(c=>o[r[c]]!=null);return a===void 0?null:lt(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=pa(e?.error),r=wr(t),s=false;if(vr(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(!Ue(r)&&!this.authExhausted){mt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");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 ua(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function pa(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 Es=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 f("STORE_CLOSED","MemoryAuthStore is closed")}};var Et=null,ma=async()=>{if(Et)return Et;try{return Et=(await import('better-sqlite3')).default,Et}catch(n){throw new f("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},gn="default",ks=500,Ts=n=>Array.from({length:n},()=>"?").join(","),Os=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Is=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(gn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(gn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(gn);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Os(t,ks)){let o=Ts(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 l=c[d];l===null?i.push({type:a,id:d}):l!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Ts(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Os(t,ks))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 f("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new f("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 ma(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new f("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;
|
|
17
17
|
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 f("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,aa.BufferJSON.replacer),"utf8")}catch(t){throw new f("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,aa.BufferJSON.reviver)}catch(t){throw new f("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var kt,ga=async()=>(kt||(kt=import('pg').catch(n=>{throw kt=void 0,new f("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),kt),fa="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",ha="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",xs=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 f("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new f("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 f("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 ga(),r=t.Pool??t.default?.Pool;if(!r)throw new f("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(fa),await e.query(ha);}catch(t){throw new f("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"),aa.BufferJSON.reviver);}return s}catch(i){throw i instanceof f?i:new f("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,aa.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 f("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 f("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 f("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,aa.BufferJSON.reviver)}catch(t){throw t instanceof f?t:new f("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,aa.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 f("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 f("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var ya="zaileys",wa=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],va=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Rs=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new f("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new f("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??ya,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,aa.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),l=this.indexKey(i);c===null?(r.del(d),r.sRem(l,a)):c!==void 0&&(r.set(d,JSON.stringify(c,aa.BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of wa){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,aa.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,aa.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 f("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 va(r)?new f("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new f("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 f("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 f("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new f("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 f("STORE_CLOSED","RedisAuthStore is closed")}};var Ma="zaileys",Ye={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Sa=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},ye=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new f("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new f("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??Ma,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(Ye.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(Ye.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(Ye.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ye.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(Ye.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 Sa(r)?new f("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new f("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 f("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new f("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new f("STORE_CLOSED","Convex store is closed")}};var It="creds",Aa="signal:",Ze=(n,e)=>`${Aa}${n}:${e}`,Ls=class{creds;signal;kv;constructor(e){this.kv=new ye(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([It])).get(It);return s===void 0?void 0:JSON.parse(s,aa.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:It,value:JSON.stringify(r,aa.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([It]);}},this.signal={async read(r,s){let i=s.map(c=>Ze(r,c)),o=await t.get(i),a={};for(let c of s){let d=o.get(Ze(r,c));a[c]=d===void 0?void 0:JSON.parse(d,aa.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(Ze(o,c)):s.push({key:Ze(o,c),value:JSON.stringify(d,aa.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=>Ze(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var xt=null,Pa=async()=>{if(xt)return xt;try{return xt=(await import('better-sqlite3')).default,xt}catch(n){throw new f("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Rt=n=>{try{return Buffer.from(JSON.stringify(n,aa.BufferJSON.replacer),"utf8")}catch(e){throw new f("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},ae=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,aa.BufferJSON.reviver)}catch(e){throw new f("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ns=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,Rt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?ae(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=>ae(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,Rt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?ae(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>ae(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,Rt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?ae(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>ae(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,Rt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?ae(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
18
18
|
SELECT rowid FROM (
|
|
19
19
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|
package/dist/index.mjs
CHANGED
|
@@ -7,13 +7,13 @@ import aa,{prepareWAMessageMedia,generateWAMessageFromContent,BufferJSON,makeCac
|
|
|
7
7
|
`)}:{type:"code",content:u.join(`
|
|
8
8
|
`)});continue}let d=e[i+1];if(o.includes("|")&&d!==void 0&&d.includes("|")&&mi.test(d)){s();let u=[qn(o)];for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim().length>0;)u.push(qn(e[i])),i++;t.push({type:"table",rows:u});continue}let l=Un.exec(o);if(l){s();let u=[l[1]];for(i++;i<e.length;){let w=Un.exec(e[i]);if(!w)break;u.push(w[1]),i++;}t.push({type:"image",url:u.length===1?u[0]:u});continue}r.push(o),i++;}return s(),t};var $n=(n,e)=>{if(typeof n!="string"||!n.trimStart().startsWith("BEGIN:VCARD"))throw new g("INVALID_OPTIONS","contact() requires a vcard string starting with BEGIN:VCARD");let t={contacts:[{vcard:n}]};return {contacts:t}};var Gn=async(n,e)=>{if(typeof e?.fileName!="string"||e.fileName.trim().length===0)throw new g("INVALID_OPTIONS","document() requires a non-empty fileName");let{buffer:t,mime:r}=await I(n),s={document:t,fileName:e.fileName,mimetype:e.mimetype??r};return e.caption!==void 0&&(s.caption=e.caption),s};var Vn=(n,e)=>{let t=n instanceof Date?n:new Date(n);if(Number.isNaN(t.getTime()))throw new g("INVALID_OPTIONS",`event() ${e} must be a valid Date or epoch ms`);return new Date(Math.floor(t.getTime()/1e3)*1e3)},Hn=n=>{if(n==null||typeof n.name!="string"||n.name.trim().length===0)throw new g("INVALID_OPTIONS","event() requires a non-empty name");return {event:{name:n.name,startDate:Vn(n.startAt,"startAt"),...n.description!==void 0?{description:n.description}:{},...n.endAt!==void 0?{endDate:Vn(n.endAt,"endAt")}:{},...n.call!==void 0?{call:n.call}:{},...n.canceled!==void 0?{isCancelled:n.canceled}:{},...n.location!==void 0?{location:{degreesLatitude:n.location.latitude,degreesLongitude:n.location.longitude,...n.location.name!==void 0?{name:n.location.name}:{},...n.location.address!==void 0?{address:n.location.address}:{}}}:{}}}};var zn=n=>{if(n==null||typeof n.jid!="string"||!n.jid.endsWith("@g.us"))throw new g("INVALID_OPTIONS","groupInvite() requires a group jid ending in @g.us");if(typeof n.code!="string"||n.code.trim().length===0)throw new g("INVALID_OPTIONS","groupInvite() requires an invite code");let e={inviteCode:n.code,inviteExpiration:n.expiresAt??Math.floor(Date.now()/1e3)+3*86400,groupJid:n.jid,groupName:n.subject??"",caption:n.caption??""};return n.thumbnail!==void 0&&(e.jpegThumbnail=n.thumbnail),{[N]:{groupInviteMessage:e}}};var Yn=10,Zn=n=>{if(typeof n?.buttonText!="string"||n.buttonText.trim().length===0)throw new g("INVALID_OPTIONS","list() requires a non-empty buttonText");if(!Array.isArray(n.sections)||n.sections.length===0)throw new g("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 g("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 g("INVALID_OPTIONS","list row id must be a non-empty string");if(typeof d.title!="string"||d.title.trim().length===0)throw new g("INVALID_OPTIONS","list row title must be a non-empty string");if(t.has(d.id))throw new g("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>Yn)throw new g("INVALID_OPTIONS",`list() accepts at most ${Yn} 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}),{[N]:{interactiveMessage:i}}};var Xn=(n,e,t)=>{if(typeof n!="number"||Number.isNaN(n)||n<-90||n>90)throw new g("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 g("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 Qn=2,er=12,tr=(n,e,t)=>{if(typeof n!="string"||n.trim().length===0)throw new g("EMPTY_CONTENT","poll() requires a non-empty question");if(!Array.isArray(e)||e.length<Qn)throw new g("INVALID_OPTIONS",`poll() requires a minimum of ${Qn} options`);if(e.length>er)throw new g("INVALID_OPTIONS",`poll() accepts a maximum of ${er} options`);let r=new Set;for(let i of e){if(typeof i!="string"||i.trim().length===0)throw new g("INVALID_OPTIONS","poll options must be non-empty strings");if(r.has(i))throw new g("INVALID_OPTIONS",`duplicate poll options: ${i}`);r.add(i);}return {poll:{name:n,values:e,selectableCount:t?.multipleChoice?e.length:1}}};var nr=async n=>{if(n==null||typeof n.title!="string"||n.title.trim().length===0)throw new g("INVALID_OPTIONS","product() requires a non-empty title");if(typeof n.businessOwnerId!="string"||n.businessOwnerId.length===0)throw new g("INVALID_OPTIONS","product() requires businessOwnerId");let{buffer:e}=await I(n.image),t={productImage:e,title:n.title};n.productId!==void 0&&(t.productId=n.productId),n.description!==void 0&&(t.description=n.description),n.currency!==void 0&&(t.currencyCode=n.currency),n.price!==void 0&&(t.priceAmount1000=Math.round(n.price*1e3)),n.retailerId!==void 0&&(t.retailerId=n.retailerId),n.url!==void 0&&(t.url=n.url);let r={product:t,businessOwnerJid:n.businessOwnerId};return n.body!==void 0&&(r.body=n.body),n.footer!==void 0&&(r.footer=n.footer),r};var rr=async(n,e)=>{let{buffer:t}=await I(n),r;try{r=await new ee(t).sticker.create();}catch(i){throw new g("MEDIA_LOAD_FAILED",`sticker() conversion failed: ${i.message}`,{cause:i})}return {sticker:r,isAnimated:e?.animated??false}};var sr=3,ir=n=>{if(typeof n?.body!="string"||n.body.trim().length===0)throw new g("INVALID_OPTIONS","template() requires a non-empty body");if(!Array.isArray(n.buttons)||n.buttons.length===0)throw new g("INVALID_OPTIONS","template() requires at least one button");if(n.buttons.length>sr)throw new g("INVALID_OPTIONS",`template() accepts at most ${sr} 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),it(n.buttons,t)};var ct=n=>{if(typeof n!="string"||n.trim().length===0)throw new g("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var or=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var Mi=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],V=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,or(t,r,s))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=Wn(Jn(e),t):this.internal.content=ct(e),this}image(e,t){return this.internal.pendingContent=le(e,t),this}videoNote(e,t){return this.internal.pendingContent=X(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=X(e,t),this}audio(e,t){return this.internal.pendingContent=Dn(e,t),this}document(e,t){return this.internal.pendingContent=Gn(e,t),this}sticker(e,t){return this.internal.pendingContent=rr(e,t),this}buttons(e,t){return this.internal.content=it(e,t),this}carousel(e,t){return this.internal.content=Fn(e,t),this}list(e){return this.internal.content=Zn(e),this}poll(e,t,r){return this.internal.content=tr(e,t,r),this}location(e,t,r){return this.internal.content=Xn(e,t,r),this}contact(e){return this.internal.content=$n(e),this}template(e){return this.internal.content=ir(e),this}event(e){return this.internal.content=Hn(e),this}groupInvite(e){return this.internal.content=zn(e),this}product(e){return this.internal.pendingContent=nr(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new g("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 g("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new g("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 g("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),xn(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 g("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[N];if(i!==void 0){let d=s[$t],l=s[Vt];return this.sendRelay(i,d,l)}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 g("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new g("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await I(t.src),s=await 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 g("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let u=e.interactiveMessage?.header;t!==void 0&&u&&await this.uploadHeaderMedia(u,t);let w=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&w)for(let S of r){let v=w[S.index]?.header;v&&await this.uploadHeaderMedia(v,S);}}catch(u){throw new g("SEND_FAILED","interactive media upload failed",{cause:u})}let o={userJid:this.socket.user?.id??""},a=this.internal.quoted;a!==void 0&&a.message!=null&&(o.quoted=a);let c=generateWAMessageFromContent(this.internal.recipient,e,o);if(typeof c.key?.id!="string")throw new g("SEND_FAILED","failed to generate relay message key");let l="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:c.key.id,additionalNodes:Mi}:{messageId:c.key.id};try{await s(this.internal.recipient,c.message,l);}catch(u){throw new g("SEND_FAILED","socket relayMessage rejected",{cause:u})}return this.internal.recordSent?.(c),c.key}};var Ae=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=ct(e),this}image(e,t){return this.pendingContent=le(e,t),this}video(e,t){return this.pendingContent=X(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 g("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new g("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 g("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new g("SEND_FAILED","socket returned no message key");return r.key}};var zt=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new g("INVALID_OPTIONS","message key is missing remoteJid");return e},Yt=n=>{if(!n?.key)throw new g("SEND_FAILED","socket returned no message key");return n.key},Zt=async(n,e,t={})=>{let r=zt(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new g("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},Xt=async(n,e,t)=>{let r=zt(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return Yt(s)},Qt=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new g("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return Yt(i)},dt=async(n,e,t,r={})=>{let s=zt(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return Yt(o)};var Si=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Pe=n=>Si.test(n),en=async(n,e,t,r=Ai)=>{if(Pe(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 g("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);}},Ai=new Map;var k=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 Ce=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new k("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var Ee=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("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 be=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new k("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var ke=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var Te=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Pi=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new k("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Oe=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){await this.requireSocket().chatModify({markRead:true,lastMessages:await this.last(e)},e);}async markUnread(e){await this.requireSocket().chatModify({markRead:false,lastMessages:await this.last(e)},e);}async star(e,t=true){let r=Pi(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var Ie=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var xe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var x=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 Ci=n=>{let e=n[0];return e==="{"||e==="["},Ei=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},bi=n=>n===" "||n===" "||n===`
|
|
10
|
+
`:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),it(n.buttons,t)};var ct=n=>{if(typeof n!="string"||n.trim().length===0)throw new g("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var or=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var Mi=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],V=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,or(t,r,s))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=Wn(Jn(e),t):this.internal.content=ct(e),this}image(e,t){return this.internal.pendingContent=le(e,t),this}videoNote(e,t){return this.internal.pendingContent=X(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=X(e,t),this}audio(e,t){return this.internal.pendingContent=Dn(e,t),this}document(e,t){return this.internal.pendingContent=Gn(e,t),this}sticker(e,t){return this.internal.pendingContent=rr(e,t),this}buttons(e,t){return this.internal.content=it(e,t),this}carousel(e,t){return this.internal.content=Fn(e,t),this}list(e){return this.internal.content=Zn(e),this}poll(e,t,r){return this.internal.content=tr(e,t,r),this}location(e,t,r){return this.internal.content=Xn(e,t,r),this}contact(e){return this.internal.content=$n(e),this}template(e){return this.internal.content=ir(e),this}event(e){return this.internal.content=Hn(e),this}groupInvite(e){return this.internal.content=zn(e),this}product(e){return this.internal.pendingContent=nr(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new g("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 g("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new g("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 g("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),xn(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 g("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[N];if(i!==void 0){let d=s[$t],l=s[Vt];return this.sendRelay(i,d,l)}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 g("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new g("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await I(t.src),s=await 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 g("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let u=e.interactiveMessage?.header;t!==void 0&&u&&await this.uploadHeaderMedia(u,t);let w=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&w)for(let S of r){let v=w[S.index]?.header;v&&await this.uploadHeaderMedia(v,S);}}catch(u){throw new g("SEND_FAILED","interactive media upload failed",{cause:u})}let o={userJid:this.socket.user?.id??""},a=this.internal.quoted;a!==void 0&&a.message!=null&&(o.quoted=a);let c=generateWAMessageFromContent(this.internal.recipient,e,o);if(typeof c.key?.id!="string")throw new g("SEND_FAILED","failed to generate relay message key");let l="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:c.key.id,additionalNodes:Mi}:{messageId:c.key.id};try{await s(this.internal.recipient,c.message,l);}catch(u){throw new g("SEND_FAILED","socket relayMessage rejected",{cause:u})}return this.internal.recordSent?.(c),c.key}};var Ae=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=ct(e),this}image(e,t){return this.pendingContent=le(e,t),this}video(e,t){return this.pendingContent=X(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 g("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new g("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 g("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new g("SEND_FAILED","socket returned no message key");return r.key}};var zt=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new g("INVALID_OPTIONS","message key is missing remoteJid");return e},Yt=n=>{if(!n?.key)throw new g("SEND_FAILED","socket returned no message key");return n.key},Zt=async(n,e,t={})=>{let r=zt(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new g("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},Xt=async(n,e,t)=>{let r=zt(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return Yt(s)},Qt=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new g("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return Yt(i)},dt=async(n,e,t,r={})=>{let s=zt(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return Yt(o)};var Si=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Pe=n=>Si.test(n),en=async(n,e,t,r=Ai)=>{if(Pe(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 g("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);}},Ai=new Map;var k=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 Ce=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new k("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new k("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var Ee=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("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 be=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new k("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var ke=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var Te=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Pi=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new k("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},Oe=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:true,lastMessages:t},e);}async markUnread(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:false,lastMessages:t},e);}async star(e,t=true){let r=Pi(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var Ie=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var xe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new k("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var x=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 Ci=n=>{let e=n[0];return e==="{"||e==="["},Ei=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},bi=n=>n===" "||n===" "||n===`
|
|
11
11
|
`||n==="\r",ki=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(bi(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Ti=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},Oi=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function tn(n,e){let t=Ti(n,e);if(t===null)return Oi(n);let r=n.slice(t.length),s=ki(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 l=d.indexOf("=");if(l!==-1){let w=d.slice(0,l),S=d.slice(l+1);i.flags[w]=S;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[d]=u,a+=1):i.flags[d]=true;continue}if(!o&&Ci(c)){let d=Ei(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var ar=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new x("INVALID_COMMAND_NAME","empty command segment in spec");return e},pe=n=>n.join(" "),Re=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new x("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>ar(a)),s=r[0],i=r.slice(1).map(a=>pe(a)),o={name:pe(s),aliases:i,parts:s,handler:t};for(let a of r){let c=pe(a);if(this.paths.has(c))throw new x("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(pe(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)}}}unregister(e){let t=e.split("|").map(o=>ar(o)),r=pe(t[0]),s=this.paths.get(r);if(s===void 0)return;for(let o of [s.parts,...s.aliases.map(a=>a.split(" "))])this.paths.delete(pe(o));let i=this.defs.indexOf(s);i>=0&&this.defs.splice(i,1),this.maxDepth=this.defs.reduce((o,a)=>Math.max(o,a.parts.length),1);}list(){return [...this.defs]}};async function nn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new x("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 x?c:new x("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function rn(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=tn(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(nn(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let l=d instanceof x?d:new x("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(l,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var cr=n=>n;var Le=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t){if(typeof e?.name!="string"||typeof e?.setup!="function"){this.logger?.warn({file:t},"plugin: invalid shape (need name + setup); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let r=[],s={client:this.host,logger:this.logger,pluginDir:We.dirname(t),command:(i,o)=>{this.host.command(i,o),r.push(()=>this.host.unregisterCommand(i));},use:i=>{this.host.use(i),r.push(()=>{this.host.unuse(i);});},on:(i,o)=>{let a=this.host.on(i,o);return r.push(a),a},once:(i,o)=>{let a=false,c=this.host.on(i,d=>{a||(a=true,c(),o(d));});return r.push(c),c}};try{let i=await e.setup(s);typeof i=="function"&&r.push(i);}catch(i){for(let o of [...r].reverse())try{await o();}catch{}this.logger?.error({err:i,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:r});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Li=/\.(ts|js|mjs|cjs)$/,Ni=/(\.d\.ts$|^_|[/\\]_)/;async function on(n,e,t){let r;try{r=await promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=We.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await on(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function lr(n,e){try{let r=await import(pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"&&typeof s.setup=="function"?s:void 0}catch{return}}var Ne=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=We.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Li,this.ignore=e.options.ignore??Ni,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await on(this.dir,this.pattern,this.ignore);for(let t of e)await this.loadFile(t);this.watchEnabled&&this.startWatch();}async stop(){this.debounce&&clearTimeout(this.debounce),this.watcher?.close(),this.watcher=void 0,await this.flushChain,await this.registry.unloadAll(),this.fileToName.clear();}async loadFile(e){let t=await lr(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=We.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var O=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 Di=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),ne=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new O("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new O("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new O("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??Di;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 _i={"group.create":6e4,"group.join":3e4,"group.participants":1e4,"group.update":3e3,"community.create":12e4,"community.join":3e4,"community.update":3e3,"newsletter.create":12e4,"newsletter.follow":2e3,"newsletter.update":3e3},Bi=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function an(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??Bi,i={..._i,...n.intervalsMs??{}},o=new Map,a=new Map,c=async(d,l)=>{let u=i[d]??0,w=o.get(d);if(w!==void 0&&u>0){let S=u-(r()-w);S>0&&await s(S);}return o.set(d,r()),l()};return {run(d,l){if(!t)return l();let w=(a.get(d)??Promise.resolve()).then(()=>c(d,l),()=>c(d,l));return a.set(d,w.then(()=>{},()=>{})),w}}}var Fi={maxRetries:0,backoffMs:()=>0},Wi=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),De=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??Fi,this.sleep=t.sleep??Wi;}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 ji=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function cn(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 ne({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},l=c?new De({concurrency:1,retry:c},d):void 0,u=n.length,w=0;for(let S of n){await a.acquire(S);let v=()=>e(t.sendTo(S)).then(()=>{});try{l?await l.add(v):await v(),s.sent.push(S),w+=1,r.onProgress?.(w,u,S,!0);}catch(C){s.failed.push({jid:S,error:ji(C)}),w+=1,r.onProgress?.(w,u,S,false);}}return s}var Ui=1e3,_e=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??Ui,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new Map;requireSocket(){let e=this.getSocket();if(!e)throw new O("NOT_CONNECTED","client not connected");return e}throttled(e,t){if(!this.throttleEnabled||this.minIntervalMs<=0)return false;let r=`${e}:${t??"global"}`,s=this.lastSent.get(r),i=this.now();return s!==void 0&&i-s<this.minIntervalMs?true:(this.lastSent.set(r,i),false)}async update(e,t){let r=this.requireSocket();if(!this.throttled(e,t))try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new O("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 Ki={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},Ji=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",Be=class{store;sendSnapshot;now;timer;logger;acquire;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??Ki,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new O("SCHEDULE_INVALID","scheduleAt requires a valid Date");let s=await this.evaluate(t),i=randomUUID(),o={id:i,fireAt:r,recipient:s.recipient,payload:s};return await this.persist(o),this.arm(o),{id:i,cancel:()=>{this.cancel(i);}}}async loadPending(){let e=this.store.listScheduledJobs;if(!e){for(let r of this.memory.values())this.timers.has(r.id)||this.arm(r);return}let t;try{t=await e.call(this.store);}catch(r){this.logger?.warn(r,"scheduler loadPending failed");return}for(let r of t)this.timers.has(r.id)||(this.memory.set(r.id,r),this.arm(r));}dispose(){for(let e of this.timers.values())this.timer.clear(e);this.timers.clear();}cancel(e){let t=this.timers.get(e);t!==void 0&&(this.timer.clear(t),this.timers.delete(e)),this.memory.delete(e),this.remove(e);}arm(e){let t=Math.max(0,e.fireAt-this.now()),r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),Ji(e.payload))try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed; retaining job for retry");return}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,c)=>{if(r+=1,r>1)throw new O("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=c?{recipient:o,content:a,options:c}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new O("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=V.create(s,"");try{await e(i);}catch(o){throw o instanceof O?o:new O("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new O("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function ur(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((c,d)=>Number(d.messageTimestamp??0)-Number(c.messageTimestamp??0));for(let c=0;c<a.length;c+=1){let d=a[c],l=Number(d.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&c>=e.maxPerChat;(u||w)&&(await n.deleteMessage(d.key),r+=1);}}return r}var Fe=class{store;options;logger;now;timer;running=false;warnedUnsupported=false;disabled=false;constructor(e){this.store=e.store,this.options=e.options,this.logger=e.logger,this.now=e.now??Date.now;}get active(){return this.options.maxAgeMs!==void 0||this.options.maxPerChat!==void 0}buildPruneOptions(){let e={};return this.options.maxAgeMs!==void 0&&(e.olderThan=Math.floor((this.now()-this.options.maxAgeMs)/1e3)),this.options.maxPerChat!==void 0&&(e.maxPerChat=this.options.maxPerChat),typeof this.options.chats=="function"&&(e.chatFilter=this.options.chats),e}async runOnce(){if(!this.active||this.disabled)return 0;let e=this.buildPruneOptions();return typeof this.store.pruneMessages=="function"?this.store.pruneMessages(e):typeof this.store.deleteMessage=="function"?ur(this.store,e):(this.disabled=true,this.warnedUnsupported||(this.warnedUnsupported=true,this.logger?.warn({code:"AUTO_DELETE_UNSUPPORTED"},"autoDelete: store implements neither pruneMessages nor deleteMessage; sweeper disabled")),0)}start(){if(!this.active||this.timer)return;let e=this.options.intervalMs??6e4;this.timer=setInterval(()=>{this.running||(this.running=true,this.runOnce().catch(t=>this.logger?.warn(t,"autoDelete sweep failed")).finally(()=>{this.running=false;}));},e),this.timer.unref?.();}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0);}};var $i={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Gi=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[$i[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},lt=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=Gi(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")}},pr=(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 re="[zaileys]",Vi="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 gr(n){switch(n.kind){case "connecting":return `${re} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${re} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${re} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${re} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${re} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
|
|
12
12
|
${re} ${Vi}`:t}case "disconnect":return n.willReconnect?null:`${re} Disconnected (${n.reason}).`;default:return null}}var mr=false,Hi=["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:"],zi=n=>typeof n[0]=="string"&&Hi.some(e=>n[0].startsWith(e));function fr(){if(mr)return;mr=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{zi(r)||t(...r);};};n("info"),n("warn"),n("error");}var f=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 Zi="./.zaileys/auth",Xi=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),je=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",pt=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??Zi;}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 promises.readFile(i,"utf8");r[s]=JSON.parse(o,BufferJSON.reviver);}catch(o){if(je(o))return;throw new f("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 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(promises.unlink(c).catch(d=>{if(!je(d))throw new f("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,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 promises.unlink(s);}catch(i){if(!je(i))throw new f("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen(),await promises.rm(this.basePath,{recursive:true,force:true});},close:async()=>{this.closed=true;}};creds={readCreds:async()=>{this.assertOpen();try{let e=await promises.readFile(this.credsPath(),"utf8");return JSON.parse(e,BufferJSON.reviver)}catch(e){if(je(e))return;throw new f("STORE_READ_FAILED","failed to read creds.json",{cause:e})}},writeCreds:async e=>{this.assertOpen(),await promises.mkdir(this.basePath,{recursive:true}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await promises.unlink(this.credsPath());}catch(e){if(!je(e))throw new f("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return We.join(this.basePath,"creds.json")}signalDir(e){return We.join(this.basePath,"signal",String(e))}signalPath(e,t){return We.join(this.signalDir(e),`${Xi(t)}.json`)}async atomicWrite(e,t){let r=We.join(We.dirname(e),`tmp-${randomBytes(8).toString("hex")}`);try{await promises.writeFile(r,t,"utf8"),await promises.rename(r,e);}catch(s){throw await promises.unlink(r).catch(()=>{}),new f("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new f("STORE_CLOSED","FileAuthStore is closed")}};function hr(n,e){let t=n.signal,s=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 l of a)d[l]=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 yr(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);},clear:async()=>{await n.clear();}}}var eo=429;function wr(n){if(n===eo)return "rate-limited";switch(n){case DisconnectReason.loggedOut:return "logged-out";case DisconnectReason.forbidden:return "forbidden";case DisconnectReason.connectionLost:return "connection-lost";case DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case DisconnectReason.connectionClosed:return "connection-closed";case DisconnectReason.connectionReplaced:return "connection-replaced";case DisconnectReason.badSession:return "bad-session";case DisconnectReason.unavailableService:return "unavailable-service";case DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Ue(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function mt(n){return n==="rate-limited"}function vr(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function rp(n){return !Ue(n)}var gt={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},to=3e5;function Mr(n={}){let e=n.enabled??gt.enabled,t=n.maxQrAttempts??gt.maxQrAttempts,r=n.maxPairingAttempts??gt.maxPairingAttempts,s=n.pairingCooldownMs??gt.pairingCooldownMs,i=0,o=0,a=0,c=w=>w<=0?0:Math.min(s*w,to);return {evaluate:(w,S)=>{if(!e)return {allowed:true,waitMs:0,attempts:w==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(w==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let v=c(o),C=S-a;return o>0&&C<v?{allowed:false,reason:"cooldown",waitMs:v-C,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(w,S)=>{w==="pairing"?(o+=1,a=S):i+=1;},reset:()=>{i=0,o=0,a=0;},get enabled(){return e},get qrAttempts(){return i},get pairingAttempts(){return o}}}var no=/[\s\-()+]/g;function ro(n){return typeof n!="string"?"":n.replace(no,"")}function so(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=ro(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 Sr(n){let e=so(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 oo(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{io.generate(n,{small:true},t=>e(t));})}async function Ar(n,e=t=>{process.stdout.write(t);}){let t=await oo(n);e(t+`
|
|
13
13
|
`);}var me={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function Pr(n,e){let t=n?.enabled??me.enabled,r=n?.maxAttempts??me.maxAttempts,s=n?.initialDelayMs??me.initialDelayMs,i=n?.maxDelayMs??me.maxDelayMs,o=n?.jitterFactor??me.jitterFactor,a=n?.rateLimitedDelayMs??me.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Ue(w))return null;let S=d+1;if(S>r)return null;if(d=S,mt(w))return {attempt:S,delayMs:a};let v=Math.pow(2,S-1),C=Math.min(i,s*v),y=1+(c()*2-1)*o,p=C*y,m=Math.min(i,Math.max(0,p));return {attempt:S,delayMs:Math.round(m)}},reset:()=>{d=0;},get attempts(){return d}}}var ao={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 Cr(n="idle"){let e=n,t=new Set,r=s=>ao[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 ft=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,ht=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=ft(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(ft(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 l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(ft(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=ft(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new f("STORE_CLOSED","MemoryMessageStore is closed")}};var lo=["silent","fatal","error","warn","info","debug","trace"];function uo(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":lo.includes(e)?e:"silent"}function po(n={}){let e=uo(n.level),t=co({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var Er=["debug","info","warn","error","fatal"];function mo(n){if(n===null||typeof n!="object")return false;for(let e of Er)if(typeof n[e]!="function")return false;return true}function qe(){}function go(n){let e={debug:qe,info:qe,warn:qe,error:qe,fatal:qe};for(let t of Er){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function dn(n,e){return n===void 0?e??po():mo(n)?n:go(n)}var hp=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),br=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 fo=new Set(["offer","ringing"]),ho=new Set(["timeout","reject","accept","terminate"]),kr=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},Tr=n=>typeof n.id!="string"||n.id.length===0||!fo.has(n.status)?null:{kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:kr(n.date),status:n.status},Or=n=>typeof n.id!="string"||n.id.length===0||!ho.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:kr(n.date),status:n.status};var _=n=>typeof n=="string"&&n.length>0,yo=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},Ir=(n,e,t)=>n.filter(r=>_(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return _(i)&&(s.participantAlt=i),_(e)&&(s.authorPn=e),_(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),xr=n=>_(n?.id)?{groupId:n.id,update:yo(n),timestamp:Date.now()}:null,Rr=n=>{if(!_(n?.groupId)||!_(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 _(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},wo=new Set(["add","invite","invite-link"]),vo=new Set(["remove","leave"]),Lr=n=>{if(!_(n?.id)||!wo.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Ir(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 _(n.author)&&(t.by=n.author),t},Nr=n=>{if(!_(n?.id)||!vo.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=Ir(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 _(n.author)&&(t.by=n.author),t};var ge=n=>typeof n!="string"||n.length===0?null:jidNormalizedUser(n),H=n=>typeof n=="string"&&n.length>0?n:void 0,Ao=["@s.whatsapp.net","@c.us"],yt=n=>n.endsWith("@lid"),Dr=n=>Ao.some(e=>n.endsWith(e)),q=(n,e)=>{if(!n)return null;let t=H(n.participant)??n.remoteJid,r=ge(t);if(r===null)return null;let s=H(n.participantAlt)??H(n.remoteJidAlt),i=s!=null?ge(s):null,o=H(n.participantUsername)??H(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(yt),l=c.find(Dr);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=H(e);return u!==void 0&&(a.pushName=u),a},_r=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=H(n.participant),r=H(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=q(s);return o&&(i.sender=o),i},Ke=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 fe=n=>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 Po=["quick_reply","cta_url","cta_call","button_click"],Co=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,Fr=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return q(n.key,e)},Wr=n=>he(n.messageTimestamp)??0,jr=(n,e)=>{if(!J(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}},wt=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},Ur=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return ln(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return ln(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Po.includes(i.name)){let o=jr(i.paramsJson,e.logger);if(!o)return null;let a=wt(o,["id","button_id"]);return a===void 0?null:ln(n,a,wt(o,["display_text"])??null)}return null},ln=(n,e,t)=>{let r=Fr(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Wr(n)};return J(t)&&(s.buttonText=t),s},qr=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return Br(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Co.includes(i.name)){let o=jr(i.paramsJson,e.logger);if(!o)return null;let a=wt(o,["row_id","id"]);return a===void 0?null:Br(n,a,wt(o,["title"])??null)}return null},Br=(n,e,t)=>{let r=Fr(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Wr(n)};return J(t)&&(s.title=t),s};var Eo=new Set(["available","unavailable","composing","recording","paused"]),bo=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,Kr=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},un=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:bo(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},Jr=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"||!Eo.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},Je=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 Gr=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},$r=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},Vr=n=>($r(n).toString(16).padStart(8,"0")+$r(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),Hr=n=>Vr(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),zr=(n,e)=>Vr(`${n??""}|${e}`),Yr=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},Zr=n=>{let e=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"},To=n=>n.trim().endsWith("?"),Oo=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Io=(n,e)=>{if(e.length===0)return false;let t;try{t=jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return jidNormalizedUser(r)===t}catch{return r===n}})},xo=(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)}},Ro=0,Lo=14,No=1,Do=2,vt=n=>n!=null&&typeof n=="object"?n:null,_o=n=>{let e=vt(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false};let t=vt(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof vt(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Lo,isDeleted:r===Ro,isPinned:s===No,isUnPinned:s===Do,isBot:vt(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null}},pn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&fe(e),r=_o(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(jidNormalizedUser(e)):i,a={uniqueId:Hr(n.key),staticId:zr(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderDevice:Zr(n.sender.deviceJid??n.sender.jid),timestamp:Yr(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Gr(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:To(n.text),isPrefix:Oo(n.text,n.prefixes),isTagMe:Io(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isStory:e==="status@broadcast",roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:xo(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var St={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},Qr=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},h=n=>n!=null&&typeof n=="object"?n:null,M=n=>typeof n=="string"&&n.length>0?n:null,z=(...n)=>{for(let e of n){let t=M(e);if(t!=null)return t}return null},Bo=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage"],He=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Bo){let i=h(h(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e},es=n=>{let e=h(n.message);if(e==null)return n;let t=He(e);return t===e?n:{...n,message:t}},Fo=n=>{let t=h(h(h(n.botForwardedMessage)?.message)?.richResponseMessage)??h(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=M(h(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
|
|
14
14
|
`).trim();return i.length>0?i:null},Wo=n=>{let e=h(n.templateMessage),t=h(e?.hydratedTemplate)??h(e?.hydratedFourRowTemplate);return M(t?.hydratedContentText)},jo=n=>z(h(n.pollCreationMessage)?.name,h(n.pollCreationMessageV2)?.name,h(n.pollCreationMessageV3)?.name),Uo=n=>{let e=h(n.locationMessage)??h(n.liveLocationMessage);if(e==null)return null;let t=z(e.name,e.address);if(t!=null){let i=M(e.name),o=M(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},qo=n=>{let e=M(h(n.contactMessage)?.displayName);if(e!=null)return e;let t=h(n.contactsArrayMessage),r=M(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>M(h(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},ts=n=>z(n.conversation,h(n.extendedTextMessage)?.text,Fo(n),M(h(h(n.interactiveMessage)?.body)?.text),h(n.buttonsMessage)?.contentText,h(n.listMessage)?.description,Wo(n),jo(n),Uo(n),qo(n)),Ko=n=>z(h(n.buttonsResponseMessage)?.selectedDisplayText,h(n.buttonsResponseMessage)?.selectedButtonId,h(n.templateButtonReplyMessage)?.selectedDisplayText,h(n.templateButtonReplyMessage)?.selectedId,h(n.listResponseMessage)?.title,h(h(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,h(h(n.interactiveResponseMessage)?.body)?.text),Jo=n=>z(h(n.imageMessage)?.caption,h(n.videoMessage)?.caption,h(n.documentMessage)?.caption,h(n.documentMessage)?.fileName),T=n=>{if(typeof n=="number")return n;let e=he(n);return typeof e=="number"?e:null},$o=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],ns=n=>{let e=h(n.pollCreationMessage)??h(n.pollCreationMessageV2)??h(n.pollCreationMessageV3);if(e!=null){let p=Array.isArray(e.options)?e.options:[];return {type:"poll",name:M(e.name),options:p.map(m=>M(h(m)?.optionName)).filter(m=>m!=null),selectableCount:T(e.selectableOptionsCount)??0}}let t=h(n.contactMessage);if(t!=null)return {type:"contact",displayName:M(t.displayName),vcard:M(t.vcard),contacts:[{displayName:M(t.displayName),vcard:M(t.vcard)}]};let r=h(n.contactsArrayMessage);if(r!=null){let p=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:M(r.displayName),vcard:null,contacts:p.map(m=>({displayName:M(h(m)?.displayName),vcard:M(h(m)?.vcard)}))}}let s=h(n.locationMessage);if(s!=null)return {type:"location",latitude:T(s.degreesLatitude),longitude:T(s.degreesLongitude),name:M(s.name),address:M(s.address),accuracy:T(s.accuracyInMeters),speed:T(s.speedInMps),caption:M(s.comment)};let i=h(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:T(i.degreesLatitude),longitude:T(i.degreesLongitude),name:null,address:null,accuracy:T(i.accuracyInMeters),speed:T(i.speedInMps),caption:M(i.caption)};let o=h(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:T(o.expectedImageCount),expectedVideoCount:T(o.expectedVideoCount)};let a=h(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:M(a.groupJid),groupName:M(a.groupName),inviteCode:M(a.inviteCode),caption:M(a.caption),expiresAt:T(a.inviteExpiration)};let c=h(h(n.productMessage)?.product);if(h(n.productMessage)!=null){let p=M(h(n.productMessage)?.businessOwnerJid),m=T(c?.priceAmount1000);return {type:"product",productId:M(c?.productId),title:M(c?.title),description:M(c?.description),price:m!=null?m/1e3:null,currency:M(c?.currencyCode),retailerId:M(c?.retailerId),url:M(c?.url),businessOwnerId:p}}let d=h(n.orderMessage);if(d!=null){let p=T(d.totalAmount1000),m={1:"inquiry",2:"accepted",3:"declined"},A=d.status;return {type:"order",orderId:M(d.orderId),title:M(d.orderTitle),itemCount:T(d.itemCount),total:p!=null?p/1e3:null,currency:M(d.totalCurrencyCode),status:typeof A=="number"?m[A]??null:M(A),message:M(d.message)}}let l=h(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||h(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||h(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let p=h(l.node),m=T(p?.amount1000),A=h(p?.noteMessage);return {type:"payment",kind:l.kind,amount:m!=null?m/1e3:null,currency:M(p?.currencyCodeIso4217),note:z(A?.conversation,h(A?.extendedTextMessage)?.text),expiresAt:T(p?.expiryTimestamp)}}let u=h(n.eventMessage);if(u!=null){let p=h(u.location);return {type:"event",name:M(u.name),description:M(u.description),location:p!=null?z(p.name,p.address):null,startTime:T(u.startTime),endTime:T(u.endTime),isCanceled:u.isCanceled===true}}let w=h(n.buttonsMessage);if(w!=null){let p=Array.isArray(w.buttons)?w.buttons:[];return {type:"buttons",contentText:M(w.contentText),footerText:M(w.footerText),buttons:p.map(m=>({id:M(h(m)?.buttonId),text:M(h(h(m)?.buttonText)?.displayText)}))}}let S=h(n.listMessage);if(S!=null){let p=Array.isArray(S.sections)?S.sections:[];return {type:"list",title:M(S.title),description:M(S.description),buttonText:M(S.buttonText),sections:p.map(m=>{let A=Array.isArray(h(m)?.rows)?h(m).rows:[];return {title:M(h(m)?.title),rows:A.map(E=>({id:M(h(E)?.rowId),title:M(h(E)?.title),description:M(h(E)?.description)}))}})}}let v=h(n.interactiveMessage);if(v!=null){let p=h(v.nativeFlowMessage),m=Array.isArray(p?.buttons)?p.buttons:[];return {type:"interactive",title:M(h(v.header)?.title),body:M(h(v.body)?.text),footer:M(h(v.footer)?.text),buttons:m.map(A=>({name:M(h(A)?.name),params:M(h(A)?.buttonParamsJson)}))}}let C=h(n.templateMessage);if(C!=null){let p=h(C.hydratedTemplate)??h(C.hydratedFourRowTemplate),m=Array.isArray(p?.hydratedButtons)?p.hydratedButtons:[];return {type:"template",text:M(p?.hydratedContentText),buttons:m.map(A=>{let E=h(A),de=h(E?.quickReplyButton)??h(E?.urlButton)??h(E?.callButton);return {id:M(de?.id),text:M(de?.displayText)}})}}let y=h(n.extendedTextMessage);if(y!=null){let p=z(y.canonicalUrl,y.matchedText),m=M(y.title),A=M(y.description);if(p!=null&&(m!=null||A!=null))return {type:"link",url:p,title:m,description:A}}return null};var Ge=n=>{let e=h(n.message);if(e==null)return null;let t=He(e);return ts(t)??Ko(t)??Jo(t)},At=n=>{let e=h(es(n).message);if(e==null)return null;let t=h(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(St)){let s=e[r];if(s!=null&&typeof s=="object"){let i=s.contextInfo;if(i!=null)return i}}return null},Go=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[St[e]];return r==null||typeof r!="object"?null:r},Vo=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(St)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},Ho=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,se=n=>{let e=h(n);if(e==null)return "text";let t=He(e);for(let r of Object.values(St))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of $o)if(t[r]!=null)return s;return "text"},zo=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},Yo=async(n,e,t,r,s)=>{try{if(n==null||n.quotedMessage==null)return null;let i=n.stanzaId;if(typeof i!="string"||i.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let v=await e.resolveQuoted(i,t);if(v!=null&&v.message!=null){let C=Ge(v)??"",y=ie(v,e,se(v.message),C,Ve(v,e),s);if(y!==null)return y}}let o=_r(n);if(o===null||typeof o.key.id!="string"||o.key.id.length===0||(t.length>0&&(o.key.remoteJid=t),typeof o.key.remoteJid!="string"||o.key.remoteJid.length===0))return null;let a=o.key.participant,c=typeof a=="string"&&(e.selfJid.length>0&&Mt(a,e.selfJid)||e.selfLid!=null&&Mt(a,e.selfLid)),d=fe(t),l=o.sender?.pushName;c?(o.key.fromMe=!0,e.selfJid.length>0&&(o.key.participant=e.selfJid),e.selfLid!=null&&(o.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&(!d||zo(o.sender,r))&&(r.pn!=null&&(o.key.participant=r.pn),r.lid!=null&&(o.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,w=Object.assign({key:o.key,message:u??null},l!=null?{pushName:l}:{}),S=Ge(w)??"";return ie(w,e,se(u),S,Ve(w,e),s)}catch{return null}},rs=n=>Ke(At(n)).mentionedJids,Zo=n=>{try{return jidNormalizedUser(n)}catch{return n}},ss=(n,e)=>n.map(t=>{let r=Zo(t);return e.lidMap?.get(r)??r}),Xr=n=>(n.split("@")[0]??"").split(":")[0]??"",Xo=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Xr(s),Xr(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},ie=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=q(o,n.pushName??void 0);if(a===null)return null;let c=Qr(o);if(c.length===0)return null;let d=At(n),l=fe(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),S=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=Vo(n),C=Ho(n,d),y=e.channelId??"",p=e.receiverId??"",m=e.prefixes??[],A=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),E=e.resolveReceiverName??(()=>Promise.resolve(null)),de=()=>Yo(d,e,c,a,A),Ft=c.length>0?c:a.pn??a.jid,Wt=(Ut,Ks)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(Ft,Ut,Ks,n),jt=Ut=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,Ut),Us=ss(Ke(d).mentionedJids,e),qs=Xo(r,e.lidMap),wn={message:n,key:o,channelId:y,receiverId:p,selfJid:e.selfJid,text:qs,chatType:t,sender:a,mentions:Us,isViewOnce:v,isEphemeral:C,isForwarded:S,isBroadcast:u,isNewsletter:w,prefixes:m,...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:A,resolveReceiverName:E,resolveReplied:de,reply:Wt,react:jt},vn=s!==void 0?{...wn,media:s}:wn;return pn(e.citationConfig!==void 0?{...vn,citationConfig:e.citationConfig}:vn)},Qo=["image","video","audio","document","sticker"],is=(n,e,t)=>{let r=es(n),s=Go(r,e);if(s===null)return null;let i=lt(r,e,t.logger),o=pr(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:T(s.fileLength),ptt:s.ptt===true,buffer:async()=>(await i()).buffer,stream:o}},Ve=(n,e)=>{let t=h(n.message);if(t==null)return;let r=se(n.message);return Qo.includes(r)?is(n,r,e)??void 0:ns(He(t))??void 0},os=(n,e)=>{if(h(n.message)==null)return null;let r=se(n.message),s=Ve(n,e),i=Ge(n)??"";return i===""&&s===void 0?null:ie(n,e,r,i,s)},as=(n,e)=>{let t=h(n.message);if(t==null)return null;let r=He(t),s=ts(r),i=ns(r)??void 0;return s===null&&i===void 0?null:ie(n,e,se(n.message),s??"",i)},ze=(n,e,t)=>{let r=is(e,n,t);return r===null?null:ie(e,t,n,r.caption??"",r)},cs=(n,e)=>ze("image",n,e),ds=(n,e)=>ze("video",n,e),ls=(n,e)=>ze("audio",n,e),us=(n,e)=>ze("document",n,e),ps=(n,e)=>ze("sticker",n,e),Mt=(n,e)=>{try{return jidNormalizedUser(n)===jidNormalizedUser(e)}catch{return n===e}},ms=(n,e)=>{if(n.key==null)return null;let r=At(n),s=Ke(r).mentionedJids;if(s.length===0)return null;let i=ss(s,e);if(!(i.some(u=>Mt(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Mt(u,e.selfLid)))||h(n.message)==null)return null;let c=Ge(n)??"",d=Ve(n,e),l=ie(n,e,se(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},gs=(n,e)=>{let t=n.key;if(t==null)return null;let r=Qr(t);if(r.length===0||!fe(r))return null;let{mentionAll:s}=Ke(At(n));if(!s||h(n.message)==null)return null;let o=Ge(n)??"",a=Ve(n,e),c=ie(n,e,se(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var oe=(n,e)=>{let t=he(n);return t===null?e:t},ea=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
|
|
15
15
|
`)}return ""},ta=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],hs=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=q(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:oe(t.senderTimestampMs,0)}},ys=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=q(n.key,e.pushName);return s===null?null:{key:r,newContent:ea(t.editedMessage),editedAt:oe(n.update.messageTimestamp,0),sender:s}},ws=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=q(n.key,e.pushName);if(s===null)return null;let i=ge(n.key.remoteJid),o=ge(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:oe(n.update.messageTimestamp,0)}},vs=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=q(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;return i?{pollKey:i,selectedOptions:ta(t.vote?.selectedOptions),voter:s,timestamp:oe(t.senderTimestampMs,oe(n.update.messageTimestamp,0))}:null}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],voter:s,timestamp:oe(r.senderTimestampMs,oe(n.update.messageTimestamp,0))}:null}return null};var Pt=n=>Array.isArray(n)?n:[],na=3e3,ra=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),sa=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function Ss(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let p=s.get(y);if(p!==void 0)return p;let m=t.groupMetadata;if(m==null)return Promise.resolve(null);let A=m(y).then(E=>E?.subject??null).catch(()=>null);return s.set(y,A),A}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid},d=(y,p)=>{let m=(...A)=>{try{p(A[0]);}catch(E){t.logger?.warn(E,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,m),r.push(()=>e.ev.off(y,m));},l=(y,p)=>{v(()=>os(y,p),m=>n.emit("message",m)),v(()=>as(y,p),m=>n.emit("text",m)),v(()=>cs(y,p),m=>n.emit("image",m)),v(()=>ds(y,p),m=>n.emit("video",m)),v(()=>ls(y,p),m=>n.emit("audio",m)),v(()=>us(y,p),m=>n.emit("document",m)),v(()=>ps(y,p),m=>n.emit("sticker",m)),v(()=>ms(y,p),m=>n.emit("mention",m)),v(()=>gs(y,p),m=>n.emit("mention-all",m)),v(()=>Ur(y,a),m=>n.emit("button-click",m)),v(()=>qr(y,a),m=>n.emit("list-select",m));},u=y=>{if(typeof y!="string"||y.length===0)return null;let p;try{p=jidNormalizedUser(y);}catch{p=y;}return yt(p)?p:null},w=y=>{let p=new Set;for(let m of [y.key?.participant,y.key?.remoteJid,t.selfJid,...rs(y)]){let A=u(m);A!=null&&p.add(A);}return [...p]},S=async y=>{let p=t.resolveLidToPn;if(p==null||y.length===0)return;let m=new Map;return await Promise.all(y.map(async A=>{try{let E=await ra(Promise.resolve(p(A)),na);if(E!=null&&E.length>0)try{m.set(A,jidNormalizedUser(E));}catch{m.set(A,E);}}catch(E){t.logger?.warn(E,"inbound pipeline: lid->pn resolve threw");}})),m.size>0?m:void 0},v=(y,p)=>{let m;try{m=y();}catch(A){t.logger?.warn(A,"inbound pipeline: decoder threw");return}m!=null&&p(m);};d("messages.upsert",y=>{let p=br(y);for(let m of p.messages){if(t.ignoreMe===!0&&m.key?.fromMe===!0)continue;let A=t.resolveLidToPn!=null?w(m):[];if(A.length===0){l(m,o);continue}S(A).then(E=>l(m,E!=null?{...o,lidMap:E}:o)).catch(E=>{t.logger?.warn(E,"inbound pipeline: deferred lid resolve emit failed"),l(m,o);});}}),d("messages.update",y=>{for(let p of Pt(y))v(()=>ys(p,c),m=>n.emit("edit",m)),v(()=>ws(p,c),m=>n.emit("delete",m)),v(()=>vs(p,c),m=>n.emit("poll-vote",m));}),d("messages.reaction",y=>{for(let p of Pt(y))v(()=>hs(p,c),m=>n.emit("reaction",m));}),d("groups.update",y=>{for(let p of Pt(y))v(()=>xr(p),m=>n.emit("group-update",m));}),d("group-participants.update",y=>{let p=y;v(()=>Lr(p),m=>n.emit("group-join",m)),v(()=>Nr(p),m=>n.emit("group-leave",m));}),d("group.member-tag.update",y=>{v(()=>Rr(y),p=>n.emit("member-tag",p));}),d("call",y=>{for(let p of Pt(y))v(()=>Tr(p),m=>n.emit("call-incoming",m)),v(()=>Or(p),m=>n.emit("call-ended",m));}),d("messaging-history.status",y=>{v(()=>Kr(y),p=>n.emit("history-sync",p));}),d("presence.update",y=>{let p=(()=>{try{return Jr(y)}catch(m){return t.logger?.warn(m,"inbound pipeline: decodePresence threw"),[]}})();for(let m of p)n.emit("presence",m);}),d("connection.update",y=>{let p=sa(y);p!==null&&v(()=>un({source:"connection-update",reachoutTimeLock:p}),m=>n.emit("limited",m));}),d("message-capping.update",y=>{v(()=>un({source:"message-capping",capInfo:y}),p=>n.emit("limited",p));}),d("newsletter.reaction",y=>{v(()=>Je({source:"reaction",payload:y}),p=>n.emit("newsletter",p));}),d("newsletter.view",y=>{v(()=>Je({source:"view",payload:y}),p=>n.emit("newsletter",p));}),d("newsletter-participants.update",y=>{v(()=>Je({source:"participants",payload:y}),p=>n.emit("newsletter",p));}),d("newsletter-settings.update",y=>{v(()=>Je({source:"settings",payload:y}),p=>n.emit("newsletter",p));});let C=false;return {detach(){if(!C){C=true;for(let y of r)y();r.length=0;}}}}var Ct=class{inner=new 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=oa,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},oa=Symbol("zaileys.typed-ee.tag");var da="default",la="qr",Ps=6e4,Cs=class extends Ct{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=Cr();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;_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;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;constructor(e={}){super({logger:dn(e.logger)}),this.sessionId=e.sessionId??da,this.logger=dn(e.logger),this.authType=e.authType??la,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&fr(),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new pt({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new ht,this.reconnectStrategy=Pr(this.reconnectOptions),this.authGuard=Mr(e.authGuard),this.operationGuard=an(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ne({perSec:t}):void 0,this.commandPrefixes=ua(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=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=gr(e);t&&process.stderr.write(`${t}
|
|
16
|
-
`);}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 Ce(()=>this._socket,this.operationGuard)}get privacy(){return this._privacy??=new Ee(()=>this._socket)}get newsletter(){return this._newsletter??=new be(()=>this._socket,this.operationGuard)}get community(){return this._community??=new ke(()=>this._socket,this.operationGuard)}get profile(){return this._profile??=new Te(()=>this._socket)}get chat(){return this._chat??=new Oe(()=>this._socket,async e=>{try{return (await this.store.listMessages(e,{limit:1})).filter(r=>r.key!=null).map(r=>({key:r.key,messageTimestamp:Number(r.messageTimestamp??0)}))}catch{return []}})}get contact(){return this._contact??=new Ie(()=>this._socket,e=>Pe(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this._business??=new xe(()=>this._socket)}get presence(){return this._presence??=new _e(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),cn(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Be({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}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";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=hr(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=yr(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:Ps,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a)},i=aa(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{let d=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{d?.(),a();},this.connectReject=u=>{l?.(u),c(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??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.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,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 Re).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=rn({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 x("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(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return Pe(e)?V.create(t,e,void 0,r):V.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return new Ae(this.requireSocket(),e)}async delete(e,t){await Zt(this.requireSocket(),e,t);}async react(e,t){return Xt(this.requireSocket(),e,t)}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return Qt(r,this.store,e,s)}async pin(e,t){return dt(this.requireSocket(),e,true,t)}async unpin(e){return dt(this.requireSocket(),e,false)}async setDisappearing(e,t){let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}resolveRecipient(e){return en(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new g("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.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Sr({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let c=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:c.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:c.code,expiresAt:c.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Ar(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+Ps});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Ss(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.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")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Fe({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Le({client:this,logger:this.logger}),this.pluginLoader=new Ne({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(c=>o[r[c]]!=null);return a===void 0?null:lt(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=pa(e?.error),r=wr(t),s=false;if(vr(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(!Ue(r)&&!this.authExhausted){mt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");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 ua(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function pa(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 Es=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 f("STORE_CLOSED","MemoryAuthStore is closed")}};var Et=null,ma=async()=>{if(Et)return Et;try{return Et=(await import('better-sqlite3')).default,Et}catch(n){throw new f("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},gn="default",ks=500,Ts=n=>Array.from({length:n},()=>"?").join(","),Os=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Is=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(gn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(gn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(gn);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Os(t,ks)){let o=Ts(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 l=c[d];l===null?i.push({type:a,id:d}):l!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Ts(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Os(t,ks))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 f("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new f("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 ma(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new f("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
|
+
`);}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 Ce(()=>this._socket,this.operationGuard)}get privacy(){return this._privacy??=new Ee(()=>this._socket)}get newsletter(){return this._newsletter??=new be(()=>this._socket,this.operationGuard)}get community(){return this._community??=new ke(()=>this._socket,this.operationGuard)}get profile(){return this._profile??=new Te(()=>this._socket)}get chat(){return this._chat??=new Oe(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this._contact??=new Ie(()=>this._socket,e=>Pe(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this._business??=new xe(()=>this._socket)}get presence(){return this._presence??=new _e(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),cn(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new Be({store:this.store,sendSnapshot:e=>this.dispatchSnapshot(e),logger:this.logger,...this.scheduleLimiter?{acquire:()=>this.scheduleLimiter.acquire()}:{}})}async dispatchSnapshot(e){await this.requireSocket().sendMessage(e.recipient,e.content,e.options);}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";e||(this.authGuard.reset(),this.authExhausted=false),this.machine.transition("connecting"),this.connectAttemptSeq+=1,this.pairingRequested=false,this.openedThisRun=false,e||this.logStatus({kind:"connecting",sessionId:this.sessionId}),this.cacheSignal&&!this.cachedSignalWrap&&(this.auth=hr(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=yr(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:Ps,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a)},i=aa(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,c)=>{let d=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{d?.(),a();},this.connectReject=u=>{l?.(u),c(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??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.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,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 Re).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=rn({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 x("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(),r=s=>{this.store.saveMessage(s).catch(i=>this.logger.warn(i,"recordSent failed"));};return Pe(e)?V.create(t,e,void 0,r):V.create(t,e,s=>this.resolveRecipient(s),r)}edit(e){return new Ae(this.requireSocket(),e)}async delete(e,t){await Zt(this.requireSocket(),e,t);}async react(e,t){return Xt(this.requireSocket(),e,t)}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return Qt(r,this.store,e,s)}async pin(e,t){return dt(this.requireSocket(),e,true,t)}async unpin(e){return dt(this.requireSocket(),e,false)}async setDisappearing(e,t){let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}resolveRecipient(e){return en(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new g("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.authExhausted)return;if(this.authType==="pairing"&&this.phoneNumber){if(this.pairingRequested)return;let s=Date.now(),i=this.authGuard.evaluate("pairing",s);if(!i.allowed){i.reason==="budget-exhausted"&&this.handleAuthExhausted("pairing",i.attempts,i.max);return}this.pairingRequested=true,this.authGuard.record("pairing",s),this.machine.canTransition("pairing-pending")&&this.machine.transition("pairing-pending");try{let o=Sr({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let c=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:c.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:c.code,expiresAt:c.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Ar(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+Ps});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Ss(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.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")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Fe({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Le({client:this,logger:this.logger}),this.pluginLoader=new Ne({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(c=>o[r[c]]!=null);return a===void 0?null:lt(i,a,this.logger)()}return null}async lookupQuoted(e,t){for(let r of [false,true])try{let s=await this.store.getMessage({id:e,remoteJid:t,fromMe:r});if(s!=null)return s}catch{continue}return null}async handleClose(e){this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands();let t=pa(e?.error),r=wr(t),s=false;if(vr(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(!Ue(r)&&!this.authExhausted){mt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");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 ua(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function pa(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 Es=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 f("STORE_CLOSED","MemoryAuthStore is closed")}};var Et=null,ma=async()=>{if(Et)return Et;try{return Et=(await import('better-sqlite3')).default,Et}catch(n){throw new f("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},gn="default",ks=500,Ts=n=>Array.from({length:n},()=>"?").join(","),Os=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Is=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(gn);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(gn,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(gn);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Os(t,ks)){let o=Ts(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 l=c[d];l===null?i.push({type:a,id:d}):l!==void 0&&s.push({type:a,id:d,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Ts(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Os(t,ks))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 f("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new f("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 ma(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new f("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;
|
|
17
17
|
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 f("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,BufferJSON.replacer),"utf8")}catch(t){throw new f("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,BufferJSON.reviver)}catch(t){throw new f("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var kt,ga=async()=>(kt||(kt=import('pg').catch(n=>{throw kt=void 0,new f("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),kt),fa="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",ha="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",xs=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 f("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new f("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 f("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 ga(),r=t.Pool??t.default?.Pool;if(!r)throw new f("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(fa),await e.query(ha);}catch(t){throw new f("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"),BufferJSON.reviver);}return s}catch(i){throw i instanceof f?i:new f("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,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 f("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 f("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 f("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,BufferJSON.reviver)}catch(t){throw t instanceof f?t:new f("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,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 f("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 f("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var ya="zaileys",wa=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],va=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Rs=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new f("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new f("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??ya,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,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),l=this.indexKey(i);c===null?(r.del(d),r.sRem(l,a)):c!==void 0&&(r.set(d,JSON.stringify(c,BufferJSON.replacer)),r.sAdd(l,a)),s+=1;}}s!==0&&await this.runWrite(()=>r.exec());},delete:async(e,t)=>{if(this.assertOpen(),t.length===0)return;let s=(await this.ensureReady()).multi();for(let i of t)s.del(this.signalKey(e,i)),s.sRem(this.indexKey(e),i);await this.runWrite(()=>s.exec());},clear:async()=>{this.assertOpen();let e=await this.ensureReady(),t=e.multi();for(let r of wa){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,BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,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 f("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 va(r)?new f("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new f("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 f("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 f("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new f("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 f("STORE_CLOSED","RedisAuthStore is closed")}};var Ma="zaileys",Ye={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Sa=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},ye=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new f("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new f("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??Ma,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(Ye.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(Ye.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(Ye.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(Ye.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(Ye.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 Sa(r)?new f("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new f("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 f("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new f("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new f("STORE_CLOSED","Convex store is closed")}};var It="creds",Aa="signal:",Ze=(n,e)=>`${Aa}${n}:${e}`,Ls=class{creds;signal;kv;constructor(e){this.kv=new ye(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([It])).get(It);return s===void 0?void 0:JSON.parse(s,BufferJSON.reviver)},async writeCreds(r){await t.set([{key:It,value:JSON.stringify(r,BufferJSON.replacer)}]);},async deleteCreds(){await t.del([It]);}},this.signal={async read(r,s){let i=s.map(c=>Ze(r,c)),o=await t.get(i),a={};for(let c of s){let d=o.get(Ze(r,c));a[c]=d===void 0?void 0:JSON.parse(d,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(Ze(o,c)):s.push({key:Ze(o,c),value:JSON.stringify(d,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=>Ze(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var xt=null,Pa=async()=>{if(xt)return xt;try{return xt=(await import('better-sqlite3')).default,xt}catch(n){throw new f("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Rt=n=>{try{return Buffer.from(JSON.stringify(n,BufferJSON.replacer),"utf8")}catch(e){throw new f("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},ae=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,BufferJSON.reviver)}catch(e){throw new f("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ns=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,Rt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?ae(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=>ae(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,Rt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?ae(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>ae(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,Rt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?ae(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>ae(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,Rt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?ae(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
18
18
|
SELECT rowid FROM (
|
|
19
19
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|