import{Da as e,Wn as t,Yn as n,ec as r}from"./model-auth-C2mRFxhd.js";import{I as i,L as a,M as o,V as s,r as c}from"./logger-DBxM8LRL.js";import{i as l,n as u,t as d}from"./session-CYHcG3ym.js";import{DisconnectReason as f}from"@whiskeysockets/baileys";async function p(p,m,h=o,g){let _=m??l,v=t({cfg:e(),accountId:g}),y=await d(!0,p,{authDir:v.authDir});c(`Waiting for WhatsApp connection...`,h);try{await _(y),console.log(s(`✅ Linked! Credentials saved for future sends.`))}catch(e){let t=e?.error?.output?.statusCode??e?.output?.statusCode;if(t===515){console.log(a(`WhatsApp asked for a restart after pairing (code 515); creds are saved. Restarting connection once…`));try{y.ws?.close()}catch{}let e=await d(!1,p,{authDir:v.authDir});try{await _(e),console.log(s(`✅ Linked after restart; web session ready.`));return}finally{setTimeout(()=>e.ws?.close(),500)}}if(t===f.loggedOut)throw await n({authDir:v.authDir,isLegacyAuthDir:v.isLegacyAuthDir,runtime:h}),console.error(i(`WhatsApp reported the session is logged out. Cleared cached web session; please rerun ${r(`openclaw channels login`)} and scan the QR again.`)),Error(`Session logged out; cache cleared. Re-run login.`,{cause:e});let o=u(e);throw console.error(i(`WhatsApp Web connection ended before fully opening. ${o}`)),Error(o,{cause:e})}finally{setTimeout(()=>{try{y.ws?.close()}catch{}},500)}}export{p as t};
