import{ok,err}from"./_deps/shared/index.js";export class GatewayTransport{apiKey;gateway;timeoutMs;fetchFn;pollIntervalMs;handlers=[];pollTimer=null;senderDid=null;constructor(e){this.apiKey=e.apiKey,this.gateway=e.gateway.replace(/\/$/,""),this.timeoutMs=e.timeoutMs??15e3,this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.pollIntervalMs=e.pollIntervalMs??0}async send(e,t){const s=`${this.gateway}/gateway/deliver`;try{const t=new AbortController,i=setTimeout(()=>t.abort(),this.timeoutMs),a=await this.fetchFn(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e),signal:t.signal});return clearTimeout(i),a.ok?ok(void 0):err(404===a.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(e){return e instanceof DOMException&&"AbortError"===e.name?err("TIMEOUT"):err("NETWORK_ERROR")}}onReceive(e){this.handlers.push(e)}startPolling(e){this.senderDid=e,this.pollIntervalMs>0&&!this.pollTimer&&(this.pollTimer=setInterval(()=>{this.poll()},this.pollIntervalMs))}dispose(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.handlers=[]}async poll(){if(this.senderDid)try{const e=`${this.gateway}/gateway/messages/${encodeURIComponent(this.senderDid)}`,t=await this.fetchFn(e,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!t.ok)return;const s=await t.json();for(const e of s.messages){for(const t of this.handlers)t(e.envelope);await this.fetchFn(`${this.gateway}/gateway/ack/${e.id}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`}})}}catch{}}}