import Bluebird from"../../deps/bluebird_fork.js";function parseResponseHeaders(e){const s={};if("string"!=typeof e)return s;for(const i of e.split(/\r?\n/)){var t=i.indexOf(":");if(0<=t){var r=i.substr(0,t).trim(),t=i.substr(t+1).trim();const n=s[r];n instanceof Array?n.push(t):"string"==typeof n?s[r]=[n,t]:s[r]=t}}return s}class ChannelProvider{constructor(e,s){this.resolver=Bluebird.defer(),this.binary=!1,this.timeout=6e4,this.corsWithCredentials=!1,this.name=s,this.type=e,this.request={headers:{}},this.response={headers:{}}}static register(e){e.factories.push(e=>e===this.type?this:void 0)}static create(e,s){return e instanceof this?e.new():new this(this,s)}tryConclude(e){const s=this.xhr;var t;s.readyState===s.DONE&&(this.response.status=s.status,this.response.message=s.statusText,this.response.headers=parseResponseHeaders(s.getAllResponseHeaders()),("string"==typeof(t=s.response)||t instanceof ArrayBuffer)&&(this.response.content=t),this.resolver.resolve(200<=s.status&&s.status<300)),null!=e&&(this.response.error=e,this.resolver.resolve(!1))}cancel(){this.resolver.resolve(!1)}send(){let e=this.promise;if(void 0===e){if(e=this.promise=this.resolver.promise.timeout(this.timeout).catch(e=>!1),e.isResolved())return e;const n=this.xhr=new XMLHttpRequest;e.finally(()=>n.abort());try{n.open(this.request.method||"GET",this.request.url,!0),n.onreadystatechange=e=>this.tryConclude(),n.onerror=e=>this.tryConclude(e.error),this.corsWithCredentials&&(n.withCredentials=!0),this.binary?n.responseType="arraybuffer":n.responseType="text";var s=this.request.headers;for(const o in s){var t=s[o];if(t instanceof Array)for(const a of t)n.setRequestHeader(o,"string"==typeof a?a:JSON.stringify(a));else n.setRequestHeader(o,"string"==typeof t?t:JSON.stringify(t))}var r=this.request.json,i=void 0!==r?JSON.stringify(r):this.request.content;n.send(i)}catch(e){this.response.error=e,this.resolver.resolve(!1)}}return e}getResponseData(e){return e}new(){return new this.type(this.type,this.name)}}ChannelProvider.type="59378113-D159-4E5C-A4AB-292F6E52620E:ChannelProvider";export{ChannelProvider};