zaileys 4.14.0 → 4.14.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 +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -18,7 +18,7 @@ VERSION:3.0
|
|
|
18
18
|
FN:${i}${o?`
|
|
19
19
|
${o}`:""}
|
|
20
20
|
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Qd=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:X(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Xd=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Hd(n)??zd(n)??Yd(n)??Zd(n);if(t===null)return null;let r=Qd(t,n),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:X(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},ec=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?X(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},tc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Ut(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:X(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},nc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Ut(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:X(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},rc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=X(n.from),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ki(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=Vd(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=rc(l,c);if(u){t.push(u);continue}let w=tc(l,c);if(w){i.push(w);continue}let M=nc(l,c);if(M){o.push(M);continue}let v=Xd(l,c);v&&e.push(v);}for(let l of c.statuses??[]){let u=ec(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Ei=3,Fn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Ti(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Fn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Ei)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Ei} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=Fn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?Fn(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ee=class{ev=new events.EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=jt(e);}get apiVersion(){return this.options.apiVersion??Ft}get baseUrl(){return this.options.baseUrl??Wn}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Ti(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...V(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...V(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...V(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new C("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new C("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await ge(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ki(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=bi(e,t,r);if(s===null){let d=Ci(t);if(d){let c=await Ai(this.graph,this.options.phoneNumberId,d);s={...V(e,d.kind,r),[d.kind]:Pi(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ut=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=jt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var ac=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=crypto.createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:crypto.timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function jn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!ac(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var uc="default",pc="qr",xi=6e4,mc=2,gc=3e3,fc="29829202653362039",hc=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},Oi=class extends Wt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zs();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;chatExpiration=new Map;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:_n(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Bn(e.cloud):void 0,this.sessionId=e.sessionId??uc,this.logger=_n(e.logger),this.authType=e.authType??pc,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&js(),this.on("message",r=>this.rememberChatExpiration(r)),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ot({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Lt,this.reconnectStrategy=Hs(this.reconnectOptions),this.authGuard=Gs(e.authGuard),this.operationGuard=Tn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ae({perSec:t}):void 0,this.commandPrefixes=yc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ze(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&ye.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof dc.fetchLatestBaileysVersion!="function"?Promise.resolve():(this.versionWarming=dc.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=Fs(e);t&&process.stderr.write(`${t}
|
|
21
|
-
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({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._provider==="cloud")return this.connectCloud();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=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??dc.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();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 $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({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),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,client:this,send:s=>this.send(s??t.roomId??t.senderId),reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r,s):Y.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.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=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:dc.S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(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=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(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 Ri=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 h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=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(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))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 h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("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 vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("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;
|
|
21
|
+
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({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._provider==="cloud")return this.connectCloud();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=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc__default.default(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(u);};});return this.auth.creds.readCreds().then(a=>{this.credsLoadedAtConnect=!!a,Object.assign(t,a??dc.initAuthCreds());}).catch(a=>{this.rejectPendingConnect(a instanceof Error?a:new Error(String(a)));}),o}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();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 $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("message",r),()=>this.off("message",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,client:this,send:s=>this.send(s??t.roomId??t.senderId),reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r,s):Y.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.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=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:dc.S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(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=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(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 Ri=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 h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=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(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))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 h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("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 vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
22
22
|
CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new h("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,dc.BufferJSON.replacer),"utf8")}catch(t){throw new h("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,dc.BufferJSON.reviver)}catch(t){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var $t,Mc=async()=>($t||($t=import('pg').then(n=>n).catch(n=>{throw $t=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),$t),Sc="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",bc="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",Wi=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 h("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("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 h("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 Mc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(Sc),await e.query(bc);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,d)=>`$${d+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let d=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(d.toString("utf8"),dc.BufferJSON.reviver);}return s}catch(i){throw i instanceof h?i:new h("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a];if(d===null)r.push({kind:"delete",type:String(i),id:a});else if(d!==void 0){let c=Buffer.from(JSON.stringify(d,dc.BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:c});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new h("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 h("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 h("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,dc.BufferJSON.reviver)}catch(t){throw t instanceof h?t:new h("STORE_READ_FAILED","failed to read creds",{cause:t})}},writeCreds:async e=>{let t=await this.ensureReady();try{let r=JSON.stringify(e,dc.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 h("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 h("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var Cc="zaileys",Ac=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Pc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Fi=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??Cc,this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let d=i[a];d!=null&&(o[t[a]]=JSON.parse(d,dc.BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a],c=this.signalKey(i,a),l=this.indexKey(i);d===null?(r.del(c),r.sRem(l,a)):d!==void 0&&(r.set(c,JSON.stringify(d,dc.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 Ac){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,dc.BufferJSON.reviver)},writeCreds:async e=>{this.assertOpen();let t=await this.ensureReady();await this.runWrite(()=>t.set(this.credsKey(),JSON.stringify(e,dc.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 h("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 Pc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("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 h("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 h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("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 h("STORE_CLOSED","RedisAuthStore is closed")}};var kc="zaileys",pt={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Ec=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Te=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??kc,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(pt.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(pt.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(pt.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.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(pt.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 Ec(r)?new h("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new h("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 h("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","Convex store is closed")}};var Vt="creds",Tc="signal:",mt=(n,e)=>`${Tc}${n}:${e}`,ji=class{creds;signal;kv;constructor(e){this.kv=new Te(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([Vt])).get(Vt);return s===void 0?void 0:JSON.parse(s,dc.BufferJSON.reviver)},async writeCreds(r){await t.set([{key:Vt,value:JSON.stringify(r,dc.BufferJSON.replacer)}]);},async deleteCreds(){await t.del([Vt]);}},this.signal={async read(r,s){let i=s.map(d=>mt(r,d)),o=await t.get(i),a={};for(let d of s){let c=o.get(mt(r,d));a[d]=c===void 0?void 0:JSON.parse(c,dc.BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let d of Object.keys(a)){let c=a[d];c==null?i.push(mt(o,d)):s.push({key:mt(o,d),value:JSON.stringify(c,dc.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=>mt(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var Ht=null,Ic=async()=>{if(Ht)return Ht;try{return Ht=(await import('better-sqlite3')).default,Ht}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},zt=n=>{try{return Buffer.from(JSON.stringify(n,dc.BufferJSON.replacer),"utf8")}catch(e){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},pe=n=>{try{let e=Buffer.isBuffer(n)?n.toString("utf8"):Buffer.from(n).toString("utf8");return JSON.parse(e,dc.BufferJSON.reviver)}catch(e){throw new h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ui=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,zt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?pe(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=>pe(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,zt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?pe(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>pe(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,zt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?pe(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>pe(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,zt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?pe(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
23
23
|
SELECT rowid FROM (
|
|
24
24
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|
package/dist/index.mjs
CHANGED
|
@@ -18,7 +18,7 @@ VERSION:3.0
|
|
|
18
18
|
FN:${i}${o?`
|
|
19
19
|
${o}`:""}
|
|
20
20
|
END:VCARD`}}),r=t.length===1?t[0]:void 0;return r?{contactMessage:r}:{contactsArrayMessage:{displayName:`${t.length} contacts`,contacts:t}}},Qd=(n,e)=>{let t=e.context;if(!t?.id)return n;let r={stanzaId:t.id,...t.from?{participant:X(t.from)}:{},quotedMessage:{}};if(typeof n.conversation=="string")return {extendedTextMessage:{text:n.conversation,contextInfo:r}};let s=Object.keys(n)[0];return s&&(n[s].contextInfo=r),n},Xd=(n,e)=>{if(!n.id||!n.from)return null;let t=n.type==="text"&&typeof n.text?.body=="string"?{conversation:n.text.body}:Hd(n)??zd(n)??Yd(n)??Zd(n);if(t===null)return null;let r=Qd(t,n),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:X(n.from),fromMe:false},message:r,messageTimestamp:Number(n.timestamp??0)||0,...s?{pushName:s}:{}}},ec=n=>{let e=n.id,t=n.status;if(typeof e!="string"||typeof t!="string"||t!=="sent"&&t!=="delivered"&&t!=="read"&&t!=="failed")return null;let r=typeof n.recipient_id=="string"?X(n.recipient_id):"",s=n.conversation,i=n.errors;return {id:e,status:t,recipientId:r,timestamp:Number(n.timestamp??0)||0,...s?.id?{conversationId:s.id}:{},...i?.[0]?{error:i[0]}:{}}},tc=(n,e)=>{let t=n.interactive;if(n.type!=="interactive"||t?.type!=="nfm_reply"||!n.id||!n.from)return null;let r=t.nfm_reply,s={};try{s=JSON.parse(r?.response_json??"{}");}catch{s={};}let i=Ut(e,n.from);return {id:n.id,name:r?.name??"flow",...r?.body?{body:r.body}:{},response:s,senderId:X(n.from),...i?{senderName:i}:{},timestamp:Number(n.timestamp??0)||0}},nc=(n,e)=>{let t=n.order;if(n.type!=="order"||!t||!n.id||!n.from)return null;let r=Ut(e,n.from);return {id:n.id,catalogId:t.catalog_id??"",...t.text?{text:t.text}:{},items:(t.product_items??[]).map(s=>({productRetailerId:s.product_retailer_id??"",quantity:s.quantity??0,price:s.item_price??0,currency:s.currency??""})),senderId:X(n.from),...r?{senderName:r}:{},timestamp:Number(n.timestamp??0)||0}},rc=(n,e)=>{let t=n.reaction;if(n.type!=="reaction"||!n.id||!n.from||typeof t?.message_id!="string")return null;let r=X(n.from),s=Ut(e,n.from);return {key:{id:n.id,remoteJid:r,fromMe:false},reaction:{key:{id:t.message_id,remoteJid:r,fromMe:false},text:t.emoji??"",senderTimestampMs:(Number(n.timestamp??0)||0)*1e3},...s?{pushName:s}:{}}};function ki(n){let e=[],t=[],r=[],s=[],i=[],o=[];for(let a of n.entry??[])for(let d of a.changes??[]){let c=d.value;if(c){if(d.field==="message_template_status_update"){let l=Vd(c);l&&s.push(l);continue}for(let l of c.messages??[]){let u=rc(l,c);if(u){t.push(u);continue}let w=tc(l,c);if(w){i.push(w);continue}let M=nc(l,c);if(M){o.push(M);continue}let v=Xd(l,c);v&&e.push(v);}for(let l of c.statuses??[]){let u=ec(l);u&&r.push(u);}}}return {messages:e,reactions:t,statuses:r,templateStatuses:s,flowResponses:i,orders:o}}var Ei=3,Fn=n=>{if(!n)return {};try{return JSON.parse(n)}catch{return {}}};function Ti(n){let e=n.interactiveMessage;if(!e)return null;let t=e.nativeFlowMessage?.buttons??[],r=e.body?.text??" ",s=e.footer?.text,i=e.header?.title;if(e.header?.hasMediaAttachment===true)throw new C("NOT_IMPLEMENTED","interactive media headers are not supported on the cloud provider yet");let o={body:{text:r},...s?{footer:{text:s}}:{}},a=t.length===1?t[0]:void 0;if(a?.name==="single_select"){let l=Fn(a.buttonParamsJson);return {type:"list",...i?{header:{type:"text",text:i}}:{},...o,action:{button:l.title??"Select",sections:(l.sections??[]).map(u=>({...u.title?{title:u.title}:{},rows:(u.rows??[]).map(w=>({id:w.id??"",title:w.title??"",description:w.description??""}))}))}}}let d=t.filter(l=>l.name==="quick_reply");if(d.length>0&&d.length===t.length){if(d.length>Ei)throw new C("NOT_IMPLEMENTED",`cloud interactive buttons allow at most ${Ei} reply buttons (got ${d.length})`);return {type:"button",...i?{header:{type:"text",text:i}}:{},...o,action:{buttons:d.map(l=>{let u=Fn(l.buttonParamsJson);return {type:"reply",reply:{id:u.id??"",title:u.display_text??""}}})}}}let c=a&&a.name==="cta_url"?Fn(a.buttonParamsJson):null;if(c){let l=c;return {type:"cta_url",...i?{header:{type:"text",text:i}}:{},...o,action:{name:"cta_url",parameters:{display_text:l.display_text??"",url:l.url??""}}}}throw new C("NOT_IMPLEMENTED","this interactive layout is not supported on the cloud provider yet")}var Ee=class{ev=new EventEmitter;user;options;graph;constructor(e){this.options=e,this.user={id:e.phoneNumberId},this.graph=jt(e);}get apiVersion(){return this.options.apiVersion??Ft}get baseUrl(){return this.options.baseUrl??Wn}url(e){return `${this.baseUrl}/${this.apiVersion}/${e}`}async connect(){let e;try{e=await fetch(this.url(this.options.phoneNumberId),{method:"GET",headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(r){throw new C("REQUEST_FAILED","cloud health-check request failed",{cause:r})}if(e.status===401||e.status===403)throw new C("AUTH",`cloud auth rejected (${e.status}) \u2014 check accessToken/phoneNumberId`);if(!e.ok)throw new C("REQUEST_FAILED",`cloud health-check failed (${e.status})`);let t=await e.json().catch(()=>({}));return {id:t.id??this.options.phoneNumberId,...t.verified_name?{name:t.verified_name}:{}}}async disconnect(){this.ev.removeAllListeners();}relayMessage=async(e,t,r)=>{let s=t;if(s.botForwardedMessage!=null||s.richResponseMessage!=null)throw new C("NOT_IMPLEMENTED","AIRich rich responses (rich: true) are a WhatsApp-Web-only feature and are not supported on the cloud provider. Send the markdown as plain text with send().text(md) \u2014 WhatsApp renders *bold*, _italic_, ~strike~ and ```mono``` natively.");let i=Ti(s);if(i===null)throw new C("NOT_IMPLEMENTED","this relay content is not supported on the cloud provider");let o={...V(e,"interactive"),interactive:i},d=(await this.graph.post(`${this.options.phoneNumberId}/messages`,o)).messages?.[0]?.id;if(d){let c=lt(d,e,{text:""},Date.now());c.message=t,this.ev.emit("messages.upsert",{messages:[c],type:"append"});}return r.messageId};async sendInteractive(e,t){let r={...V(e,"interactive"),interactive:t},i=(await this.graph.post(`${this.options.phoneNumberId}/messages`,r)).messages?.[0]?.id;if(!i)throw new C("REQUEST_FAILED","graph interactive send returned no message id");let o=lt(i,e,{text:""},Date.now());return o.message={interactiveMessage:t},this.ev.emit("messages.upsert",{messages:[o],type:"append"}),o}async sendTemplate(e,t,r,s){let i={...V(e,"template"),template:{name:t,language:{code:r},...s!==void 0?{components:s}:{}}},a=(await this.graph.post(`${this.options.phoneNumberId}/messages`,i)).messages?.[0]?.id;if(!a)throw new C("REQUEST_FAILED","graph template send returned no message id");let d=lt(a,e,{text:`template:${t}`},Date.now());return this.ev.emit("messages.upsert",{messages:[d],type:"append"}),d}async markRead(e,t){await this.graph.post(`${this.options.phoneNumberId}/messages`,{messaging_product:"whatsapp",status:"read",message_id:e,...t?.typing===true?{typing_indicator:{type:"text"}}:{}});}async downloadMedia(e){let t=await this.graph.get(e);if(!t.url)return null;let r;try{r=await fetch(t.url,{headers:{Authorization:`Bearer ${this.options.accessToken}`}});}catch(o){throw new C("REQUEST_FAILED","media download failed",{cause:o})}if(!r.ok)throw new C("REQUEST_FAILED",`media download failed (${r.status})`);let s=Buffer.from(await r.arrayBuffer()),i=t.mime_type??await ge(s);return {buffer:s,mime:i,size:s.byteLength}}ingest(e){let{messages:t,reactions:r,statuses:s,templateStatuses:i,flowResponses:o,orders:a}=ki(e);t.length>0&&this.ev.emit("messages.upsert",{messages:t,type:"notify"}),r.length>0&&this.ev.emit("messages.reaction",r);for(let d of s)this.ev.emit("cloud.status",d);for(let d of i)this.ev.emit("cloud.template-status",d);for(let d of o)this.ev.emit("cloud.flow-response",d);for(let d of a)this.ev.emit("cloud.order",d);}async sendMessage(e,t,r){let s=bi(e,t,r);if(s===null){let d=Ci(t);if(d){let c=await Ai(this.graph,this.options.phoneNumberId,d);s={...V(e,d.kind,r),[d.kind]:Pi(d,c)};}}if(s===null)throw new C("NOT_IMPLEMENTED","this content type is not supported on the cloud provider yet");let o=(await this.graph.post(`${this.options.phoneNumberId}/messages`,s)).messages?.[0]?.id;if(!o)throw new C("REQUEST_FAILED","graph send returned no message id");let a=lt(o,e,t,Date.now());return this.ev.emit("messages.upsert",{messages:[a],type:"append"}),a}};var ut=class{graph;options;getTransport;constructor(e,t){this.options=e,this.graph=jt(e),this.getTransport=t;}requireWaba(){let e=this.options.wabaId;if(!e)throw new C("CONFIG","this operation needs cloud.wabaId (WhatsApp Business Account id)");return e}async info(){return this.graph.get(`${this.options.phoneNumberId}?fields=id,display_phone_number,verified_name,quality_rating,throughput,code_verification_status,platform_type`)}async phoneNumbers(){let e=this.requireWaba();return (await this.graph.get(`${e}/phone_numbers?fields=id,display_phone_number,verified_name,quality_rating`)).data??[]}async sendAddressRequest(e,t){return (await this.getTransport().sendInteractive(e,{type:"address_message",body:{text:t.bodyText},action:{name:"address_message",parameters:{country:t.countryIso,...t.values?{values:t.values}:{}}}})).key}commerce={catalogs:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/product_catalogs?fields=id,name`)).data??[]},products:async(e,t=50)=>(await this.graph.get(`${e}/products?fields=id,retailer_id,name,price,availability&limit=${t}`)).data??[],sendProduct:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product",...t.bodyText?{body:{text:t.bodyText}}:{},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,product_retailer_id:t.retailerId}})).key,sendProductList:async(e,t)=>(await this.getTransport().sendInteractive(e,{type:"product_list",header:{type:"text",text:t.headerText},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{catalog_id:t.catalogId,sections:t.sections.map(s=>({title:s.title,product_items:s.productIds.map(i=>({product_retailer_id:i}))}))}})).key};templates={list:async e=>{let t=this.requireWaba(),r=new URLSearchParams;e?.status&&r.set("status",e.status),e?.limit&&r.set("limit",String(e.limit));let s=r.size>0?`?${r.toString()}`:"";return (await this.graph.get(`${t}/message_templates${s}`)).data??[]},get:async e=>{let t="id,name,status,category,language,components,quality_score";if(/^\d+$/.test(e)){let i=await this.graph.get(`${e}?fields=${t}`);return i.id?i:null}let r=this.requireWaba();return (await this.graph.get(`${r}/message_templates?name=${encodeURIComponent(e)}&fields=${t}`)).data?.[0]??null},create:async e=>{let t=this.requireWaba();return this.graph.post(`${t}/message_templates`,e)},delete:async(e,t)=>{let r=this.requireWaba(),s=new URLSearchParams({name:e});t&&s.set("hsm_id",t),await this.graph.delete(`${r}/message_templates?${s.toString()}`);}};profile={get:async()=>(await this.graph.get(`${this.options.phoneNumberId}/whatsapp_business_profile?fields=about,address,description,email,websites,vertical`)).data?.[0]??{},update:async e=>{await this.graph.post(`${this.options.phoneNumberId}/whatsapp_business_profile`,{messaging_product:"whatsapp",...e});}};flows={list:async()=>{let e=this.requireWaba();return (await this.graph.get(`${e}/flows`)).data??[]},send:async(e,t)=>{if(!t.flowId&&!t.flowName)throw new C("CONFIG","flows.send needs flowId or flowName");return (await this.getTransport().sendInteractive(e,{type:"flow",...t.headerText?{header:{type:"text",text:t.headerText}}:{},body:{text:t.bodyText},...t.footerText?{footer:{text:t.footerText}}:{},action:{name:"flow",parameters:{flow_message_version:"3",...t.flowId?{flow_id:t.flowId}:{},...t.flowName?{flow_name:t.flowName}:{},flow_cta:t.cta,...t.flowToken?{flow_token:t.flowToken}:{},...t.mode?{mode:t.mode}:{},flow_action:t.action??"navigate",flow_action_payload:{screen:t.screen,...t.data?{data:t.data}:{}}}}})).key}};blocklist={add:async e=>{await this.graph.post(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},remove:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/block_users`,{messaging_product:"whatsapp",block_users:e.map(t=>({user:t}))});},list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/block_users`)).data?.[0]?.block_users??[]};qr={create:async(e,t="PNG")=>this.graph.post(`${this.options.phoneNumberId}/message_qrdls`,{prefilled_message:e,generate_qr_image:t}),list:async()=>(await this.graph.get(`${this.options.phoneNumberId}/message_qrdls`)).data??[],delete:async e=>{await this.graph.delete(`${this.options.phoneNumberId}/message_qrdls/${e}`);}};analytics={conversations:async e=>{let t=this.requireWaba(),r=`conversation_analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAILY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.conversation_analytics??s},messages:async e=>{let t=this.requireWaba(),r=`analytics.start(${e.start}).end(${e.end}).granularity(${e.granularity??"DAY"})`,s=await this.graph.get(`${t}?fields=${encodeURIComponent(r)}`);return s.analytics??s}};phone={register:async e=>{await this.graph.post(`${this.options.phoneNumberId}/register`,{messaging_product:"whatsapp",pin:e});},deregister:async()=>{await this.graph.post(`${this.options.phoneNumberId}/deregister`,{});},requestCode:async(e,t="en_US")=>{await this.graph.post(`${this.options.phoneNumberId}/request_code`,{code_method:e,language:t});},verifyCode:async e=>{await this.graph.post(`${this.options.phoneNumberId}/verify_code`,{code:e});}}};var ac=(n,e,t)=>{if(!t||!t.startsWith("sha256="))return false;let r=createHmac("sha256",n).update(e).digest("hex"),s=t.slice(7);return s.length!==r.length?false:timingSafeEqual(Buffer.from(s,"utf8"),Buffer.from(r,"utf8"))};function jn(n){return async e=>{if(e.method==="GET"){let s=new URL(e.url),i=s.searchParams.get("hub.mode"),o=s.searchParams.get("hub.verify_token"),a=s.searchParams.get("hub.challenge")??"";return i==="subscribe"&&n.verifyToken!==void 0&&o===n.verifyToken?new Response(a,{status:200}):new Response("forbidden",{status:403})}if(e.method!=="POST")return new Response("method not allowed",{status:405});let t=await e.text();if(n.appSecret!==void 0&&!ac(n.appSecret,t,e.headers.get("x-hub-signature-256")))return new Response("invalid signature",{status:401});let r;try{r=JSON.parse(t);}catch{return new Response("malformed body",{status:400})}try{n.onPayload(r);}catch{}return new Response("OK",{status:200})}}var uc="default",pc="qr",xi=6e4,mc=2,gc=3e3,fc="29829202653362039",hc=n=>{let e=n?.content;if(!Array.isArray(e))return [];let t=e.find(o=>o?.tag==="result")?.content;if(!Buffer.isBuffer(t))return [];let r;try{r=JSON.parse(t.toString());}catch{return []}let s=r?.data?.xwa2_fetch_wa_users;if(!Array.isArray(s))return [];let i=[];for(let o of s){let a=o?.jid,d=o?.username_info?.username;typeof a=="string"&&typeof d=="string"&&d.length>0&&i.push({jid:a,username:d});}return i},Oi=class extends Wt{sessionId;auth;store;logger;authType;phoneNumber;cacheSignal;qrTerminal;statusLog;reconnectOptions;baileysExtra;machine=zs();reconnectStrategy;authGuard;operationGuard;presenceThrottle;scheduleLimiter;authExhausted=false;chatExpiration=new Map;_socket;reconnectTimer;listenerCleanup=[];inboundHandle;connectResolve;connectReject;pairingRequested=false;cachedSignalWrap=false;creds;credsLoadedAtConnect=false;openedThisRun=false;credsHintShown=false;postOpenLogoutRetries=0;disconnectEmittedFor=0;connectAttemptSeq=0;pendingDisconnectReason;usernameCache=new Map;_group;_privacy;_newsletter;_community;_profile;_chat;_contact;_business;commandRegistry;commandMiddleware=[];commandPrefixes;citationConfig;ignoreMe;commandDispatcher;_presence;_scheduler;autoDeleteOptions;autoRejectCall;autoDeleteSweeper;pluginsOptions;pluginRegistry;pluginLoader;waVersion;versionWarming;_provider;cloudOptions;cloudTransport;cloudRuntimeReady=false;_cloudModule;constructor(e={}){super({logger:_n(e.logger)}),this._provider=e.provider??"baileys",this.cloudOptions=this._provider==="cloud"?Bn(e.cloud):void 0,this.sessionId=e.sessionId??uc,this.logger=_n(e.logger),this.authType=e.authType??pc,this.phoneNumber=e.phoneNumber,this.cacheSignal=e.cacheSignal??true,this.qrTerminal=e.qrTerminal??true,this.statusLog=e.statusLog??true,this.statusLog&&js(),this.on("message",r=>this.rememberChatExpiration(r)),this.reconnectOptions=e.reconnect??{},this.baileysExtra=e.baileys??{},this.auth=e.auth??new Ot({basePath:`./.zaileys/auth/${this.sessionId}`}),this.store=e.store??new Lt,this.reconnectStrategy=Hs(this.reconnectOptions),this.authGuard=Gs(e.authGuard),this.operationGuard=Tn(e.operationGuard),this.presenceThrottle=e.presence;let t=e.scheduleRateLimitPerSec??1;this.scheduleLimiter=t>0?new ae({perSec:t}):void 0,this.commandPrefixes=yc(e.commandPrefix),this.citationConfig=e.citation,this.ignoreMe=e.ignoreMe??true,this.autoRejectCall=new Ze(()=>this._socket,e.autoRejectCall===true?{enabled:true}:e.autoRejectCall===false||e.autoRejectCall===void 0?{}:e.autoRejectCall,this.logger),this._provider==="baileys"&&this.autoRejectCall.enabled&&this.on("call-incoming",r=>{this.autoRejectCall.handle(r);}),this.autoDeleteOptions=e.autoDelete===false?void 0:{maxAgeMs:720*60*60*1e3,...e.autoDelete},this.pluginsOptions=e.plugins,e.sticker&&ye.setDefaultMetadata(e.sticker),this.attachEmitterLogger(),(e.autoConnect??true)&&queueMicrotask(()=>{this.machine.state==="idle"&&this.warmVersion().finally(()=>{if(this.machine.state==="idle")try{this.connect().catch(r=>this.emitAutoConnectError(r));}catch(r){this.emitAutoConnectError(r);}});});}warmVersion(){if(this._provider==="cloud"||this.waVersion)return Promise.resolve();if(this.versionWarming)return this.versionWarming;try{return typeof 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=Fs(e);t&&process.stderr.write(`${t}
|
|
21
|
-
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({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._provider==="cloud")return this.connectCloud();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=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(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}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();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 $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({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),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,client:this,send:s=>this.send(s??t.roomId??t.senderId),reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r,s):Y.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.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=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(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=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(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 Ri=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 h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=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(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))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 h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("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 vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("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;
|
|
21
|
+
`);}resolveMe(){let e=this._socket?.user;if(e&&typeof e.id=="string"&&e.id.length>0)return e;let t=this.creds?.me;return t&&typeof t.id=="string"&&t.id.length>0?t:{id:""}}get provider(){return this._provider}get state(){return this.machine.state}get socket(){return this._socket}assertWebProvider(e){if(this._provider==="cloud")throw new ct(e)}get group(){return this.assertWebProvider("group"),this._group??=new De(()=>this._socket,this.operationGuard)}get privacy(){return this.assertWebProvider("privacy"),this._privacy??=new Be(()=>this._socket)}get newsletter(){return this.assertWebProvider("newsletter"),this._newsletter??=new We(()=>this._socket,this.operationGuard)}get community(){return this.assertWebProvider("community"),this._community??=new Fe(()=>this._socket,this.operationGuard)}get profile(){return this.assertWebProvider("profile"),this._profile??=new je(()=>this._socket)}get chat(){return this.assertWebProvider("chat"),this._chat??=new Ue(()=>this._socket,async e=>{try{let t=await this.store.listMessages(e,{limit:1}),r=s=>{if(typeof s=="number")return s;if(s!=null&&typeof s.toNumber=="function")return s.toNumber();let i=Number(s??0);return Number.isFinite(i)?i:0};return t.filter(s=>s.key!=null).map(s=>({key:s.key,messageTimestamp:r(s.messageTimestamp)})).filter(s=>s.messageTimestamp>0)}catch{return []}})}get contact(){return this.assertWebProvider("contact"),this._contact??=new qe(()=>this._socket,e=>Le(e)?e:`${e.replace(/\D/g,"")}@s.whatsapp.net`)}get business(){return this.assertWebProvider("business"),this._business??=new Ke(()=>this._socket)}get presence(){return this.assertWebProvider("presence"),this._presence??=new He(()=>this._socket,this.presenceThrottle)}async broadcast(e,t,r){return this.requireSocket(),In(e,t,{sendTo:s=>this.send(s)},r)}async scheduleAt(e,t){return this.ensureScheduler().scheduleAt(e,t)}ensureScheduler(){return this._scheduler??=new ze({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._provider==="cloud")return this.connectCloud();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=Us(this.auth,{logger:this.logger}),this.cachedSignalWrap=true),this.warmVersion();let t={};this.creds=t;let r=qs(this.auth.signal,this.logger),s={markOnlineOnConnect:false,syncFullHistory:false,qrTimeout:xi,...this.waVersion?{version:this.waVersion}:{},...this.baileysExtra,auth:{creds:t,keys:r},logger:this.logger,getMessage:a=>this.resolveMessageForResend(a),patchMessageBeforeSending:this.patchOutgoing},i=dc(s);this._socket=i,this.store.bind(i),this.wireSocket(i);let o=new Promise((a,d)=>{let c=this.connectResolve,l=this.connectReject;this.connectResolve=()=>{c?.(),a();},this.connectReject=u=>{l?.(u),d(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}ensureCloudRuntime(){let e=this.cloudTransport??=new Ee(this.cloudOptions);return this.cloudRuntimeReady||(this.cloudRuntimeReady=true,this.store.bind(e),this.attachCloudPipeline(e,this.cloudOptions.phoneNumberId)),e}async connectCloud(){if(this.machine.state==="connecting"||this.machine.state==="connected")return;this.machine.transition("connecting"),this.logStatus({kind:"connecting",sessionId:this.sessionId});let e=this.ensureCloudRuntime();try{let t=await e.connect();this.machine.transition("connected"),this.logStatus({kind:"connected",id:t.id}),this.emit("connect",{sessionId:this.sessionId,me:t});}catch(t){throw this.machine.transition("disconnected"),t}}attachCloudPipeline(e,t){let r=t.includes("@")?t:`${t}@s.whatsapp.net`;this.inboundHandle?.detach(),this.inboundHandle=Dn(this,e,{selfJid:r,channelId:this.sessionId,receiverId:r,prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},receiverName:()=>Promise.resolve(null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:()=>Promise.resolve(null),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe}),e.ev.on("cloud.status",s=>{this.emit("message-status",s);}),e.ev.on("cloud.template-status",s=>{this.emit("template-status",s);}),e.ev.on("cloud.flow-response",s=>{this.emit("flow-response",s);}),e.ev.on("cloud.order",s=>{this.emit("order",s);}),this.attachCommandsIfReady();}webhook(){if(this._provider!=="cloud")throw new C("CONFIG","webhook() is only available on the cloud provider");let e=this.cloudOptions;return jn({...e.verifyToken!==void 0?{verifyToken:e.verifyToken}:{},...e.appSecret!==void 0?{appSecret:e.appSecret}:{},onPayload:t=>{this.ensureCloudRuntime().ingest(t);}})}async disconnectCloud(){this.machine.state==="idle"||this.machine.state==="disconnected"||(this.machine.canTransition("disconnecting")&&this.machine.transition("disconnecting"),await this.cloudTransport?.disconnect(),this.machine.transition("disconnected"),this.emit("disconnect",{sessionId:this.sessionId,reason:"unknown",willReconnect:false}));}async disconnect(){if(this._provider==="cloud")return this.disconnectCloud();if(!(this.machine.state==="idle"||this.machine.state==="disconnected")){this.machine.transition("disconnecting"),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.inboundHandle?.detach(),this.inboundHandle=void 0,this.detachCommands(),this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=void 0,await this.pluginLoader?.stop().catch(()=>{}),this.pluginLoader=void 0,this.pluginRegistry=void 0,this._scheduler?.dispose();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 $e).register(e,t),this.attachCommandsIfReady(),this}unregisterCommand(e){return this.commandRegistry?.unregister(e),this}commands(){return this.commandRegistry?.describe()??[]}use(e){return this.commandMiddleware.push(e),this}unuse(e){let t=this.commandMiddleware.indexOf(e);return t>=0&&this.commandMiddleware.splice(t,1),this}attachCommandsIfReady(){if(this.commandDispatcher||this.commandPrefixes.length===0||this.commandRegistry===void 0||this.commandRegistry.list().length===0||!this._socket)return;let e=this.commandRegistry;this.commandDispatcher=An({registry:e,middleware:this.commandMiddleware,prefixes:this.commandPrefixes,logger:this.logger,onText:t=>{let r=s=>t(s);return this.on("message",r),()=>this.off("message",r)},buildContext:(t,r)=>this.buildCommandContext(t,r),isAdmin:(t,r)=>this.isGroupAdmin(t,r),onError:(t,r)=>this.listenerCount("command-error")===0?false:(this.emit("command-error",{command:r.command,error:t,ctx:r}),true),onNotFound:(t,r)=>{this.listenerCount("command-not-found")!==0&&this.emit("command-not-found",{command:t,message:r});},onBlocked:(t,r)=>{this.emit("command-blocked",{command:r.command,reason:t.reason,...t.retryIn!==void 0?{retryIn:t.retryIn}:{},ctx:r});}});}async replyWithSameLifetime(e,t,r,s){let i=this.send(e).text(t,r),o=Cs(s);return (o!==void 0?i.disappearing(o):i).reply(s)}async isGroupAdmin(e,t){try{let r=await this.group.metadata(e),s=o=>o.split("@")[0]?.split(":")[0]??o,i=s(t);return (r.participants??[]).some(o=>{let a=o;return [o.id,a.phoneNumber,a.jid].filter(c=>typeof c=="string").some(c=>s(c)===i)&&o.admin!=null})}catch{return false}}buildCommandContext(e,t){let r;return {...t,raw:e.raw,command:e.command,args:e.args,flags:e.flags,json:e.json,client:this,send:s=>this.send(s??t.roomId??t.senderId),reply:async(s,i)=>{let o=t.message().key.remoteJid??t.roomId??t.senderId,a=await this.replyWithSameLifetime(o,s,i,t.message());return r=a,a},react:s=>this.react(t.message().key,s),edit:async s=>{if(r===void 0)throw new _("NO_SENT_MESSAGE","ctx.edit requires a prior ctx.reply");await this.edit(r).text(s);}}}detachCommands(){this.commandDispatcher?.detach(),this.commandDispatcher=void 0;}send(e){let t=this.requireBuilderSocket(),r=i=>{this.store.saveMessage(i).catch(o=>this.logger.warn(o,"recordSent failed"));},s=i=>this.chatExpiration.get(i);return this._provider==="cloud"||Le(e)?Y.create(t,e,void 0,r,s):Y.create(t,e,i=>this.resolveRecipient(i),r,s)}rememberChatExpiration(e){let t=e.roomId;if(t!==null){if(e.ephemeralDuration===null){this.chatExpiration.delete(t);return}if(this.chatExpiration.size>=500&&!this.chatExpiration.has(t)){let r=this.chatExpiration.keys().next().value;r!==void 0&&this.chatExpiration.delete(r);}this.chatExpiration.set(t,e.ephemeralDuration);}}edit(e){return this.assertWebProvider("edit"),new Ne(this.requireSocket(),e)}async delete(e,t){this.assertWebProvider("delete"),await hn(this.requireSocket(),e,t);}async react(e,t){return yn(this.requireBuilderSocket(),e,t)}async rejectCall(e,t){if(this.assertWebProvider("rejectCall"),typeof e=="string"){if(typeof t!="string"||t.length===0)throw new x("NOT_CONNECTED","rejectCall(callId, from) requires the caller jid");return this.autoRejectCall.reject(e,t)}return this.autoRejectCall.reject(e.callId,e.from)}get cloud(){if(this._provider!=="cloud")throw new C("CONFIG","wa.cloud requires provider: 'cloud'");return this._cloudModule??=new ut(this.cloudOptions,()=>this.cloudTransport??=new Ee(this.cloudOptions))}async sendTemplate(e,t,r,s){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","sendTemplate() is only available on the cloud provider");return (await this.cloudTransport.sendTemplate(e,t,r,s)).key}async markRead(e,t){if(this._provider!=="cloud"||!this.cloudTransport)throw new C("CONFIG","markRead(messageId) is only available on the cloud provider");await this.cloudTransport.markRead(e,t);}async forward(e,t){let r=this.requireSocket(),s=await this.resolveRecipient(t);return wn(r,this.store,e,s)}async pin(e,t){return this.assertWebProvider("pin"),kt(this.requireSocket(),e,true,t)}async unpin(e){return this.assertWebProvider("unpin"),kt(this.requireSocket(),e,false)}async setDisappearing(e,t){this.assertWebProvider("setDisappearing");let r=await this.resolveRecipient(e);await this.requireSocket().sendMessage(r,{disappearingMessagesInChat:t});}patchOutgoing=async(e,t)=>{let r=Kr(e),s=this.baileysExtra.patchMessageBeforeSending;return typeof s!="function"?r:await s(r,t)};resolveRecipient(e){return vn(this.requireSocket(),e,this.usernameCache)}requireSocket(){if(!this._socket)throw new p("INVALID_OPTIONS","client not connected");return this._socket}requireBuilderSocket(){if(this._provider==="cloud"){if(!this.cloudTransport||this.machine.state!=="connected")throw new p("INVALID_OPTIONS","client not connected");return this.cloudTransport}return this.requireSocket()}attachEmitterLogger(){this.logger;}wireSocket(e){let t=o=>{this.handleConnectionUpdate(o);},r=o=>{let a=this.creds?Object.assign(this.creds,o):o;this.creds=a,this.auth.creds.writeCreds(a).catch(d=>{this.logger.warn(d,"auth.creds.writeCreds failed");});},s=o=>{try{Yr(o);}catch(a){this.logger.warn(a,"rememberCallerInfo failed");}};e.ev.on("connection.update",t),e.ev.on("creds.update",r);let i=e.ws;if(i!==void 0&&typeof i.on=="function"&&typeof i.off=="function"){let o=i;o.on("CB:call",s),this.listenerCleanup.push({off:()=>o.off("CB:call",s)});}this.listenerCleanup.push({off:()=>e.ev.off("connection.update",t)}),this.listenerCleanup.push({off:()=>e.ev.off("creds.update",r)});}async handleConnectionUpdate(e){if(e.qr&&await this.handleQrUpdate(e.qr),e.connection==="open"){this.handleOpen();return}e.connection==="close"&&await this.handleClose(e.lastDisconnect);}async handleQrUpdate(e){if(this.authExhausted)return;if(this.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=Js({phoneNumber:this.phoneNumber}),a=this._socket;if(!a)return;let d=await o.requestCode(a);this.logStatus({kind:"pairing-code",code:d.code}),this.emit("pairing-code",{sessionId:this.sessionId,code:d.code,expiresAt:d.expiresAt});}catch(o){this.logger.warn(o,"pairing-code request failed");}return}let t=Date.now(),r=this.authGuard.evaluate("qr",t);if(!r.allowed){this.handleAuthExhausted("qr",r.attempts,r.max);return}if(this.authGuard.record("qr",t),this.machine.canTransition("qr-pending")&&this.machine.transition("qr-pending"),this.qrTerminal)try{await Vs(e);}catch(s){this.logger.warn(s,"printQrToTerminal failed");}this.logStatus({kind:"qr"}),this.emit("qr",{sessionId:this.sessionId,qrString:e,expiresAt:t+xi});}handleAuthExhausted(e,t,r){this.authExhausted||(this.authExhausted=true,this.logger.warn({sessionId:this.sessionId,kind:e,attempts:t,max:r},`auth attempts exhausted (${t}/${r} ${e}); stopping to avoid WhatsApp spam restriction \u2014 call connect() to retry`),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.emit("auth-exhausted",{sessionId:this.sessionId,kind:e,attempts:t,max:r}),this.disconnect());}handleOpen(){this.machine.canTransition("connected")&&this.machine.transition("connected"),this.openedThisRun=true,this.credsHintShown=false,this.postOpenLogoutRetries=0,this.authExhausted=false,this.authGuard.reset(),this.reconnectStrategy.reset();let e=this.resolveMe();this.logStatus({kind:"connected",id:typeof e.id=="string"?e.id:""}),this.emit("connect",{sessionId:this.sessionId,me:e});let t=this._socket;t&&(this.inboundHandle?.detach(),this.inboundHandle=Dn(this,t,{selfJid:typeof e.id=="string"?e.id:"",...typeof e.lid=="string"&&e.lid.length>0?{selfLid:e.lid}:{},...typeof e.name=="string"&&e.name.length>0?{selfName:e.name}:{},channelId:this.sessionId,receiverId:typeof e.id=="string"?e.id:"",prefixes:this.commandPrefixes,logger:this.logger,...this.citationConfig!=null?{citationConfig:this.citationConfig}:{},groupMetadata:s=>this.group.metadata(s).catch(()=>null),receiverName:()=>Promise.resolve(this.resolveMe().name??null),resolveQuoted:(s,i)=>this.lookupQuoted(s,i),resolveLidToPn:s=>this.lidToPn(s),sendReply:async(s,i,o,a)=>await this.replyWithSameLifetime(s,i,o,a),react:(s,i)=>this.react(s,i),ignoreMe:this.ignoreMe})),this.attachCommandsIfReady(),this.ensureScheduler().loadPending().catch(s=>this.logger.warn(s,"scheduler loadPending failed")),this.autoDeleteOptions&&(this.autoDeleteSweeper?.stop(),this.autoDeleteSweeper=new Ye({store:this.store,options:this.autoDeleteOptions,logger:this.logger}),this.autoDeleteSweeper.start()),this.pluginsOptions&&!this.pluginLoader&&(this.pluginRegistry=new Ge({client:this,logger:this.logger}),this.pluginLoader=new Je({registry:this.pluginRegistry,options:this.pluginsOptions,logger:this.logger}),this.pluginLoader.start().catch(s=>this.logger.error(s,"plugin loader start failed")));let r=this.connectResolve;this.connectResolve=void 0,this.connectReject=void 0,r&&r();}async resolveMessageForResend(e){try{return (await this.store.getMessage(e))?.message??void 0}catch(t){this.logger.warn(t,"getMessage resend lookup failed");return}}lidMapping(){return this._socket?.signalRepository?.lidMapping}async lidMapBulk(e,t,r){let s=new Map;if(t.length===0)return s;try{let i=this.lidMapping()?.[e];if(typeof i!="function")return s;for(let o of await i(t)??[])o?.pn!=null&&o?.lid!=null&&s.set(o[r],r==="pn"?o.lid:o.pn);}catch{return s}return s}async lidToPn(e){try{let t=this.lidMapping()?.getPNForLID;return typeof t=="function"?await t(e):null}catch{return null}}async pnToLid(e){try{let t=this.lidMapping()?.getLIDForPN;return typeof t=="function"?await t(e):null}catch{return null}}async lidToPns(e){return this.lidMapBulk("getPNsForLIDs",e,"lid")}async pnToLids(e){return this.lidMapBulk("getLIDsForPNs",e,"pn")}async usernames(e){let t=new Map;if(e.length===0)return t;let r=this._socket,s=r?.query,i=r?.generateMessageTag;if(typeof s!="function"||typeof i!="function")return t;let o={input:{query_input:e.map(a=>({jid:a})),telemetry:{context:"INTERACTIVE"}},include_username:true,include_about_status:false,include_country_code:false};try{let a=await s({tag:"iq",attrs:{id:i(),type:"get",to:S_WHATSAPP_NET,xmlns:"w:mex"},content:[{tag:"query",attrs:{query_id:fc},content:Buffer.from(JSON.stringify({variables:o}),"utf-8")}]});for(let d of hc(a))t.set(d.jid,d.username);}catch{return t}return t}async getUsername(e){return (await this.usernames([e])).get(e)??null}async downloadMedia(e){let t=["image","video","audio","document","sticker"],r={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"};for(let s of [e.fromMe===true,e.fromMe!==true]){let i=await this.store.getMessage({...e,fromMe:s}).catch(()=>{}),o=i?.message;if(i==null||o==null)continue;let a=t.find(d=>o[r[d]]!=null);if(a===void 0)return null;if(this._provider==="cloud"){let c=o[r[a]]?.cloudMediaId;return typeof c!="string"||!this.cloudTransport?null:this.cloudTransport.downloadMedia(c)}return Et(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=wc(e?.error),r=Ks(t),s=false,i=r==="logged-out"&&this.openedThisRun&&!this.authExhausted&&this.postOpenLogoutRetries<mc;if(i&&(this.postOpenLogoutRetries+=1,this.logger.warn({sessionId:this.sessionId,attempt:this.postOpenLogoutRetries},"logged-out right after connect; treating as spurious and reconnecting instead of clearing session")),$s(r)&&!i){try{await this.auth.signal.clear();}catch(o){this.logger.warn(o,"auth.signal.clear failed (post-close)");}try{await this.auth.creds.deleteCreds();}catch(o){this.logger.warn(o,"auth.creds.deleteCreds failed (post-close)");}}if((i||!ot(r))&&!this.authExhausted){Rt(r)&&this.logger.warn({sessionId:this.sessionId},"WhatsApp returned rate-limited (429); backing off before reconnect to avoid restriction");let o=i?{attempt:this.postOpenLogoutRetries,delayMs:gc}:this.reconnectStrategy.next(r);if(o!==null){s=true,this.machine.canTransition("reconnecting")&&this.machine.transition("reconnecting");let a=this.credsLoadedAtConnect&&!this.openedThisRun&&o.attempt>=2&&!this.credsHintShown;a&&(this.credsHintShown=true),this.logStatus({kind:"reconnecting",attempt:o.attempt,delayMs:o.delayMs,reason:r,invalidCredsSuspected:a}),this.emit("reconnecting",{sessionId:this.sessionId,attempt:o.attempt,delayMs:o.delayMs,reason:r}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(d=>{this.logger.warn(d,"reconnect attempt failed");});},o.delayMs);}}if(this.disconnectEmittedFor=this.connectAttemptSeq,this.logStatus({kind:"disconnect",reason:r,willReconnect:s}),this.emit("disconnect",{sessionId:this.sessionId,reason:r,willReconnect:s}),!s){if(this._socket){for(let o of this.listenerCleanup)o.off();this.listenerCleanup=[],this._socket=void 0;}this.machine.canTransition("disconnected")&&this.machine.transition("disconnected"),this.rejectPendingConnect(new Error(`connection closed (${r})`));}}rejectPendingConnect(e){let t=this.connectReject;this.connectResolve=void 0,this.connectReject=void 0,t&&t(e);}};function yc(n){return n===void 0?[]:(Array.isArray(n)?n:[n]).filter(t=>t.length>0)}function wc(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 Ri=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 h("STORE_CLOSED","MemoryAuthStore is closed")}};var qt=null,vc=async()=>{if(qt)return qt;try{return qt=(await import('better-sqlite3')).default,qt}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},Un="default",Ni=500,Li=n=>Array.from({length:n},()=>"?").join(","),Di=(n,e)=>{let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t},Bi=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(Un);if(t)return this.parseBlob(t.data)},writeCreds:async e=>{let t=await this.ensureReady(),r=this.encodeBlob(e);t.writeCreds.run(Un,r);},deleteCreds:async()=>{(await this.ensureReady()).deleteCreds.run(Un);}};signal={read:async(e,t)=>{await this.ensureReady();let r={};if(t.length===0)return r;let s=this.db;for(let i of Di(t,Ni)){let o=Li(i.length),d=s.prepare(`SELECT id, data FROM auth_signal WHERE type = ? AND id IN (${o})`).all(e,...i);for(let c of d)r[c.id]=this.parseBlob(c.data);}return r},write:async e=>{let t=await this.ensureReady(),r=this.db,s=[],i=[];for(let a of Object.keys(e)){let d=e[a];if(d)for(let c of Object.keys(d)){let l=d[c];l===null?i.push({type:a,id:c}):l!==void 0&&s.push({type:a,id:c,blob:this.encodeBlob(l)});}}r.transaction(()=>{for(let a of s)t.writeSignal.run(a.type,a.id,a.blob);for(let a of i)t.deleteSignal.run(a.type,a.id);})();},delete:async(e,t)=>{if(await this.ensureReady(),t.length===0)return;let r=this.db,s=r.transaction(i=>{let o=Li(i.length);r.prepare(`DELETE FROM auth_signal WHERE type = ? AND id IN (${o})`).run(e,...i);});for(let i of Di(t,Ni))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 h("STORE_WRITE_FAILED","failed to close sqlite database",{cause:e})}finally{this.db=null,this.prepared=null;}}}};async ensureReady(){if(this.closed)throw new h("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 vc(),t;try{t=new e(this.options.database,{readonly:this.options.readonly??!1});}catch(r){throw new h("STORE_CONNECTION_FAILED",`failed to open sqlite database at ${String(this.options.database)}`,{cause:r})}try{t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),t.exec(`CREATE TABLE IF NOT EXISTS auth_creds (id TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID;
|
|
22
22
|
CREATE TABLE IF NOT EXISTS auth_signal (type TEXT NOT NULL, id TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY(type, id)) WITHOUT ROWID;`);}catch(r){throw t.close(),new h("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 h("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 h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:t})}}};var $t,Mc=async()=>($t||($t=import('pg').then(n=>n).catch(n=>{throw $t=void 0,new h("STORE_NOT_AVAILABLE","pg is not installed. Run: pnpm add pg",{cause:n})})),$t),Sc="CREATE TABLE IF NOT EXISTS zaileys_auth_creds (id text PRIMARY KEY, data jsonb NOT NULL)",bc="CREATE TABLE IF NOT EXISTS zaileys_auth_signal (type text NOT NULL, id text NOT NULL, data bytea NOT NULL, PRIMARY KEY(type, id))",Wi=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 h("STORE_CONNECTION_FAILED","PostgresAuthStore: provide either pool or connectionString, not both");if(!t&&!r)throw new h("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 h("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 Mc(),r=t.Pool??t.default?.Pool;if(!r)throw new h("STORE_NOT_AVAILABLE","pg.Pool constructor not found");e=new r({connectionString:this.connectionString,max:this.poolMax}),this.ownedPool=e;}try{await e.query(Sc),await e.query(bc);}catch(t){throw new h("STORE_CONNECTION_FAILED","failed to migrate auth schema",{cause:t})}return this.resolvedPool=e,e})());try{return await this.readyPromise}catch(e){throw this.readyPromise=void 0,e}}signal={read:async(e,t)=>{let r=await this.ensureReady(),s={};if(t.length===0)return s;try{let i=t.map((a,d)=>`$${d+2}`).join(", "),o=await r.query(`SELECT id, data FROM zaileys_auth_signal WHERE type = $1 AND id IN (${i})`,[String(e),...Array.from(t)]);for(let a of o.rows){let d=Buffer.isBuffer(a.data)?a.data:Buffer.from(a.data);s[a.id]=JSON.parse(d.toString("utf8"),BufferJSON.reviver);}return s}catch(i){throw i instanceof h?i:new h("STORE_READ_FAILED","failed to read signal rows",{cause:i})}},write:async e=>{let t=await this.ensureReady(),r=[];for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a];if(d===null)r.push({kind:"delete",type:String(i),id:a});else if(d!==void 0){let c=Buffer.from(JSON.stringify(d,BufferJSON.replacer),"utf8");r.push({kind:"upsert",type:String(i),id:a,value:c});}}}if(r.length===0)return;let s;try{s=await t.connect(),await s.query("BEGIN");for(let i of r)i.kind==="delete"?await s.query("DELETE FROM zaileys_auth_signal WHERE type = $1 AND id = $2",[i.type,i.id]):await s.query("INSERT INTO zaileys_auth_signal(type, id, data) VALUES ($1, $2, $3) ON CONFLICT (type, id) DO UPDATE SET data = EXCLUDED.data",[i.type,i.id,i.value]);await s.query("COMMIT");}catch(i){if(s)try{await s.query("ROLLBACK");}catch{}throw new h("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 h("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 h("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 h?t:new h("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 h("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 h("STORE_WRITE_FAILED","failed to delete creds",{cause:t})}}}};var Cc="zaileys",Ac=["pre-key","session","sender-key","sender-key-memory","app-state-sync-key","app-state-sync-version","lid-mapping","device-list","tctoken","identity-key"],Pc=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Fi=class{namespace;externalClient;url;ownedClient;ready;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","RedisAuthStore requires either client or url");this.namespace=e.namespace??Cc,this.externalClient=e.client,this.url=e.url;}signal={read:async(e,t)=>{if(this.assertOpen(),t.length===0)return {};let r=await this.ensureReady(),s=t.map(a=>this.signalKey(e,a)),i=await this.runRead(()=>r.mGet(s)),o={};for(let a=0;a<t.length;a+=1){let d=i[a];d!=null&&(o[t[a]]=JSON.parse(d,BufferJSON.reviver));}return o},write:async e=>{this.assertOpen();let r=(await this.ensureReady()).multi(),s=0;for(let i of Object.keys(e)){let o=e[i];if(o)for(let a of Object.keys(o)){let d=o[a],c=this.signalKey(i,a),l=this.indexKey(i);d===null?(r.del(c),r.sRem(l,a)):d!==void 0&&(r.set(c,JSON.stringify(d,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 Ac){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 h("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 Pc(r)?new h("STORE_NOT_AVAILABLE","redis peer dependency missing. Run: pnpm add redis",{cause:r}):new h("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 h("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 h("STORE_READ_FAILED","redis read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("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 h("STORE_CLOSED","RedisAuthStore is closed")}};var kc="zaileys",pt={get:"zaileys:get",set:"zaileys:set",del:"zaileys:del",clear:"zaileys:clear",list:"zaileys:list"},Ec=n=>{if(typeof n!="object"||n===null)return false;let e=n.code;return e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND"},Te=class{namespace;externalClient;url;client;closed=false;constructor(e){if(e.client&&e.url)throw new h("STORE_CONNECTION_FAILED","pass either client OR url, not both");if(!e.client&&!e.url)throw new h("STORE_CONNECTION_FAILED","ConvexKv requires either client or url");this.namespace=e.namespace??kc,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(pt.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(pt.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(pt.del,{namespace:this.namespace,keys:[...e]}));}async clear(e){this.assertOpen();let t=await this.ensureClient();await this.runWrite(()=>t.mutation(pt.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(pt.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 Ec(r)?new h("STORE_NOT_AVAILABLE","convex peer dependency missing. Run: pnpm add convex",{cause:r}):new h("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 h("STORE_READ_FAILED","convex read failed",{cause:t})}}async runWrite(e){try{return await e()}catch(t){throw new h("STORE_WRITE_FAILED","convex write failed",{cause:t})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","Convex store is closed")}};var Vt="creds",Tc="signal:",mt=(n,e)=>`${Tc}${n}:${e}`,ji=class{creds;signal;kv;constructor(e){this.kv=new Te(e);let t=this.kv;this.creds={async readCreds(){let s=(await t.get([Vt])).get(Vt);return s===void 0?void 0:JSON.parse(s,BufferJSON.reviver)},async writeCreds(r){await t.set([{key:Vt,value:JSON.stringify(r,BufferJSON.replacer)}]);},async deleteCreds(){await t.del([Vt]);}},this.signal={async read(r,s){let i=s.map(d=>mt(r,d)),o=await t.get(i),a={};for(let d of s){let c=o.get(mt(r,d));a[d]=c===void 0?void 0:JSON.parse(c,BufferJSON.reviver);}return a},async write(r){let s=[],i=[];for(let o of Object.keys(r)){let a=r[o];if(a)for(let d of Object.keys(a)){let c=a[d];c==null?i.push(mt(o,d)):s.push({key:mt(o,d),value:JSON.stringify(c,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=>mt(r,i)));},async clear(){await t.clear();},async close(){t.close();}};}};var Ht=null,Ic=async()=>{if(Ht)return Ht;try{return Ht=(await import('better-sqlite3')).default,Ht}catch(n){throw new h("STORE_NOT_AVAILABLE","better-sqlite3 belum terpasang. Run: pnpm add better-sqlite3",{cause:n})}},zt=n=>{try{return Buffer.from(JSON.stringify(n,BufferJSON.replacer),"utf8")}catch(e){throw new h("STORE_WRITE_FAILED","failed to serialize sqlite blob",{cause:e})}},pe=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 h("STORE_CORRUPTED","failed to parse sqlite blob",{cause:e})}},Ui=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,zt(e));}async getMessage(e){let r=(await this.ensureReady()).getMessage.get(e.remoteJid??"",e.id??"",e.fromMe?1:0);return r?pe(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=>pe(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,zt(e));}async getChat(e){let r=(await this.ensureReady()).getChat.get(e);return r?pe(r.data):void 0}async listChats(e){let t=await this.ensureReady();return (e?.archived===true?t.listChatsArchived.all():t.listChats.all()).map(s=>pe(s.data))}async saveContact(e){(await this.ensureReady()).upsertContact.run(e.id,zt(e));}async getContact(e){let r=(await this.ensureReady()).getContact.get(e);return r?pe(r.data):void 0}async listContacts(){return (await this.ensureReady()).listContacts.all().map(r=>pe(r.data))}async savePresence(e,t){(await this.ensureReady()).upsertPresence.run(e,zt(t));}async getPresence(e){let r=(await this.ensureReady()).getPresence.get(e);return r?pe(r.data):void 0}async deleteMessage(e){(await this.ensureReady()).deleteMessage.run(e.remoteJid??"",e.id??"",e.fromMe===true?1:0);}async pruneMessages(e){let t=await this.ensureReady(),r=this.db,s=0,i=e.chatFilter?r.prepare("SELECT DISTINCT remote_jid FROM messages").all().map(o=>o.remote_jid).filter(o=>e.chatFilter(o)):void 0;if(e.olderThan!==void 0)if(i)for(let o of i)s+=t.pruneByAgeChat.run(e.olderThan,o).changes;else s+=t.pruneByAge.run(e.olderThan).changes;if(e.maxPerChat!==void 0){let o=i?"WHERE remote_jid IN ("+i.map(()=>"?").join(",")+")":"",a=r.prepare(`DELETE FROM messages WHERE rowid IN (
|
|
23
23
|
SELECT rowid FROM (
|
|
24
24
|
SELECT rowid, ROW_NUMBER() OVER (PARTITION BY remote_jid ORDER BY timestamp DESC) AS rn
|