"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GatewayTransport=void 0;const shared_1=require("../_deps/shared/index.js");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,a=setTimeout(()=>t.abort(),this.timeoutMs),r=await this.fetchFn(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e),signal:t.signal});return clearTimeout(a),r.ok?(0,shared_1.ok)(void 0):(0,shared_1.err)(404===r.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(e){return e instanceof DOMException&&"AbortError"===e.name?(0,shared_1.err)("TIMEOUT"):(0,shared_1.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{}}}exports.GatewayTransport=GatewayTransport;