justrun-ws 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/index.min.js +1 -1
  2. package/package.json +1 -1
package/lib/index.min.js CHANGED
@@ -1 +1 @@
1
- class t{constructor(t,e){e?this.u=t:this.v=t}get data(){return this.v||(this.v=this.decode(this.u)),this.v}set data(t){this.v=t,this.u=void 0}get buff(){return this.u||(this.u=this.encode(this.v)),this.u}u;v}class e extends t{static context;static registerPkgType(t){let e;try{e=this.pkgType}catch{return void Object.defineProperty(this,"pkgType",{value:t,writable:!1,enumerable:!1})}if(e!==t)throw new Error(`Wrapper ${this.name} is already registered with type ${e}`)}static get pkgType(){throw new Error(`Wrapper ${this.name} need to be registered`)}}class s extends e{isError(){return!0}}class n extends e{isMessage(){return!0}}class i extends e{isEvent(){return!0}}class r extends e{constructor(t,e){super(t,e)}isRequest(){return!0}get resp(){return this.w||(this.w=this.decodeResponse(this.x)),this.w}set resp(t){this.w=t,this.x=void 0}get respBuff(){return this.x||(this.x=this.encodeResponse(this.w)),this.x}set respBuff(t){this.w=void 0,this.x=t}w;x}const o=new TextEncoder,h=new TextDecoder;class a extends s{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class c extends n{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class d extends r{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}encodeResponse(t){const e=JSON.stringify(t);return o.encode(e)}decodeResponse(t){const e=h.decode(t);return JSON.parse(e)}}class u extends a{}let l=(t,e)=>new u(e.message);const g=t=>{l=t},p=Object.freeze({}),f=()=>p,w=t=>{let e=0,s=0;for(;e<t.length;)s+=t[e++].length;const n=new Uint8Array(s);for(s=0;e>0;){const i=t[--e];n.set(i,s),s+=i.length}return n};class y{constructor(t,e){if(this.a0=t,this.R=e,this.z=0,this.I=0,this.$=[],0===t)return this.insert=f,this.update=f,void(this.remove=f);for(let t=0;t<e;t++){const t={onTimeout:f,e:p,c:p};t.e=t.c=t,this.$.push(t)}}insert(t){this.I||(this.a1=setInterval(this.ad,this.a0)),this.I++;const e=this.$[this.z],{c:s}=e,n={onTimeout:t,e:e,c:s};return s.e=n,e.c=n,n}update(t){const e=t,{e:s,c:n}=e;s.c=n,n.e=s;const i=this.$[this.z];e.e=i,e.c=i.c,i.c.e=e,i.c=e}remove(t){const{e:e,c:s}=t;e.c=s,s.e=e,--this.I||clearInterval(this.a1)}ad=()=>{const{R:t,$:e}=this;++this.z===t&&(this.z=0);const s=e[this.z];let n=s.c;for(;n!==s;){const{onTimeout:t}=n;n=n.c,t()}};a0;R;z;I;a1;$}const v={AuthTimeout:"Auth Timeout",BadRequest:"Bad Request",ConnectFailed:"Connect Failed",ConnectionClosed:"Connection Closed",InvalidConnString:"Invalid Connection String",InvalidConnection:"Invalid Connection",InvalidPackage:"Invalid Package",NotAuthenticated:"Not Authenticated",NotFound:"Not Found",Timeout:"Timeout",UnknownError:"Unknown Error"};class k{constructor(t,e,s){this._=new y(t,e),this.A=new y(t,s)}insert(t,e){const{_:s,A:n}=this,i=s.insert(()=>t(v.Timeout)),r=e&&n.insert(e);return{onReceive:()=>s.update(i),onSend:r?()=>n.update(r):f,c:i,b:r}}remove(t){const{_:e,A:s}=this,{c:n,b:i}=t;e.remove(n),i&&s.remove(i)}_;A}class m{constructor(t,e){this.i=new Map,this.m=new y(t,e)}get(t){const{i:e,m:s}=this,n=e.get(t);if(n)return s.update(n.handle),n.val}set(t,e){const{i:s,m:n}=this,i=s.get(t);if(i)i.val=e,n.update(i.handle);else{const i=n.insert(()=>{const e=s.get(t);e&&(n.remove(e.handle),s.delete(t))});s.set(t,{handle:i,key:t,val:e})}}delete(t){const{i:e,m:s}=this,n=e.get(t);return!!n&&(s.remove(n.handle),e.delete(t))}i;m}let b=class{constructor(t,e){this.a2=new Promise(t=>{this.r=t}),this.J=e,t>0?this.j=setTimeout(()=>{this.j=void 0,this.r(!0),e?.()},t):(this.r(!0),e?.())}ak(t){const{j:e,r:s,J:n}=this;e&&clearTimeout(e),t>0?this.j=setTimeout(()=>{this.j=void 0,n?.(),s(!0)},t):(this.j=void 0,s(!0),n?.())}ae(){this.j&&(clearTimeout(this.j),this.j=void 0,this.r(!1))}al(){return this.a2}r;a2;j;J};class E extends c{}class T{constructor(t,e,s){let n=sessionStorage.getItem("jrSession");n||(n=crypto.randomUUID(),sessionStorage.setItem("jrSession",n)),this.b="",this.c=n,this.S=t,this.L="",this.B=e,this.f=s,this.M=this.M.bind(this);const i=()=>{throw new Error("JustrunAuthProvider shall be enabled before use")};this.authWithCredential=i,this.authWithOAuth2=i,this.resetAuthState=i,this.resetConnState=i}async init(t,e){const s=T.prototype;this.authWithCredential=s.authWithCredential,this.authWithOAuth2=s.authWithOAuth2,this.resetAuthState=s.resetAuthState,this.resetConnState=s.resetConnState,e.onConnectionStatus(this.ah.bind(this)),e.registerMessage(t,E),e.handleMessageWith(E,this.ai.bind(this));const{c:n,f:i}=this,r=this.T();if(r){const{cid:t,h:e}=r;if(Math.round(Date.now()/1e3)<=e)return void i(t,n)}i("","")}async preConnect(){const{b:t,c:e,e:s,f:n,B:i}=this;if(s)return n(t,e,s),"";const r=""===s;this.e=void 0;let o=this.T();if(o){const{cid:t,address:s,g:n,h:h}=o,a=Math.round(Date.now()/1e3);if(a<=n)return this.L=o.address,i(s,e,r);if(a<=h&&(o=await this.N("refresh",""),o))return this.L=o.address,i(o.address,e,r)}return this.e="unknown error",n("",""),""}async authWithCredential(t,e,s,n){await this.N(t,`${e},${s},${n}`)}authWithOAuth2(t,e,s,n){const i=`${e}?client_id=${s}&redirect_uri=${this.S}&scope=${n}&response_type=code`;window.location.href=`${i}&state=${this.c}~${s}~${encodeURI(t)}`}async resetAuthState(){await this.N("signout","")}resetConnState(t){if(this.e){this.e=t?"":void 0;const{b:e,c:s,f:n}=this;n(e,s)}}ah(t,e,s,n){if(t){this.a=e;const t=this.T();if(t){const{g:e}=t;this.C=new b(1e3*e-Date.now(),this.M)}}else{this.a=void 0,this.C&&(this.C.ae(),this.C=void 0);const t=this.e=n?.message||v.UnknownError,{b:e,c:s,f:i}=this;i(e,s,t)}}async M(){this.C=void 0;const{c:t,B:e}=this,s=await this.N("refresh","");if(s&&this.a){const{address:n,g:i}=s;if(n===this.L){const s=e(n,t),[r,o]=s.split("://");await fetch(`${r.replace("ws","http")}://${o}`),this.C=new b(1e3*i-Date.now(),this.M)}else this.a&&(this.a.close(),this.a=void 0)}}async ai(t){const{b:e,c:s,a:n}=this,{type:i,j:r}=t;"kick"===i&&n&&(n.close(),this.a=void 0,r&&(this.e=r,this.f(e,s,r)))}T(){const t=localStorage.getItem("jrAuth")||void 0;if(t){const[e,s,n,i]=t.split(","),{b:r,a:o}=this;return r&&e!==r&&o&&(o.close(),this.a=void 0),this.b=e,{cid:e,address:s,g:parseInt(n),h:parseInt(i)}}}async N(t,e){const s=await fetch(this.S,{method:"POST",body:`${t}:${e}`}).catch(t=>{throw new u(t.message)}),n=await s.text();if(!s.ok)throw new u(n);if(n.startsWith("auth:")){const t=n.substring(5);localStorage.setItem("jrAuth",t);const[e,s,i,r]=t.split(","),{b:o,a:h}=this;return o!==e&&(o&&h&&(h.close(),this.a=void 0),this.b=e,this.f(e,this.c,this.e)),{cid:e,address:s,g:parseInt(i),h:parseInt(r)}}if(n.startsWith("clear:"))localStorage.removeItem("jrAuth"),this.b="",this.e=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0);else if(n.startsWith("error:")){"refresh"!==t&&"signout"!==t||(localStorage.removeItem("jrAuth"),this.b="",this.e=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0));const e=n.substring(6);throw new u(e)}}b;c;S;L;a;e;C;B;f}const C=new Error(v.NotAuthenticated);class P{constructor(t,e,s){this.n=t,this.s=e,this.t=!s}get pkgType(){return this.n.pkgType}get m(){return this.n.name}async v(t,e){const{buff:s,bodyOffset:n}=e,i=s.subarray(n),r=new this.n(i,!0);if(void 0===t.context&&this.t)l(t,C);else try{await this.s(t,r)}catch(e){e.isError||l(t,e)}void 0===t.context&&await t.close()}async u(t,e){if(void 0===t.context&&this.t)l(t,C);else try{return await this.s(t,e)}catch(e){e.isError||l(t,e)}}n;s;t}let S=class{constructor(t,e,s){this.n=t,this.s=e,this.t=!s}get pkgType(){return this.n.pkgType}get m(){return this.n.name}async v(t,e){const{buff:s,requestId:n,bodyOffset:i}=e,r=s.subarray(i),o=new this.n(r,!0);let h;if(void 0===t.context&&this.t)h=l(t,C);else try{await this.s(t,o)}catch(e){h=e.isError?e:l(t,e)}try{h?await t.sendErrorResponse(h,n):await t.sendResponse(o,n),void 0===t.context&&await t.close()}catch{return}}async u(t,e){if(void 0!==t.context||!this.t)try{return await this.s(t,e)}catch(e){throw e.isError?e:l(t,e)}throw l(t,C)}n;s;t},x=class{address(){return null}init(t){this.D=t}async C(t){return!1}async G(){return!1}async g(t){const e=new WebSocket(t);return new Promise((t,s)=>{e.onerror=t=>{s(new Error(v.UnknownError))},e.onopen=()=>{t(this.af(e,!0))}})}af=(t,e)=>{const s=new R(t),{conn:n,$:i,o:r}=this.D(s,e);t.onmessage=t=>{t.data.arrayBuffer().then(t=>{i(new Uint8Array(t))})};let o=!0;return t.onerror=t=>{o=!1,r(new Error(t.message||v.UnknownError))},t.onclose=t=>{o&&r(1e3===t.code?void 0:new Error(t.reason||"unknown error"))},n};D(t,e){throw new Error('Need to call "setConnWrapperMaker" before using')}},R=class{constructor(t){this.e=t}get socket(){return{localAddress:"",localPort:0,remoteAddress:"",remoteFamily:"",remotePort:0}}async A(t){if(this.e)return this.e.send(t),t.byteLength;throw new Error(v.InvalidConnection)}async n(t){if(this.e){const e=w(t);return this.e.send(e),e.byteLength}throw new Error(v.InvalidConnection)}async close(t){const{e:e}=this;e&&(this.e=void 0,t?(e.close(1e3,t.message),e.onerror(new ErrorEvent("error",{message:t.message})),e.onerror=e.onclose=null):e.readyState<=WebSocket.OPEN&&e.close())}B(){return!this.e}e};const A=(t,e,s)=>{const n=[e,t],i=(t=>{let e,s=0,n=0;for(;s<t.length;)for(n++,e=t[s++];e>>>=7;)n++;return n})(n),r=new Uint8Array(i);((t,e,s=0)=>{let n,i,r=s;for(n=0;n<t.length;n++){i=t[n];let s=127&i;for(;i>>>=7;)e[r++]=128|s,s=127&i;e[r++]=s}if(r<=e.length)return r-s;throw new Error("Buffer overflow")})(n,r),s.push(r)},I=t=>{const{g:[e,s],j:n}=((t,e,s=0)=>{let n,i,r=s,o=0,h=0;const a=[];for(n=0;n<t;n++){do{i=e[r++],o|=(127&i)<<h,h+=7}while(128&i);if(!(void 0!==i&&h<=35))throw new Error("Parsing failed");a.push(o),o=0,h=0}return{g:a,j:r-s}})(2,t);return{buff:t,pkgType:s,requestId:e,bodyOffset:n}};class ${constructor(t){this.a3=t}get id(){return this.a?.id??-1}get context(){return this.a?.context}set context(t){this.a&&(this.a.context=t)}localAddress;localPort;remoteAddress;remoteFamily;remotePort;async sendErrorResponse(t,e){return(this.a??await this.g()).sendErrorResponse(t,e)}async sendResponse(t,e){return(this.a??await this.g()).sendResponse(t,e)}async sendMessage(t){return(this.a??await this.g()).sendMessage(t)}async sendRequest(t){return(this.a??await this.g()).sendRequest(t)}async close(t){const{a:e}=this;if(e)return this.a=void 0,void await e.close(t);const{b:s}=this;s&&await s.then(e=>{s===this.b&&(this.b=void 0,this.a=void 0,e.close(t))},()=>{s===this.b&&(this.b=s,this.a=void 0)})}async am(){this.a||await this.g()}ag(){this.a=void 0,this.b=void 0}async g(){let{b:t}=this;return t||(t=this.b=new Promise((e,s)=>{this.a3().then(n=>{if(t===this.b&&(this.b=void 0,n))return e(n),void(this.a=n);n&&n.close(),s(new Error("Connect failed"))})})),await t}a3;a;b}class M{constructor(t,e){const{responsePkgType:s,connMonitor:n,makePkgBuff:i,parsePkgBuff:r}=e;this.responsePkgType=s,this.p=0,this.q=new Map,this.h=new Map,this.O=new Map,this.U=i,this.V=r,this.E=t,this.P=n;this.v=this.a5;const o=[];this.U(s,2097152,o),this.W={makePkgBuff:i,responsePkgType:s,j:w(o)},this.h.set(s,this),t.init((t,e)=>{do{this.p++}while(this.q.has(2097151&this.p));const s=new W(this.W,t,2097151&this.p);this.q.set(s.id,s),s.handle=this.P?.insert(s.forceClose.bind(s),s.keepAlive.bind(s));const n={conn:s,$:t=>this.a6(s,t),o:t=>this.a7(s,t)};return this.H?.(this,s,!!e),n})}responsePkgType;context;H;F;address(){return this.E.address()}M(t){return this.q.get(t)}g(t){return this.E.g(t)}async N(){do{this.p++}while(this.q.has(2097151&this.p));const t=new q(2097151&this.p,this);return this.q.set(t.id,t),t}async R(t){return this.E.C(t)}async S(){return this.E.G()}a8(t,e){const s=e.constructor.pkgType,n=this.h.get(s);if(n)return n?.u(t,e);throw new Error(v.InvalidPackage)}a9(t,e){const s=e.constructor.pkgType,n=this.h.get(s);if(n)return n?.u(t,e);throw new Error(v.InvalidPackage)}registerError(t,e){e.registerPkgType(t),this.O.set(t,e);const s=this.h.get(this.responsePkgType);this.h.set(t,s)}registerMessage(t,e){e.registerPkgType(t)}registerRequest(t,e){e.registerPkgType(t)}handleMessageWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.m} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.h.set(e,t),t}handleRequestWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.m} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.h.set(e,t),t}aj(t){const e=t.pkgType;return this.h.get(e)===t&&(this.h.delete(e),!0)}a6(t,e){t.handle?.onReceive(e.byteLength);const s=this.V(e),n=this.h.get(s.pkgType);n?n.v(t,s):t.close(new Error(v.InvalidPackage))}a7(t,e){this.q.delete(t.id),this.P?.remove(t.handle),t.o(e),this.F?.(this,t,t.d.B(),e)}a5(t,e){try{const{buff:s,pkgType:n,requestId:i,bodyOffset:r}=e;if(n===this.responsePkgType){const e=s.subarray(r);t.X(i,e)}else{const e=this.O.get(n);if(e){const n=new e(s.subarray(r),!0);t.aa(i,n)}}}catch{t.close(new Error(v.InvalidPackage))}}W;p;U;V;E;q;h;O;P}class W{constructor(t,e,s){this.id=s,this.d=e,this.y=t,this.Y=0}context;handle;id;d;get socket(){return this.d.socket}async sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];this.y.makePkgBuff(e,0,s);const n=await this.d.n(s);this.handle?.onSend(n)}sendRequest(t){return this.l=new Map,this.sendRequest=this.Z,this.X=this.ab,this.o=this.ac,this.Z(t)}async sendErrorResponse(t,e){const s=t.constructor.pkgType,n=[t.buff];this.y.makePkgBuff(s,e,n);const i=await this.d.n(n);this.handle?.onSend(i)}async sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:n,responsePkgType:i}=this.y;n(i,e,s);const r=await this.d.n(s);this.handle?.onSend(r)}async close(t){await this.d.close(t)}X(t,e){2097152===t&&void 0===this.context&&this.close(new Error(v.AuthTimeout))}aa(t,e){const s=this.l.get(t);if(s)return this.l.delete(t),s.i(e)}keepAlive(){const{j:t}=this.y;this.d.A(t).catch(f),this.handle?.onSend(t.byteLength)}forceClose(t){this.close(new Error(t??v.UnknownError))}o(t){}async Z(t){const e=2097151&this.Y++,s=t.constructor.pkgType,n=[t.buff];this.y.makePkgBuff(s,e,n);const i=new Promise((t,s)=>{const i={c:t,i:s};this.l.set(e,i),this.d.n(n).then(t=>{this.handle?.onSend(t)},t=>{this.l.delete(e),s(t)})});t.respBuff=await i}ab(t,e){const s=this.l.get(t);if(s)return this.l.delete(t),void s.c(e);2097152===t&&void 0===this.context&&this.close(new Error(v.AuthTimeout))}ac(t){const e=this.l;if(e.size>0){t||(t=new Error(v.ConnectionClosed));for(const[s,n]of e)e.delete(s),n.i(t)}this.l=void 0}y;l;Y}class q{constructor(t,e){this.id=t,this.Q=e}context;id;socket;get remoteFamily(){return"Local"}async sendMessage(t){return this.Q.a8(this,t)}async sendRequest(t){return this.Q.a9(this,t)}sendErrorResponse(t,e){throw null}sendResponse(t,e){throw null}async close(t){}Q}const N=(t,e)=>new O(t,{responsePkgType:0,makePkgBuff:A,parsePkgBuff:I,connMonitor:e});var j;!function(t){t[t.NotConnected=0]="NotConnected",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected"}(j||(j={}));class O{constructor(t,e){const s=new x,n=this.k=new M(s,e);this.G=j.NotConnected,this.a4=t,this.a=new $(()=>this.g()),n.H=this.H.bind(this),n.F=this.F.bind(this)}getConnState(){return this.G}enableAuthenticate(t,e){this.K=e,e.init(t,this)}registerError(t,e){return this.k.registerError(t,e)}registerMessage(t,e){return this.k.registerMessage(t,e)}registerRequest(t,e){return this.k.registerRequest(t,e)}handleMessageWith(t,e){this.k.handleMessageWith(new P(t,(t,s)=>e(s.data),!0))}handleRequestWith(t,e){this.k.handleRequestWith(new S(t,async(t,s)=>{s.resp=await e(s.data)},!0))}sendMessage(t){return this.a.sendMessage(t)}async sendRequest(t){return await this.a.sendRequest(t),t.resp}onConnectionStatus(t){let{c:e}=this;e||(this.c=e=[]),e.push(t)}async g(){const{k:t,K:e}=this;this.G=j.Connecting;try{const s=e?await e.preConnect():this.a4;if(!s)throw new Error(v.UnknownError);return await t.g(s)}catch(e){const s=e instanceof Error?e:new Error(v.UnknownError);this.F(t,this.a,!0,s)}}H(t,e,s){if(this.G=j.Connected,e.context="",this.c)for(const t of this.c)t(!0,e,s)}F(t,e,s,n){if(this.G=j.NotConnected,this.a.ag(),this.c)for(const t of this.c)t(!1,e,s,n)}a4;k;a;G;K;c}export{u as CommonError,k as ConnAliveMonitor,s as ErrorWrapper,i as EventWrapper,a as JsonError,c as JsonMessage,d as JsonRequest,T as JustrunAuthProvider,n as MessageWrapper,v as NetErrorString,r as RequestWrapper,m as TimeoutCache,y as TimeoutMonitor,O as WsClient,N as createNumPkgTypeClient,g as handleUncaughtErrorWith};
1
+ class t{constructor(t,e){e?this.u=t:this.v=t}get data(){return this.v||(this.v=this.decode(this.u)),this.v}set data(t){this.v=t,this.u=void 0}get buff(){return this.u||(this.u=this.encode(this.v)),this.u}u;v}class e extends t{static context;static registerPkgType(t){let e;try{e=this.pkgType}catch{return void Object.defineProperty(this,"pkgType",{value:t,writable:!1,enumerable:!1})}if(e!==t)throw new Error(`Wrapper ${this.name} is already registered with type ${e}`)}static get pkgType(){throw new Error(`Wrapper ${this.name} need to be registered`)}}class s extends e{isError(){return!0}}class n extends e{isMessage(){return!0}}class i extends e{isEvent(){return!0}}class r extends e{constructor(t,e){super(t,e)}isRequest(){return!0}get resp(){return this.w||(this.w=this.decodeResponse(this.x)),this.w}set resp(t){this.w=t,this.x=void 0}get respBuff(){return this.x||(this.x=this.encodeResponse(this.w)),this.x}set respBuff(t){this.w=void 0,this.x=t}w;x}const o=new TextEncoder,h=new TextDecoder;class a extends s{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class c extends n{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}}class d extends r{encode(t){const e=JSON.stringify(t);return o.encode(e)}decode(t){const e=h.decode(t);return JSON.parse(e)}encodeResponse(t){const e=JSON.stringify(t);return o.encode(e)}decodeResponse(t){const e=h.decode(t);return JSON.parse(e)}}class u extends a{}let l=(t,e)=>new u(e.message);const g=t=>{l=t},p=Object.freeze({}),f=()=>p,w=t=>{let e=0,s=0;for(;e<t.length;)s+=t[e++].length;const n=new Uint8Array(s);for(s=0;e>0;){const i=t[--e];n.set(i,s),s+=i.length}return n};class y{constructor(t,e){if(this.a0=t,this.R=e,this.z=0,this.I=0,this.$=[],!t||!e)return this.insert=f,this.update=f,void(this.remove=f);for(let t=0;t<e;t++){const t={onTimeout:f,e:p,c:p};t.e=t.c=t,this.$.push(t)}}insert(t){this.I||(this.a1=setInterval(this.ad,this.a0)),this.I++;const e=this.$[this.z],{c:s}=e,n={onTimeout:t,e:e,c:s};return s.e=n,e.c=n,n}update(t){const e=t,{e:s,c:n}=e;s.c=n,n.e=s;const i=this.$[this.z];e.e=i,e.c=i.c,i.c.e=e,i.c=e}remove(t){const{e:e,c:s}=t;e.c=s,s.e=e,--this.I||clearInterval(this.a1)}ad=()=>{const{R:t,$:e}=this;++this.z===t&&(this.z=0);const s=e[this.z];let n=s.c;for(;n!==s;){const{onTimeout:t}=n;n=n.c,t()}};a0;R;z;I;a1;$}const v={AuthTimeout:"Auth Timeout",BadRequest:"Bad Request",ConnectFailed:"Connect Failed",ConnectionClosed:"Connection Closed",InvalidConnString:"Invalid Connection String",InvalidConnection:"Invalid Connection",InvalidPackage:"Invalid Package",NotAuthenticated:"Not Authenticated",NotFound:"Not Found",Timeout:"Timeout",UnknownError:"Unknown Error"};class k{constructor(t,e,s){this._=new y(t,e),this.A=new y(t,s)}insert(t,e){const{_:s,A:n}=this,i=s.insert(()=>t(v.Timeout)),r=e&&n.insert(e);return{onReceive:()=>s.update(i),onSend:r?()=>n.update(r):f,c:i,b:r}}remove(t){const{_:e,A:s}=this,{c:n,b:i}=t;e.remove(n),i&&s.remove(i)}_;A}class m{constructor(t,e){this.i=new Map,this.m=new y(t,e)}get(t){const{i:e,m:s}=this,n=e.get(t);if(n)return s.update(n.handle),n.val}set(t,e){const{i:s,m:n}=this,i=s.get(t);if(i)i.val=e,n.update(i.handle);else{const i=n.insert(()=>{const e=s.get(t);e&&(n.remove(e.handle),s.delete(t))});s.set(t,{handle:i,key:t,val:e})}}delete(t){const{i:e,m:s}=this,n=e.get(t);return!!n&&(s.remove(n.handle),e.delete(t))}i;m}let b=class{constructor(t,e){this.a2=new Promise(t=>{this.r=t}),this.J=e,t>0?this.j=setTimeout(()=>{this.j=void 0,this.r(!0),e?.()},t):(this.r(!0),e?.())}ak(t){const{j:e,r:s,J:n}=this;e&&clearTimeout(e),t>0?this.j=setTimeout(()=>{this.j=void 0,n?.(),s(!0)},t):(this.j=void 0,s(!0),n?.())}ae(){this.j&&(clearTimeout(this.j),this.j=void 0,this.r(!1))}al(){return this.a2}r;a2;j;J};class E extends c{}class T{constructor(t,e,s){let n=sessionStorage.getItem("jrSession");n||(n=crypto.randomUUID(),sessionStorage.setItem("jrSession",n)),this.b="",this.c=n,this.S=t,this.L="",this.B=e,this.f=s,this.M=this.M.bind(this);const i=()=>{throw new Error("JustrunAuthProvider shall be enabled before use")};this.authWithCredential=i,this.authWithOAuth2=i,this.resetAuthState=i,this.resetConnState=i}async init(t,e){const s=T.prototype;this.authWithCredential=s.authWithCredential,this.authWithOAuth2=s.authWithOAuth2,this.resetAuthState=s.resetAuthState,this.resetConnState=s.resetConnState,e.onConnectionStatus(this.ah.bind(this)),e.registerMessage(t,E),e.handleMessageWith(E,this.ai.bind(this));const{c:n,f:i}=this,r=this.T();if(r){const{cid:t,h:e}=r;if(Math.round(Date.now()/1e3)<=e)return void i(t,n)}i("","")}async preConnect(){const{b:t,c:e,e:s,f:n,B:i}=this;if(s)return n(t,e,s),"";const r=""===s;this.e=void 0;let o=this.T();if(o){const{cid:t,address:s,g:n,h:h}=o,a=Math.round(Date.now()/1e3);if(a<=n)return this.L=o.address,i(s,e,r);if(a<=h&&(o=await this.N("refresh",""),o))return this.L=o.address,i(o.address,e,r)}return this.e="unknown error",n("",""),""}async authWithCredential(t,e,s,n){await this.N(t,`${e},${s},${n}`)}authWithOAuth2(t,e,s,n){const i=`${e}?client_id=${s}&redirect_uri=${this.S}&scope=${n}&response_type=code`;window.location.href=`${i}&state=${this.c}~${s}~${encodeURI(t)}`}async resetAuthState(){await this.N("signout","")}resetConnState(t){if(this.e){this.e=t?"":void 0;const{b:e,c:s,f:n}=this;n(e,s)}}ah(t,e,s,n){if(t){this.a=e;const t=this.T();if(t){const{g:e}=t;this.C=new b(1e3*e-Date.now(),this.M)}}else{this.a=void 0,this.C&&(this.C.ae(),this.C=void 0);const t=this.e=n?.message||v.UnknownError,{b:e,c:s,f:i}=this;i(e,s,t)}}async M(){this.C=void 0;const{c:t,B:e}=this,s=await this.N("refresh","");if(s&&this.a){const{address:n,g:i}=s;if(n===this.L){const s=e(n,t),[r,o]=s.split("://");await fetch(`${r.replace("ws","http")}://${o}`),this.C=new b(1e3*i-Date.now(),this.M)}else this.a&&(this.a.close(),this.a=void 0)}}async ai(t){const{b:e,c:s,a:n}=this,{type:i,j:r}=t;"kick"===i&&n&&(n.close(),this.a=void 0,r&&(this.e=r,this.f(e,s,r)))}T(){const t=localStorage.getItem("jrAuth")||void 0;if(t){const[e,s,n,i]=t.split(","),{b:r,a:o}=this;return r&&e!==r&&o&&(o.close(),this.a=void 0),this.b=e,{cid:e,address:s,g:parseInt(n),h:parseInt(i)}}}async N(t,e){const s=await fetch(this.S,{method:"POST",body:`${t}:${e}`}).catch(t=>{throw new u(t.message)}),n=await s.text();if(!s.ok)throw new u(n);if(n.startsWith("auth:")){const t=n.substring(5);localStorage.setItem("jrAuth",t);const[e,s,i,r]=t.split(","),{b:o,a:h}=this;return o!==e&&(o&&h&&(h.close(),this.a=void 0),this.b=e,this.f(e,this.c,this.e)),{cid:e,address:s,g:parseInt(i),h:parseInt(r)}}if(n.startsWith("clear:"))localStorage.removeItem("jrAuth"),this.b="",this.e=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0);else if(n.startsWith("error:")){"refresh"!==t&&"signout"!==t||(localStorage.removeItem("jrAuth"),this.b="",this.e=void 0,this.f("",""),this.a&&(this.a.close(),this.a=void 0));const e=n.substring(6);throw new u(e)}}b;c;S;L;a;e;C;B;f}const C=new Error(v.NotAuthenticated);class P{constructor(t,e,s){this.n=t,this.s=e,this.t=!s}get pkgType(){return this.n.pkgType}get m(){return this.n.name}async v(t,e){const{buff:s,bodyOffset:n}=e,i=s.subarray(n),r=new this.n(i,!0);if(void 0===t.context&&this.t)l(t,C);else try{await this.s(t,r)}catch(e){e.isError||l(t,e)}void 0===t.context&&await t.close()}async u(t,e){if(void 0===t.context&&this.t)l(t,C);else try{return await this.s(t,e)}catch(e){e.isError||l(t,e)}}n;s;t}let S=class{constructor(t,e,s){this.n=t,this.s=e,this.t=!s}get pkgType(){return this.n.pkgType}get m(){return this.n.name}async v(t,e){const{buff:s,requestId:n,bodyOffset:i}=e,r=s.subarray(i),o=new this.n(r,!0);let h;if(void 0===t.context&&this.t)h=l(t,C);else try{await this.s(t,o)}catch(e){h=e.isError?e:l(t,e)}try{h?await t.sendErrorResponse(h,n):await t.sendResponse(o,n),void 0===t.context&&await t.close()}catch{return}}async u(t,e){if(void 0!==t.context||!this.t)try{return await this.s(t,e)}catch(e){throw e.isError?e:l(t,e)}throw l(t,C)}n;s;t},x=class{address(){return null}init(t){this.D=t}async C(t){return!1}async G(){return!1}async g(t){const e=new WebSocket(t);return new Promise((t,s)=>{e.onerror=t=>{s(new Error(v.UnknownError))},e.onopen=()=>{t(this.af(e,!0))}})}af=(t,e)=>{const s=new R(t),{conn:n,$:i,o:r}=this.D(s,e);t.onmessage=t=>{t.data.arrayBuffer().then(t=>{i(new Uint8Array(t))})};let o=!0;return t.onerror=t=>{o=!1,r(new Error(t.message||v.UnknownError))},t.onclose=t=>{o&&r(1e3===t.code?void 0:new Error(t.reason||"unknown error"))},n};D(t,e){throw new Error('Need to call "setConnWrapperMaker" before using')}},R=class{constructor(t){this.e=t}get socket(){return{localAddress:"",localPort:0,remoteAddress:"",remoteFamily:"",remotePort:0}}async A(t){if(this.e)return this.e.send(t),t.byteLength;throw new Error(v.InvalidConnection)}async n(t){if(this.e){const e=w(t);return this.e.send(e),e.byteLength}throw new Error(v.InvalidConnection)}async close(t){const{e:e}=this;e&&(this.e=void 0,t?(e.close(1e3,t.message),e.onerror(new ErrorEvent("error",{message:t.message})),e.onerror=e.onclose=null):e.readyState<=WebSocket.OPEN&&e.close())}B(){return!this.e}e};const A=(t,e,s)=>{const n=[e,t],i=(t=>{let e,s=0,n=0;for(;s<t.length;)for(n++,e=t[s++];e>>>=7;)n++;return n})(n),r=new Uint8Array(i);((t,e,s=0)=>{let n,i,r=s;for(n=0;n<t.length;n++){i=t[n];let s=127&i;for(;i>>>=7;)e[r++]=128|s,s=127&i;e[r++]=s}if(r<=e.length)return r-s;throw new Error("Buffer overflow")})(n,r),s.push(r)},I=t=>{const{g:[e,s],j:n}=((t,e,s=0)=>{let n,i,r=s,o=0,h=0;const a=[];for(n=0;n<t;n++){do{i=e[r++],o|=(127&i)<<h,h+=7}while(128&i);if(!(void 0!==i&&h<=35))throw new Error("Parsing failed");a.push(o),o=0,h=0}return{g:a,j:r-s}})(2,t);return{buff:t,pkgType:s,requestId:e,bodyOffset:n}};class ${constructor(t){this.a3=t}get id(){return this.a?.id??-1}get context(){return this.a?.context}set context(t){this.a&&(this.a.context=t)}localAddress;localPort;remoteAddress;remoteFamily;remotePort;async sendErrorResponse(t,e){return(this.a??await this.g()).sendErrorResponse(t,e)}async sendResponse(t,e){return(this.a??await this.g()).sendResponse(t,e)}async sendMessage(t){return(this.a??await this.g()).sendMessage(t)}async sendRequest(t){return(this.a??await this.g()).sendRequest(t)}async close(t){const{a:e}=this;if(e)return this.a=void 0,void await e.close(t);const{b:s}=this;s&&await s.then(e=>{s===this.b&&(this.b=void 0,this.a=void 0,e.close(t))},()=>{s===this.b&&(this.b=s,this.a=void 0)})}async am(){this.a||await this.g()}ag(){this.a=void 0,this.b=void 0}async g(){let{b:t}=this;return t||(t=this.b=new Promise((e,s)=>{this.a3().then(n=>{if(t===this.b&&(this.b=void 0,n))return e(n),void(this.a=n);n&&n.close(),s(new Error("Connect failed"))})})),await t}a3;a;b}class M{constructor(t,e){const{responsePkgType:s,connMonitor:n,makePkgBuff:i,parsePkgBuff:r}=e;this.responsePkgType=s,this.p=0,this.q=new Map,this.h=new Map,this.O=new Map,this.U=i,this.V=r,this.E=t,this.P=n;this.v=this.a5;const o=[];this.U(s,2097152,o),this.W={makePkgBuff:i,responsePkgType:s,j:w(o)},this.h.set(s,this),t.init((t,e)=>{do{this.p++}while(this.q.has(2097151&this.p));const s=new W(this.W,t,2097151&this.p);this.q.set(s.id,s),s.handle=this.P?.insert(s.forceClose.bind(s),s.keepAlive.bind(s));const n={conn:s,$:t=>this.a6(s,t),o:t=>this.a7(s,t)};return this.H?.(this,s,!!e),n})}responsePkgType;context;H;F;address(){return this.E.address()}M(t){return this.q.get(t)}g(t){return this.E.g(t)}async N(){do{this.p++}while(this.q.has(2097151&this.p));const t=new q(2097151&this.p,this);return this.q.set(t.id,t),t}async R(t){return this.E.C(t)}async S(){return this.E.G()}a8(t,e){const s=e.constructor.pkgType,n=this.h.get(s);if(n)return n?.u(t,e);throw new Error(v.InvalidPackage)}a9(t,e){const s=e.constructor.pkgType,n=this.h.get(s);if(n)return n?.u(t,e);throw new Error(v.InvalidPackage)}registerError(t,e){e.registerPkgType(t),this.O.set(t,e);const s=this.h.get(this.responsePkgType);this.h.set(t,s)}registerMessage(t,e){e.registerPkgType(t)}registerRequest(t,e){e.registerPkgType(t)}handleMessageWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.m} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.h.set(e,t),t}handleRequestWith(t){const e=t.pkgType;if(typeof e!=typeof this.responsePkgType)throw new Error(`Wrapper ${t.m} has an incompatible pkgType ${typeof e}`);if(this.h.has(e))throw new Error(`Wrapper ${t.m} is already handled by another handler`);return this.h.set(e,t),t}aj(t){const e=t.pkgType;return this.h.get(e)===t&&(this.h.delete(e),!0)}a6(t,e){t.handle?.onReceive(e.byteLength);const s=this.V(e),n=this.h.get(s.pkgType);n?n.v(t,s):t.close(new Error(v.InvalidPackage))}a7(t,e){this.q.delete(t.id),this.P?.remove(t.handle),t.o(e),this.F?.(this,t,t.d.B(),e)}a5(t,e){try{const{buff:s,pkgType:n,requestId:i,bodyOffset:r}=e;if(n===this.responsePkgType){const e=s.subarray(r);t.X(i,e)}else{const e=this.O.get(n);if(e){const n=new e(s.subarray(r),!0);t.aa(i,n)}}}catch{t.close(new Error(v.InvalidPackage))}}W;p;U;V;E;q;h;O;P}class W{constructor(t,e,s){this.id=s,this.d=e,this.y=t,this.Y=0}context;handle;id;d;get socket(){return this.d.socket}async sendMessage(t){const e=t.constructor.pkgType,s=[t.buff];this.y.makePkgBuff(e,0,s);const n=await this.d.n(s);this.handle?.onSend(n)}sendRequest(t){return this.l=new Map,this.sendRequest=this.Z,this.X=this.ab,this.o=this.ac,this.Z(t)}async sendErrorResponse(t,e){const s=t.constructor.pkgType,n=[t.buff];this.y.makePkgBuff(s,e,n);const i=await this.d.n(n);this.handle?.onSend(i)}async sendResponse(t,e){const s=[t.respBuff],{makePkgBuff:n,responsePkgType:i}=this.y;n(i,e,s);const r=await this.d.n(s);this.handle?.onSend(r)}async close(t){await this.d.close(t)}X(t,e){2097152===t&&void 0===this.context&&this.close(new Error(v.AuthTimeout))}aa(t,e){const s=this.l.get(t);if(s)return this.l.delete(t),s.i(e)}keepAlive(){const{j:t}=this.y;this.d.A(t).catch(f),this.handle?.onSend(t.byteLength)}forceClose(t){this.close(new Error(t??v.UnknownError))}o(t){}async Z(t){const e=2097151&this.Y++,s=t.constructor.pkgType,n=[t.buff];this.y.makePkgBuff(s,e,n);const i=new Promise((t,s)=>{const i={c:t,i:s};this.l.set(e,i),this.d.n(n).then(t=>{this.handle?.onSend(t)},t=>{this.l.delete(e),s(t)})});t.respBuff=await i}ab(t,e){const s=this.l.get(t);if(s)return this.l.delete(t),void s.c(e);2097152===t&&void 0===this.context&&this.close(new Error(v.AuthTimeout))}ac(t){const e=this.l;if(e.size>0){t||(t=new Error(v.ConnectionClosed));for(const[s,n]of e)e.delete(s),n.i(t)}this.l=void 0}y;l;Y}class q{constructor(t,e){this.id=t,this.Q=e}context;id;socket;get remoteFamily(){return"Local"}async sendMessage(t){return this.Q.a8(this,t)}async sendRequest(t){return this.Q.a9(this,t)}sendErrorResponse(t,e){throw null}sendResponse(t,e){throw null}async close(t){}Q}const N=(t,e)=>new O(t,{responsePkgType:0,makePkgBuff:A,parsePkgBuff:I,connMonitor:e});var j;!function(t){t[t.NotConnected=0]="NotConnected",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected"}(j||(j={}));class O{constructor(t,e){const s=new x,n=this.k=new M(s,e);this.G=j.NotConnected,this.a4=t,this.a=new $(()=>this.g()),n.H=this.H.bind(this),n.F=this.F.bind(this)}getConnState(){return this.G}enableAuthenticate(t,e){this.K=e,e.init(t,this)}registerError(t,e){return this.k.registerError(t,e)}registerMessage(t,e){return this.k.registerMessage(t,e)}registerRequest(t,e){return this.k.registerRequest(t,e)}handleMessageWith(t,e){this.k.handleMessageWith(new P(t,(t,s)=>e(s.data),!0))}handleRequestWith(t,e){this.k.handleRequestWith(new S(t,async(t,s)=>{s.resp=await e(s.data)},!0))}sendMessage(t){return this.a.sendMessage(t)}async sendRequest(t){return await this.a.sendRequest(t),t.resp}onConnectionStatus(t){let{c:e}=this;e||(this.c=e=[]),e.push(t)}async g(){const{k:t,K:e}=this;this.G=j.Connecting;try{const s=e?await e.preConnect():this.a4;if(!s)throw new Error(v.UnknownError);return await t.g(s)}catch(e){const s=e instanceof Error?e:new Error(v.UnknownError);this.F(t,this.a,!0,s)}}H(t,e,s){if(this.G=j.Connected,e.context="",this.c)for(const t of this.c)t(!0,e,s)}F(t,e,s,n){if(this.G=j.NotConnected,this.a.ag(),this.c)for(const t of this.c)t(!1,e,s,n)}a4;k;a;G;K;c}export{u as CommonError,k as ConnAliveMonitor,s as ErrorWrapper,i as EventWrapper,a as JsonError,c as JsonMessage,d as JsonRequest,T as JustrunAuthProvider,n as MessageWrapper,v as NetErrorString,r as RequestWrapper,m as TimeoutCache,y as TimeoutMonitor,O as WsClient,N as createNumPkgTypeClient,g as handleUncaughtErrorWith};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "justrun-ws",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "module": "./lib/index.min.js",
5
5
  "typings": "./lib/index.d.ts",
6
6
  "exports": {