import p from"node:crypto";import U from"node:fs";import g from"node:path";import{fileURLToPath as _}from"node:url";import{loadConfigRouteTag as k}from"../auth/accounts.js";import{logger as l}from"../util/logger.js";import{redactBody as f,redactUrl as S}from"../util/redact.js";function m(){try{const e=g.dirname(_(import.meta.url)),n=g.resolve(e,"..","..","package.json");return JSON.parse(U.readFileSync(n,"utf-8")).version??"unknown"}catch{return"unknown"}}const h=m();function i(){return{channel_version:h}}const T=35e3,c=15e3,y=1e4;function w(e){return e.endsWith("/")?e:`${e}/`}function M(){const e=p.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function O(e){const n={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":M()};e.token?.trim()&&(n.Authorization=`Bearer ${e.token.trim()}`);const t=k();return t&&(n.SKRouteTag=t),l.debug(`requestHeaders: ${JSON.stringify({...n,Authorization:n.Authorization?"Bearer ***":void 0})}`),n}async function r(e){const n=w(e.baseUrl),t=new URL(e.endpoint,n),b=O({token:e.token,body:e.body});l.debug(`POST ${S(t.toString())} body=${f(e.body)}`);const s=new AbortController,d=setTimeout(()=>s.abort(),e.timeoutMs),u=()=>s.abort();e.abortSignal&&(e.abortSignal.aborted?(clearTimeout(d),s.abort()):e.abortSignal.addEventListener("abort",u,{once:!0}));try{const o=await fetch(t.toString(),{method:"POST",headers:b,body:e.body,signal:s.signal});clearTimeout(d);const a=await o.text();if(l.debug(`${e.label} status=${o.status} raw=${f(a)}`),!o.ok)throw new Error(`${e.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(d),o}finally{e.abortSignal?.removeEventListener("abort",u)}}async function I(e){const n=e.timeoutMs??T;try{const t=await r({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:i()}),token:e.token,timeoutMs:n,label:"getUpdates",abortSignal:e.abortSignal});return JSON.parse(t)}catch(t){if(e.abortSignal?.aborted&&t instanceof Error&&t.name==="AbortError")throw t;if(t instanceof Error&&t.name==="AbortError")return l.debug(`getUpdates: client-side timeout after ${n}ms, returning empty response`),{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw t}}async function L(e){const n=await r({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:i()}),token:e.token,timeoutMs:e.timeoutMs??c,label:"getUploadUrl"});return JSON.parse(n)}async function P(e){await r({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:i()}),token:e.token,timeoutMs:e.timeoutMs??c,label:"sendMessage"})}async function z(e){const n=await r({baseUrl:e.baseUrl,endpoint:"ilink/bot/getconfig",body:JSON.stringify({ilink_user_id:e.ilinkUserId,context_token:e.contextToken,base_info:i()}),token:e.token,timeoutMs:e.timeoutMs??y,label:"getConfig"});return JSON.parse(n)}async function $(e){await r({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:i()}),token:e.token,timeoutMs:e.timeoutMs??y,label:"sendTyping"})}export{i as buildBaseInfo,z as getConfig,I as getUpdates,L as getUploadUrl,P as sendMessage,$ as sendTyping};
