import{e as d}from"./index-BNXDN8h1.js";import{o}from"./browser-ponyfill-C_jrGRjm.js";import{i as a,s as h,a as u,f as m,p as y}from"./index-DSskmJfT.js";import"./index-DnKfU2ei.js";var b=Object.defineProperty,P=Object.defineProperties,w=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,E=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,c=(s,e,t)=>e in s?b(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,p=(s,e)=>{for(var t in e||(e={}))E.call(e,t)&&c(s,t,e[t]);if(l)for(var t of l(e))O.call(e,t)&&c(s,t,e[t]);return s},v=(s,e)=>P(s,w(e));const L={Accept:"application/json","Content-Type":"application/json"},j="POST",f={headers:L,method:j},g=10;class M{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new d.EventEmitter,this.isAvailable=!1,this.registering=!1,!a(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=h(e),r=await(await o(this.url,v(p({},f),{body:t}))).json();this.onPayload({data:r})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!a(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((r,i)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),i(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=h({id:1,jsonrpc:"2.0",method:"test",params:[]});await o(e,v(p({},f),{body:t}))}this.onOpen()}catch(t){const r=this.parseError(t);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?u(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const r=this.parseError(t),i=r.message||r.toString(),n=m(e,i);this.events.emit("payload",n)}parseError(e,t=this.url){return y(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>g&&this.events.setMaxListeners(g)}}export{M as f};
