wspromisify 2.10.1 → 2.11.2

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.
package/dist/bundle.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const t=Symbol("Placeholder"),e=e=>{let n=0;for(const s of e)s!==t&&n++;return n},n=(e,n)=>{const s=e.length,i=e.slice(),o=n.length;let r=o,l=0;for(;r&&l<s;l++)i[l]===t&&(i[l]=n[o-r],r--);for(l=s;r;l++,r--)i[l]=n[o-r];return i},s=(t,i,o)=>{const r=t.length-i.length-e(o);if(r<1)return t(...n(i,o));{const e=(...e)=>s(t,n(i,o),e);return e.$args_left=r,e}},i=t=>(...n)=>t.length>e(n)?s(t,[],n):t(...n);function o(e){return function(n,...s){return s.length>0?n===t?(e=>function(n){return n===t?e:e(n)})((t=>e(t,s[0]))):e(n,s[0]):t=>e(n,t)}}function r(t){return i(t)}const l=t=>t.length,c=/^(.*?)(8|16|32|64)(Clamped)?Array$/,u=void 0,a=1/0,h=t=>typeof t,d=t=>null===t,f=t=>"number"==h(t);const p=t=>d(t)||(t=>t===u)(t),g={u:"U",b:"B",n:"N",s:"S",f:"F"},m=Symbol(),y=t=>{const e=h(t);return"object"===e?d(t)?"Null":t.constructor.name:g[e[0]]+e.slice(1)},_=o(((t,e)=>y(e)===t)),w=o(((t,e)=>t===e)),b=o(((t,e)=>{const n=y(t);if(w(n,y(e))&&(w(n,"Object")||w(n,"Array")||(t=>c.test(t))(n))){if(d(t)||d(e))return w(t,e);if(w(t,e))return!0;for(const n of[t,e])for(const s in n)if(!(w(n,e)&&s in t||w(n,t)&&s in e&&b(t[s],e[s])))return!1;return!0}return w(t,e)})),k=o(((t,e)=>(e.push(t),e))),S=r(((t,e,n)=>n.reduce(t,e))),P=o(((t,e)=>{const n=(t=>Array.isArray(t))(e);let s,i;n&&(s=0,i=[]);for(let s in e)t(e[s],s)||(n?i.push(+s):delete e[s]);if(n)for(const t of i)e.splice(t-s++,1);return e})),v=i(((t,e,n,s)=>t(s)?e(s):n(s))),E=(...e)=>(...n)=>{let s,i=!0;for(let o=l(e)-1;o>-1;o--)i?(i=!1,s=e[o](...n)):s=s===t?e[o]():e[o](s);return s},A=o(((t,e)=>e[t])),C=r(((t,e,n)=>n.slice(t,f(e)?e:a))),j=A(0);C(1,a);const N=o(((t,e)=>e.find(t))),W=t=>()=>t,$=o(((t,e)=>(t(e),e))),q=W(!0),O=W(!1),T=o(((t,e)=>e(...t))),x=t=>(...e)=>{const n=t(...e),s=function(t){return"function"===h(t)}(n);return s&&n.$args_left?x(n):(t=>!t)(n)},z=o(((t,e)=>S(((e,n)=>N((e=>t(n,e)),e)?e:k(n,e)),[],e)));z(b);const Q=t=>{let e,n=!1;return function(...s){return n?e:(n=!0,e=t(...s))}},R=(t,e,n)=>l(e)?p(n)?t:E((s=>s in n?R(t,C(1,a,e),n[s]):t),j)(e):n,B=r(R);B(u),E(v(b(m),O,q),B(m));const M=r(((t,e,n)=>e(n)&&t(n))),I=x,D=Symbol("Placeholder"),L=t=>{let e=0;for(const n of t)n!==D&&e++;return e},U=(t,e)=>{const n=t.length,s=t.slice(),i=e.length;let o=i,r=0;for(;o&&r<n;r++)s[r]===D&&(s[r]=e[i-o],o--);for(r=n;o;r++,o--)s[r]=e[i-o];return s},F=(t,e,n)=>{const s=t.length-e.length-L(n);if(s<1)return t(...U(e,n));{const i=(...s)=>F(t,U(e,n),s);return i.$args_left=s,i}},J=t=>(...e)=>t.length>L(e)?F(t,[],e):t(...e);function G(t){return function(e,...n){return n.length>0?e===D?(t=>function(e){return e===D?t:t(e)})((e=>t(e,n[0]))):t(e,n[0]):n=>t(e,n)}}function H(t){return J(t)}const K=t=>t.length,V=/^(.*?)(8|16|32|64)(Clamped)?Array$/,X=void 0,Y=1/0,Z=t=>typeof t,tt=t=>null===t,et={u:"U",b:"B",n:"N",s:"S",f:"F"},nt=Symbol(),st=t=>{const e=Z(t);return"object"===e?tt(t)?"Null":t.constructor.name:et[e[0]]+e.slice(1)},it=G(((t,e)=>st(e)===t)),ot=G(((t,e)=>t===e)),rt=G(((t,e)=>{const n=st(t);if(ot(n,st(e))&&(ot(n,"Object")||ot(n,"Array")||(s=n,V.test(s)))){if(tt(t)||tt(e))return ot(t,e);if(ot(t,e))return!0;for(const n of[t,e])for(const s in n)if(!(ot(n,e)&&s in t||ot(n,t)&&s in e&&rt(t[s],e[s])))return!1;return!0}var s;return ot(t,e)})),lt=G(((t,e)=>(e.push(t),e))),ct=H(((t,e,n)=>n.reduce(t,e))),ut=J(((t,e,n,s)=>t(s)?e(s):n(s))),at=H(((t,e,n)=>ut(t,e,yt,n))),ht=(...t)=>(...e)=>{let n,s=!0;for(let i=K(t)-1;i>-1;i--)s?(s=!1,n=t[i](...e)):n=n===D?t[i]():t[i](n);return n},dt=G(((t,e)=>e[t])),ft=H(((t,e,n)=>n.slice(t,(t=>"number"==Z(t))(e)?e:Y))),pt=dt(0);ft(1,Y);const gt=G(((t,e)=>e.find(t))),mt=t=>()=>t,yt=t=>t,_t=G(((t,e)=>e.split(t))),wt=mt(!0),bt=mt(!1),kt=G(((t,e)=>ct(((e,n)=>gt((e=>t(n,e)),e)?e:lt(n,e)),[],e)))(rt),St=(t,e,n)=>K(e)?(t=>tt(t)||(t=>t===X)(t))(n)?t:ht((s=>s in n?St(t,ft(1,Y,e),n[s]):t),pt)(e):n,Pt=H(St);Pt(X),ht(ut(rt(nt),bt,wt),Pt(nt));const vt=G(((t,e)=>e.map(t))),{floor:Et}=Math,At="0123456789abcdefghijklmnopqrstuvwxyz",Ct=it("String"),jt=at(Ct,_t("")),Nt=ht((t=>Object.fromEntries(t)),vt(((t,e)=>[t,e])),jt);class Wt{is_str;delim;abc;abclen;c2pos;standard;setABC(t,e=""){if(this.is_str=Ct(t),this.delim=e,!ht(ot(K(n=t)),K,kt,jt)(n))throw new Error("Not all chars are unique!");var n;this.abc=t,this.abclen=K(t),this.standard=!!this.is_str&&At.startsWith(t),this.c2pos=Nt(t)}zip(t){const{abc:e,abclen:n,delim:s}=this;let i="",o=!0;for(;t>0;)i=e[t%n]+(o?"":s)+i,t=Et(t/n),o=!1;return i||"0"}unzip(t){const{standard:e,abclen:n,c2pos:s,delim:i,is_str:o}=this;if("0"===t)return 0;if(e)return parseInt(t,n);const r=o?t:t.split(i),l=K(r);let c=0;for(let t=0;t<l;t++)c+=s[r[t]]*n**(l-t-1);return c}constructor(t,e){e?this.setABC(t,e):this.setABC(t||At+"ABCDEFGHIJKLMNOPQRSTUVWXYZ")}}const $t=new Wt;$t.setABC.bind($t),$t.zip.bind($t),$t.unzip.bind($t);const qt=(()=>{try{return WebSocket||null}catch{return null}})(),Ot=(t,e,n)=>t.addEventListener(e,n),Tt=(t,e)=>setTimeout(e,t),xt={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,reconnection_attempts:1/0,max_idle_time:1/0,lazy:!1,socket:null,adapter:(t,e)=>new WebSocket(t,e),encode:(t,e,{server:n})=>JSON.stringify({[n.id_key]:t,[n.data_key]:e}),decode:t=>JSON.parse(t),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"},ping:{interval:55,content:{}}},{random:zt}=Math,Qt=new Wt,Rt=T([]),Bt=M(_("Number"),I(isNaN)),Mt={_is_ping:!0},It=t=>t&&clearTimeout(t),Dt=t=>{const e=Qt.zip(2147483637*zt()|0);return e in t?Dt(t):e};class Lt{ws=null;intentionally_closed=!1;reconnect_timeout=null;queue={};onReadyQueue=[];onCloseQueue=[];handlers={open:[],close:[],message:[],error:[],timeout:[]};config={};ping_timer=null;idle_timer=null;get opened(){return 1===this.ws?.readyState}init_flush(){P(O,this.queue)}call(t,...e){for(const n of this.handlers[t])n(...e)}log(t,e=null,n=null){const{config:s}=this;setTimeout((()=>{null===n?s.timer?s.log(t,null,e):s.log(t,e):s.log(t,n,e)}))}resetPing(){const{config:{ping:t},ping_timer:e}=this;t&&(p(e)||clearTimeout(e),this.ping_timer=Tt(1e3*t.interval,(async()=>{const{ping_timer:e,opened:n}=this;n?(await this.send(t.content,Mt),this.resetPing()):clearTimeout(e)})))}resetIdle(){const{config:{max_idle_time:t},idle_timer:e}=this;t!==1/0&&(p(e)||clearTimeout(e),this.idle_timer=Tt(1e3*t,(()=>this.opened&&this.close())))}initSocket(t){const{queue:e,config:n}=this;this.ws=t,this.onReadyQueue.forEach((t=>t())),this.onReadyQueue.splice(0);const{id_key:s,data_key:i}=n.server;this.call("open",t);for(const n in e)t.send(e[n].msg);null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),this.resetPing(),this.resetIdle(),Ot(t,"close",(async(...t)=>{this.ws=null,this.onCloseQueue.forEach(Rt),this.onCloseQueue.splice(0),this.call("close",...t);let{reconnect:e,reconnection_attempts:s}=n;if(Bt(e)){const t=async()=>{if(this.intentionally_closed||!s)return;s--,this.log("reconnect"),p(this.ws)||(this.ws.close(),this.ws=null);const n=await this.connect();p(n)||(this.reconnect_timeout=setTimeout(t,1e3*e))};t()}})),Ot(t,"message",(t=>{try{const e=n.decode(t.data);this.call("message",{...t,data:e});let o=!1;if(_("Object",e)&&s in e){const t=this.queue[e[s]];if(t){const n=t.sent_time?Date.now()-t.sent_time:null;this.log("message",e[i],n),t.ff(e[i]),o=!0}}o||this.log("message-ext",e)}catch(e){console.error(e,`WSP: Decode error. Got: ${t.data}`)}this.resetPing()}))}opening=!1;connect(){return new Promise((t=>{if(this.opened||this.opening)return t(null);this.opening=!0;const e=this.config,n=e.socket||e.adapter(e.url,e.protocols);if(!n||n.readyState>1)return this.opening=!1,this.ws=null,this.log("error","ready() on closing or closed state! status 2."),t(2);const s=Q((e=>{this.opening=!1,t(e)}));Ot(n,"error",Q((t=>{this.ws=null,this.log("error","status 3. Err: "+t.message),this.call("error",t),s(3)}))),n.readyState?(this.initSocket(n),s(null)):Ot(n,"open",Q((()=>{this.log("open"),this.initSocket(n),s(null)})))}))}get socket(){return this.ws}async ready(){return new Promise((t=>{this.config.lazy||this.opened?t():this.onReadyQueue.push(t)}))}on(t,e,n=q,s=!1){const i=t=>n(t)&&e(t);return s?Ot(this.ws,t,i):this.handlers[t].push(i),i}off(t,e,n=!1){if(n)return((t,e,n)=>t.removeEventListener(e,n))(this.ws,t,e);const s=this.handlers[t],i=s.indexOf(e);~i&&s.splice(i,1)}async close(){return new Promise(((t,e)=>{null===this.ws?e("WSP: closing a non-inited socket!"):(this.onCloseQueue.push((()=>{this.init_flush(),t(null)})),this.ws.close(),this.ws=null,this.intentionally_closed=!0)}))}open(){if(!this.opened)return this.intentionally_closed=!1,this.connect()}async prepareMessage(t,e={}){this.log(e._is_ping?"ping":"send",t);const{config:n,queue:s}=this,{pipes:i,server:{data_key:o}}=n,{top:r,_is_ping:l}=e,c=Dt(s);if("object"==typeof r&&r[o])throw new Error(`Attempting to set data key/token via ${e._is_ping?"ping":"send"}() options!`);for(const e of i)t=e(t);const[u,a]=await Promise.all([n.encode(c,t,n),this.connect()]);if(a)throw new Error("ERR while opening connection #"+a);const h=$((()=>delete this.queue[c]));return this.opened&&(Tt(0,(()=>this.ws.send(u))),this.resetPing(),l||this.resetIdle()),{id:c,msg:u,timeout:e=>Tt(n.timeout,(()=>{c in s&&(this.call("timeout",t),e({"Websocket timeout expired":n.timeout,"for the message":t}),h())})),cleanup:h}}async send(t,e={}){const{id:n,msg:s,timeout:i,cleanup:o}=await this.prepareMessage(t,e),{queue:r,config:l}=this;return new Promise(((t,e)=>{const o=i(e);r[n]={msg:s,data_type:l.data_type,sent_time:l.timer?Date.now():null,ff(e){It(o),t(e)}}})).finally(o)}async*stream(t,e={}){const{id:n,msg:s,timeout:i,cleanup:o}=await this.prepareMessage(t,e),{queue:r,config:l}=this;let c,u=!1,a=null;for(r[n]={msg:s,ff:t=>{t?.done&&(delete t.done,u=!0,setTimeout(o)),c(t)},data_type:l.data_type,sent_time:l.timer?Date.now():null};!u;)yield await new Promise(((t,e)=>{a=i(e),c=t})).catch((t=>o(t))).finally((()=>{It(a),a=null}))}constructor(t={}){this.config=(t=>{if(null===qt&&!("adapter"in t))throw new Error("\n This platform has no native WebSocket implementation.\n Please use 'ws' package as an adapter.\n See https://github.com/houd1ni/WebsocketPromisify/issues/23\n ");const e=Object.assign({},xt,t),n=e.url;if("/"==n[0])try{const t=location.protocol.includes("s:")?"wss":"ws";e.url=`${t}://${location.hostname}:${location.port}${n}`}catch(t){throw new Error("WSP: URL starting with / in non-browser environment!")}return e})(t),this.config.lazy||this.connect()}}exports.WebSocketClient=Lt,exports.default=Lt;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e=Symbol("Placeholder"),t=t=>{let n=0;for(const s of t)s!==e&&n++;return n},n=(t,n)=>{const s=t.length,i=t.slice(),o=n.length;let r=o,l=0;for(;r&&l<s;l++)i[l]===e&&(i[l]=n[o-r],r--);for(l=s;r;l++,r--)i[l]=n[o-r];return i},s=(e,i,o)=>{const r=e.length-i.length-t(o);if(r<1)return e(...n(i,o));{const t=(...t)=>s(e,n(i,o),t);return t.$args_left=r,t}},i=e=>(...n)=>e.length>t(n)?s(e,[],n):e(...n);function o(t){return function(n,...s){return s.length>0?n===e?(t=>function(n){return n===e?t:t(n)})((e=>t(e,s[0]))):t(n,s[0]):e=>t(n,e)}}function r(e){return i(e)}const l=e=>e.length,c=/^(.*?)(8|16|32|64)(Clamped)?Array$/,u=void 0,a=1/0,h=e=>typeof e,d=e=>null===e,f=e=>"number"==h(e);const p=e=>d(e)||(e=>e===u)(e),g={u:"U",b:"B",n:"N",s:"S",f:"F"},m=Symbol(),y=e=>{const t=h(e);return"object"===t?d(e)?"Null":e.constructor.name:g[t[0]]+t.slice(1)},_=o(((e,t)=>y(t)===e)),w=o(((e,t)=>e===t)),b=o(((e,t)=>{const n=y(e);if(w(n,y(t))&&(w(n,"Object")||w(n,"Array")||(e=>c.test(e))(n))){if(d(e)||d(t))return w(e,t);if(w(e,t))return!0;for(const n of[e,t])for(const s in n)if(!(w(n,t)&&s in e||w(n,e)&&s in t&&b(e[s],t[s])))return!1;return!0}return w(e,t)})),k=o(((e,t)=>(t.push(e),t))),S=r(((e,t,n)=>n.reduce(e,t))),v=o(((e,t)=>{const n=(e=>Array.isArray(e))(t);let s,i;n&&(s=0,i=[]);for(let s in t)e(t[s],s)||(n?i.push(+s):delete t[s]);if(n)for(const e of i)t.splice(e-s++,1);return t})),P=i(((e,t,n,s)=>e(s)?t(s):n(s))),E=(...t)=>(...n)=>{let s,i=!0;for(let o=l(t)-1;o>-1;o--)i?(i=!1,s=t[o](...n)):s=s===e?t[o]():t[o](s);return s},A=o(((e,t)=>t[e])),C=r(((e,t,n)=>n.slice(e,f(t)?t:a))),j=A(0);C(1,a);const N=o(((e,t)=>t.find(e))),W=e=>()=>e,$=o(((e,t)=>(e(t),t))),q=W(!0),O=W(!1),T=o(((e,t)=>t(...e))),x=e=>(...t)=>{const n=e(...t),s=function(e){return"function"===h(e)}(n);return s&&n.$args_left?x(n):(e=>!e)(n)},z=o(((e,t)=>S(((t,n)=>N((t=>e(n,t)),t)?t:k(n,t)),[],t)));z(b);const Q=e=>{let t,n=!1;return function(...s){return n?t:(n=!0,t=e(...s))}},R=(e,t,n)=>l(t)?p(n)?e:E((s=>s in n?R(e,C(1,a,t),n[s]):e),j)(t):n,B=r(R);B(u),E(P(b(m),O,q),B(m));const M=r(((e,t,n)=>t(n)&&e(n))),I=x,L=Symbol("Placeholder"),D=e=>{let t=0;for(const n of e)n!==L&&t++;return t},U=(e,t)=>{const n=e.length,s=e.slice(),i=t.length;let o=i,r=0;for(;o&&r<n;r++)s[r]===L&&(s[r]=t[i-o],o--);for(r=n;o;r++,o--)s[r]=t[i-o];return s},F=(e,t,n)=>{const s=e.length-t.length-D(n);if(s<1)return e(...U(t,n));{const i=(...s)=>F(e,U(t,n),s);return i.$args_left=s,i}},J=e=>(...t)=>e.length>D(t)?F(e,[],t):e(...t);function G(e){return function(t,...n){return n.length>0?t===L?(e=>function(t){return t===L?e:e(t)})((t=>e(t,n[0]))):e(t,n[0]):n=>e(t,n)}}function H(e){return J(e)}const K=e=>e.length,V=/^(.*?)(8|16|32|64)(Clamped)?Array$/,X=void 0,Y=1/0,Z=e=>typeof e,ee=e=>null===e,te={u:"U",b:"B",n:"N",s:"S",f:"F"},ne=Symbol(),se=e=>{const t=Z(e);return"object"===t?ee(e)?"Null":e.constructor.name:te[t[0]]+t.slice(1)},ie=G(((e,t)=>se(t)===e)),oe=G(((e,t)=>e===t)),re=G(((e,t)=>{const n=se(e);if(oe(n,se(t))&&(oe(n,"Object")||oe(n,"Array")||(s=n,V.test(s)))){if(ee(e)||ee(t))return oe(e,t);if(oe(e,t))return!0;for(const n of[e,t])for(const s in n)if(!(oe(n,t)&&s in e||oe(n,e)&&s in t&&re(e[s],t[s])))return!1;return!0}var s;return oe(e,t)})),le=G(((e,t)=>(t.push(e),t))),ce=H(((e,t,n)=>n.reduce(e,t))),ue=J(((e,t,n,s)=>e(s)?t(s):n(s))),ae=H(((e,t,n)=>ue(e,t,ye,n))),he=(...e)=>(...t)=>{let n,s=!0;for(let i=K(e)-1;i>-1;i--)s?(s=!1,n=e[i](...t)):n=n===L?e[i]():e[i](n);return n},de=G(((e,t)=>t[e])),fe=H(((e,t,n)=>n.slice(e,(e=>"number"==Z(e))(t)?t:Y))),pe=de(0);fe(1,Y);const ge=G(((e,t)=>t.find(e))),me=e=>()=>e,ye=e=>e,_e=G(((e,t)=>t.split(e))),we=me(!0),be=me(!1),ke=G(((e,t)=>ce(((t,n)=>ge((t=>e(n,t)),t)?t:le(n,t)),[],t)))(re),Se=(e,t,n)=>K(t)?(e=>ee(e)||(e=>e===X)(e))(n)?e:he((s=>s in n?Se(e,fe(1,Y,t),n[s]):e),pe)(t):n,ve=H(Se);ve(X),he(ue(re(ne),be,we),ve(ne));const Pe=G(((e,t)=>t.map(e))),{floor:Ee}=Math,Ae="0123456789abcdefghijklmnopqrstuvwxyz",Ce=ie("String"),je=ae(Ce,_e("")),Ne=he((e=>Object.fromEntries(e)),Pe(((e,t)=>[e,t])),je);class We{is_str;delim;abc;abclen;c2pos;standard;setABC(e,t=""){if(this.is_str=Ce(e),this.delim=t,!he(oe(K(n=e)),K,ke,je)(n))throw new Error("Not all chars are unique!");var n;this.abc=e,this.abclen=K(e),this.standard=!!this.is_str&&Ae.startsWith(e),this.c2pos=Ne(e)}zip(e){const{abc:t,abclen:n,delim:s}=this;let i="",o=!0;for(;e>0;)i=t[e%n]+(o?"":s)+i,e=Ee(e/n),o=!1;return i||"0"}unzip(e){const{standard:t,abclen:n,c2pos:s,delim:i,is_str:o}=this;if("0"===e)return 0;if(t)return parseInt(e,n);const r=o?e:e.split(i),l=K(r);let c=0;for(let e=0;e<l;e++)c+=s[r[e]]*n**(l-e-1);return c}constructor(e,t){t?this.setABC(e,t):this.setABC(e||Ae+"ABCDEFGHIJKLMNOPQRSTUVWXYZ")}}const $e=new We;$e.setABC.bind($e),$e.zip.bind($e),$e.unzip.bind($e);const qe=(()=>{try{return WebSocket||null}catch{return null}})(),Oe=(e,t,n)=>e.addEventListener(t,n),Te=(e,t)=>setTimeout(t,e),xe={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,reconnection_attempts:1/0,max_idle_time:1/0,lazy:!1,socket:null,adapter:(e,t)=>new WebSocket(e,t),encode:(e,t,{server:n})=>JSON.stringify({[n.id_key]:e,[n.data_key]:t}),decode:e=>JSON.parse(e),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"},ping:{interval:55,content:{}}},{random:ze}=Math,Qe=new We,Re=T([]),Be=M(_("Number"),I(isNaN)),Me={_is_ping:!0},Ie=e=>e&&clearTimeout(e),Le=e=>{const t=Qe.zip(2147483637*ze()|0);return t in e?Le(e):t};class De{ws=null;intentionally_closed=!1;reconnect_timeout=null;queue={};onReadyQueue=[];onCloseQueue=[];handlers={open:[],close:[],message:[],error:[],timeout:[]};config={};ping_timer=null;idle_timer=null;get opened(){return 1===this.ws?.readyState}init_flush(){v(O,this.queue)}call(e,...t){for(const n of this.handlers[e])n(...t)}log(e,t=null,n=null){const{config:s}=this;setTimeout((()=>{null===n?s.timer?s.log(e,null,t):s.log(e,t):s.log(e,n,t)}))}resetPing(){const{config:{ping:e},ping_timer:t}=this;e&&(p(t)||clearTimeout(t),this.ping_timer=Te(1e3*e.interval,(async()=>{const{ping_timer:t,opened:n}=this;n?(await this.send(e.content,Me),this.resetPing()):clearTimeout(t)})))}resetIdle(){const{config:{max_idle_time:e},idle_timer:t}=this;e!==1/0&&(p(t)||clearTimeout(t),this.idle_timer=Te(1e3*e,(()=>this.opened&&this.close())))}initSocket(e){const{queue:t,config:n}=this;this.ws=e,this.onReadyQueue.forEach((e=>e())),this.onReadyQueue.splice(0);const{id_key:s,data_key:i}=n.server;this.call("open",e);for(const n in t)e.send(t[n].msg);null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),this.resetPing(),this.resetIdle(),Oe(e,"close",(async(...e)=>{this.ws=null,this.onCloseQueue.forEach(Re),this.onCloseQueue.splice(0),this.call("close",...e);let{reconnect:t,reconnection_attempts:s}=n;if(Be(t)){const e=async()=>{if(this.intentionally_closed||!s)return;s--,this.log("reconnect"),p(this.ws)||(this.ws.close(),this.ws=null);const n=await this.connect();p(n)||(this.reconnect_timeout=setTimeout(e,1e3*t))};e()}})),Oe(e,"message",(e=>{try{const t=n.decode(e.data);this.call("message",{...e,data:t});let o=!1;if(_("Object",t)&&s in t){const e=this.queue[t[s]];if(e){const n=e.sent_time?Date.now()-e.sent_time:null;this.log("message",t[i],n),e.ff(t[i]),o=!0}}o||this.log("message-ext",t)}catch(t){console.error(t,`WSP: Decode error. Got: ${e.data}`)}this.resetPing()}))}opening=!1;connect(){return new Promise((e=>{if(this.opened||this.opening)return e(null);this.opening=!0;const t=this.config,n=t.socket||t.adapter(t.url,t.protocols);if(!n||n.readyState>1)return this.opening=!1,this.ws=null,this.log("error","ready() on closing or closed state! status 2."),e(2);const s=Q((t=>{this.opening=!1,e(t)}));Oe(n,"error",Q((e=>{this.ws=null,this.log("error","status 3. Err: "+e.message),this.call("error",e),s(3)}))),n.readyState?(this.initSocket(n),s(null)):Oe(n,"open",Q((()=>{this.log("open"),this.initSocket(n),s(null)})))}))}get socket(){return this.ws}async ready(){return new Promise((e=>{this.config.lazy||this.opened?e():this.onReadyQueue.push(e)}))}on(e,t,n=q,s=!1){const i=e=>n(e)&&t(e);return s?Oe(this.ws,e,i):this.handlers[e].push(i),i}off(e,t,n=!1){if(n)return((e,t,n)=>e.removeEventListener(t,n))(this.ws,e,t);const s=this.handlers[e],i=s.indexOf(t);~i&&s.splice(i,1)}async close(){return new Promise(((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.onCloseQueue.push((()=>{this.init_flush(),e(null)})),this.ws.close(),this.ws=null,this.intentionally_closed=!0)}))}open(){if(!this.opened)return this.intentionally_closed=!1,this.connect()}addEventListener(e,t,n={}){return this.on(e,t,n.predicate,n.raw)}removeEventListener(e,t,n={}){return this.off(e,t,n.raw)}async prepareMessage(e,t={}){this.log(t._is_ping?"ping":"send",e);const{config:n,queue:s}=this,{pipes:i,server:{data_key:o}}=n,{top:r,_is_ping:l}=t,c=Le(s);if("object"==typeof r&&r[o])throw new Error(`Attempting to set data key/token via ${t._is_ping?"ping":"send"}() options!`);for(const t of i)e=t(e);const[u,a]=await Promise.all([n.encode(c,e,n),this.connect()]);if(a)throw new Error("ERR while opening connection #"+a);const h=$((()=>delete this.queue[c]));return{id:c,msg:u,timeout:t=>Te(n.timeout,(()=>{c in s&&(this.call("timeout",e),t({"Websocket timeout expired":n.timeout,"for the message":e}),h())})),cleanup:h,send:()=>this.opened&&(this.ws.send(u),this.resetPing(),!l&&this.resetIdle())}}async send(e,t={}){const{id:n,msg:s,timeout:i,cleanup:o,send:r}=await this.prepareMessage(e,t),{queue:l,config:c}=this;return new Promise(((e,t)=>{const o=i(t);l[n]={msg:s,data_type:c.data_type,sent_time:c.timer?Date.now():null,ff(t){Ie(o),e(t)}},r()})).finally(o)}async*stream(e,t={}){const{id:n,msg:s,timeout:i,cleanup:o,send:r}=await this.prepareMessage(e,t),{queue:l,config:c}=this;let u,a=!1,h=null;for(l[n]={msg:s,ff:e=>{e?.done&&(delete e.done,a=!0,setTimeout(o)),u(e)},data_type:c.data_type,sent_time:c.timer?Date.now():null},r();!a;)yield await new Promise(((e,t)=>{h=i(t),u=e})).catch((e=>o(e))).finally((()=>{Ie(h),h=null}))}constructor(e={}){this.config=(e=>{if(null===qe&&!("adapter"in e))throw new Error("\n This platform has no native WebSocket implementation.\n Please use 'ws' package as an adapter.\n See https://github.com/houd1ni/WebsocketPromisify/issues/23\n ");const t=Object.assign({},xe,e),n=t.url;if("/"==n[0])try{const e=location.protocol.includes("s:")?"wss":"ws";t.url=`${e}://${location.hostname}:${location.port}${n}`}catch(e){throw new Error("WSP: URL starting with / in non-browser environment!")}return t})(e),this.config.lazy||this.connect()}}exports.WebSocketClient=De,exports.default=De;
package/dist/bundle.d.ts CHANGED
@@ -15,6 +15,7 @@ declare namespace wsc {
15
15
  }
16
16
  type AsyncErrCode = Promise<number | null | {}>;
17
17
  type EventHandler = (e: any) => void;
18
+ type Predicate = (data: any) => boolean;
18
19
  type DataPipe = (message: any) => any;
19
20
  type DataType = "json" | "string";
20
21
  interface Config {
@@ -80,10 +81,18 @@ export declare class WebSocketClient {
80
81
  private connect;
81
82
  get socket(): wsc.Socket | null;
82
83
  ready(): Promise<void>;
83
- on(event_name: wsc.WSEvent, handler: (data: any) => any, predicate?: (data: any) => boolean, raw?: boolean): wsc.EventHandler;
84
- off(event_name: wsc.WSEvent, handler: (data: any) => any, raw?: boolean): void;
84
+ on(event_name: wsc.WSEvent, handler: wsc.EventHandler, predicate?: wsc.Predicate, raw?: boolean): wsc.EventHandler;
85
+ off(event_name: wsc.WSEvent, handler: wsc.EventHandler, raw?: boolean): void;
85
86
  close(): wsc.AsyncErrCode;
86
87
  open(): Promise<number | null> | undefined;
88
+ addEventListener(e: wsc.WSEvent, cb: wsc.EventHandler, opts?: {
89
+ predicate?: wsc.Predicate;
90
+ raw?: boolean;
91
+ }): wsc.EventHandler;
92
+ removeEventListener(e: wsc.WSEvent, handler: wsc.EventHandler, opts?: {
93
+ predicate?: wsc.Predicate;
94
+ raw?: boolean;
95
+ }): void;
87
96
  private prepareMessage;
88
97
  /** .send(your_data) wraps request to server with {id: `hash`, data: `actually your data`},
89
98
  returns a Promise that will be rejected after a timeout or
package/dist/bundle.mjs CHANGED
@@ -1 +1 @@
1
- const t=Symbol("Placeholder"),e=e=>{let n=0;for(const s of e)s!==t&&n++;return n},n=(e,n)=>{const s=e.length,i=e.slice(),o=n.length;let r=o,l=0;for(;r&&l<s;l++)i[l]===t&&(i[l]=n[o-r],r--);for(l=s;r;l++,r--)i[l]=n[o-r];return i},s=(t,i,o)=>{const r=t.length-i.length-e(o);if(r<1)return t(...n(i,o));{const e=(...e)=>s(t,n(i,o),e);return e.$args_left=r,e}},i=t=>(...n)=>t.length>e(n)?s(t,[],n):t(...n);function o(e){return function(n,...s){return s.length>0?n===t?(e=>function(n){return n===t?e:e(n)})((t=>e(t,s[0]))):e(n,s[0]):t=>e(n,t)}}function r(t){return i(t)}const l=t=>t.length,c=/^(.*?)(8|16|32|64)(Clamped)?Array$/,a=void 0,u=1/0,h=t=>typeof t,d=t=>null===t,f=t=>"number"==h(t);const p=t=>d(t)||(t=>t===a)(t),g={u:"U",b:"B",n:"N",s:"S",f:"F"},m=Symbol(),y=t=>{const e=h(t);return"object"===e?d(t)?"Null":t.constructor.name:g[e[0]]+e.slice(1)},_=o(((t,e)=>y(e)===t)),w=o(((t,e)=>t===e)),b=o(((t,e)=>{const n=y(t);if(w(n,y(e))&&(w(n,"Object")||w(n,"Array")||(t=>c.test(t))(n))){if(d(t)||d(e))return w(t,e);if(w(t,e))return!0;for(const n of[t,e])for(const s in n)if(!(w(n,e)&&s in t||w(n,t)&&s in e&&b(t[s],e[s])))return!1;return!0}return w(t,e)})),k=o(((t,e)=>(e.push(t),e))),S=r(((t,e,n)=>n.reduce(t,e))),P=o(((t,e)=>{const n=(t=>Array.isArray(t))(e);let s,i;n&&(s=0,i=[]);for(let s in e)t(e[s],s)||(n?i.push(+s):delete e[s]);if(n)for(const t of i)e.splice(t-s++,1);return e})),v=i(((t,e,n,s)=>t(s)?e(s):n(s))),E=(...e)=>(...n)=>{let s,i=!0;for(let o=l(e)-1;o>-1;o--)i?(i=!1,s=e[o](...n)):s=s===t?e[o]():e[o](s);return s},A=o(((t,e)=>e[t])),C=r(((t,e,n)=>n.slice(t,f(e)?e:u))),N=A(0);C(1,u);const $=o(((t,e)=>e.find(t))),j=t=>()=>t,q=o(((t,e)=>(t(e),e))),T=j(!0),W=j(!1),z=o(((t,e)=>e(...t))),O=t=>(...e)=>{const n=t(...e),s=function(t){return"function"===h(t)}(n);return s&&n.$args_left?O(n):(t=>!t)(n)},Q=o(((t,e)=>S(((e,n)=>$((e=>t(n,e)),e)?e:k(n,e)),[],e)));Q(b);const R=t=>{let e,n=!1;return function(...s){return n?e:(n=!0,e=t(...s))}},x=(t,e,n)=>l(e)?p(n)?t:E((s=>s in n?x(t,C(1,u,e),n[s]):t),N)(e):n,B=r(x);B(a),E(v(b(m),W,T),B(m));const I=r(((t,e,n)=>e(n)&&t(n))),M=O,D=Symbol("Placeholder"),L=t=>{let e=0;for(const n of t)n!==D&&e++;return e},U=(t,e)=>{const n=t.length,s=t.slice(),i=e.length;let o=i,r=0;for(;o&&r<n;r++)s[r]===D&&(s[r]=e[i-o],o--);for(r=n;o;r++,o--)s[r]=e[i-o];return s},F=(t,e,n)=>{const s=t.length-e.length-L(n);if(s<1)return t(...U(e,n));{const i=(...s)=>F(t,U(e,n),s);return i.$args_left=s,i}},J=t=>(...e)=>t.length>L(e)?F(t,[],e):t(...e);function G(t){return function(e,...n){return n.length>0?e===D?(t=>function(e){return e===D?t:t(e)})((e=>t(e,n[0]))):t(e,n[0]):n=>t(e,n)}}function H(t){return J(t)}const K=t=>t.length,V=/^(.*?)(8|16|32|64)(Clamped)?Array$/,X=void 0,Y=1/0,Z=t=>typeof t,tt=t=>null===t,et={u:"U",b:"B",n:"N",s:"S",f:"F"},nt=Symbol(),st=t=>{const e=Z(t);return"object"===e?tt(t)?"Null":t.constructor.name:et[e[0]]+e.slice(1)},it=G(((t,e)=>st(e)===t)),ot=G(((t,e)=>t===e)),rt=G(((t,e)=>{const n=st(t);if(ot(n,st(e))&&(ot(n,"Object")||ot(n,"Array")||(s=n,V.test(s)))){if(tt(t)||tt(e))return ot(t,e);if(ot(t,e))return!0;for(const n of[t,e])for(const s in n)if(!(ot(n,e)&&s in t||ot(n,t)&&s in e&&rt(t[s],e[s])))return!1;return!0}var s;return ot(t,e)})),lt=G(((t,e)=>(e.push(t),e))),ct=H(((t,e,n)=>n.reduce(t,e))),at=J(((t,e,n,s)=>t(s)?e(s):n(s))),ut=H(((t,e,n)=>at(t,e,yt,n))),ht=(...t)=>(...e)=>{let n,s=!0;for(let i=K(t)-1;i>-1;i--)s?(s=!1,n=t[i](...e)):n=n===D?t[i]():t[i](n);return n},dt=G(((t,e)=>e[t])),ft=H(((t,e,n)=>n.slice(t,(t=>"number"==Z(t))(e)?e:Y))),pt=dt(0);ft(1,Y);const gt=G(((t,e)=>e.find(t))),mt=t=>()=>t,yt=t=>t,_t=G(((t,e)=>e.split(t))),wt=mt(!0),bt=mt(!1),kt=G(((t,e)=>ct(((e,n)=>gt((e=>t(n,e)),e)?e:lt(n,e)),[],e)))(rt),St=(t,e,n)=>K(e)?(t=>tt(t)||(t=>t===X)(t))(n)?t:ht((s=>s in n?St(t,ft(1,Y,e),n[s]):t),pt)(e):n,Pt=H(St);Pt(X),ht(at(rt(nt),bt,wt),Pt(nt));const vt=G(((t,e)=>e.map(t))),{floor:Et}=Math,At="0123456789abcdefghijklmnopqrstuvwxyz",Ct=it("String"),Nt=ut(Ct,_t("")),$t=ht((t=>Object.fromEntries(t)),vt(((t,e)=>[t,e])),Nt);class jt{is_str;delim;abc;abclen;c2pos;standard;setABC(t,e=""){if(this.is_str=Ct(t),this.delim=e,!ht(ot(K(n=t)),K,kt,Nt)(n))throw new Error("Not all chars are unique!");var n;this.abc=t,this.abclen=K(t),this.standard=!!this.is_str&&At.startsWith(t),this.c2pos=$t(t)}zip(t){const{abc:e,abclen:n,delim:s}=this;let i="",o=!0;for(;t>0;)i=e[t%n]+(o?"":s)+i,t=Et(t/n),o=!1;return i||"0"}unzip(t){const{standard:e,abclen:n,c2pos:s,delim:i,is_str:o}=this;if("0"===t)return 0;if(e)return parseInt(t,n);const r=o?t:t.split(i),l=K(r);let c=0;for(let t=0;t<l;t++)c+=s[r[t]]*n**(l-t-1);return c}constructor(t,e){e?this.setABC(t,e):this.setABC(t||At+"ABCDEFGHIJKLMNOPQRSTUVWXYZ")}}const qt=new jt;qt.setABC.bind(qt),qt.zip.bind(qt),qt.unzip.bind(qt);const Tt=(()=>{try{return WebSocket||null}catch{return null}})(),Wt=(t,e,n)=>t.addEventListener(e,n),zt=(t,e)=>setTimeout(e,t),Ot={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,reconnection_attempts:1/0,max_idle_time:1/0,lazy:!1,socket:null,adapter:(t,e)=>new WebSocket(t,e),encode:(t,e,{server:n})=>JSON.stringify({[n.id_key]:t,[n.data_key]:e}),decode:t=>JSON.parse(t),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"},ping:{interval:55,content:{}}},{random:Qt}=Math,Rt=new jt,xt=z([]),Bt=I(_("Number"),M(isNaN)),It={_is_ping:!0},Mt=t=>t&&clearTimeout(t),Dt=t=>{const e=Rt.zip(2147483637*Qt()|0);return e in t?Dt(t):e};class Lt{ws=null;intentionally_closed=!1;reconnect_timeout=null;queue={};onReadyQueue=[];onCloseQueue=[];handlers={open:[],close:[],message:[],error:[],timeout:[]};config={};ping_timer=null;idle_timer=null;get opened(){return 1===this.ws?.readyState}init_flush(){P(W,this.queue)}call(t,...e){for(const n of this.handlers[t])n(...e)}log(t,e=null,n=null){const{config:s}=this;setTimeout((()=>{null===n?s.timer?s.log(t,null,e):s.log(t,e):s.log(t,n,e)}))}resetPing(){const{config:{ping:t},ping_timer:e}=this;t&&(p(e)||clearTimeout(e),this.ping_timer=zt(1e3*t.interval,(async()=>{const{ping_timer:e,opened:n}=this;n?(await this.send(t.content,It),this.resetPing()):clearTimeout(e)})))}resetIdle(){const{config:{max_idle_time:t},idle_timer:e}=this;t!==1/0&&(p(e)||clearTimeout(e),this.idle_timer=zt(1e3*t,(()=>this.opened&&this.close())))}initSocket(t){const{queue:e,config:n}=this;this.ws=t,this.onReadyQueue.forEach((t=>t())),this.onReadyQueue.splice(0);const{id_key:s,data_key:i}=n.server;this.call("open",t);for(const n in e)t.send(e[n].msg);null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),this.resetPing(),this.resetIdle(),Wt(t,"close",(async(...t)=>{this.ws=null,this.onCloseQueue.forEach(xt),this.onCloseQueue.splice(0),this.call("close",...t);let{reconnect:e,reconnection_attempts:s}=n;if(Bt(e)){const t=async()=>{if(this.intentionally_closed||!s)return;s--,this.log("reconnect"),p(this.ws)||(this.ws.close(),this.ws=null);const n=await this.connect();p(n)||(this.reconnect_timeout=setTimeout(t,1e3*e))};t()}})),Wt(t,"message",(t=>{try{const e=n.decode(t.data);this.call("message",{...t,data:e});let o=!1;if(_("Object",e)&&s in e){const t=this.queue[e[s]];if(t){const n=t.sent_time?Date.now()-t.sent_time:null;this.log("message",e[i],n),t.ff(e[i]),o=!0}}o||this.log("message-ext",e)}catch(e){console.error(e,`WSP: Decode error. Got: ${t.data}`)}this.resetPing()}))}opening=!1;connect(){return new Promise((t=>{if(this.opened||this.opening)return t(null);this.opening=!0;const e=this.config,n=e.socket||e.adapter(e.url,e.protocols);if(!n||n.readyState>1)return this.opening=!1,this.ws=null,this.log("error","ready() on closing or closed state! status 2."),t(2);const s=R((e=>{this.opening=!1,t(e)}));Wt(n,"error",R((t=>{this.ws=null,this.log("error","status 3. Err: "+t.message),this.call("error",t),s(3)}))),n.readyState?(this.initSocket(n),s(null)):Wt(n,"open",R((()=>{this.log("open"),this.initSocket(n),s(null)})))}))}get socket(){return this.ws}async ready(){return new Promise((t=>{this.config.lazy||this.opened?t():this.onReadyQueue.push(t)}))}on(t,e,n=T,s=!1){const i=t=>n(t)&&e(t);return s?Wt(this.ws,t,i):this.handlers[t].push(i),i}off(t,e,n=!1){if(n)return((t,e,n)=>t.removeEventListener(e,n))(this.ws,t,e);const s=this.handlers[t],i=s.indexOf(e);~i&&s.splice(i,1)}async close(){return new Promise(((t,e)=>{null===this.ws?e("WSP: closing a non-inited socket!"):(this.onCloseQueue.push((()=>{this.init_flush(),t(null)})),this.ws.close(),this.ws=null,this.intentionally_closed=!0)}))}open(){if(!this.opened)return this.intentionally_closed=!1,this.connect()}async prepareMessage(t,e={}){this.log(e._is_ping?"ping":"send",t);const{config:n,queue:s}=this,{pipes:i,server:{data_key:o}}=n,{top:r,_is_ping:l}=e,c=Dt(s);if("object"==typeof r&&r[o])throw new Error(`Attempting to set data key/token via ${e._is_ping?"ping":"send"}() options!`);for(const e of i)t=e(t);const[a,u]=await Promise.all([n.encode(c,t,n),this.connect()]);if(u)throw new Error("ERR while opening connection #"+u);const h=q((()=>delete this.queue[c]));return this.opened&&(zt(0,(()=>this.ws.send(a))),this.resetPing(),l||this.resetIdle()),{id:c,msg:a,timeout:e=>zt(n.timeout,(()=>{c in s&&(this.call("timeout",t),e({"Websocket timeout expired":n.timeout,"for the message":t}),h())})),cleanup:h}}async send(t,e={}){const{id:n,msg:s,timeout:i,cleanup:o}=await this.prepareMessage(t,e),{queue:r,config:l}=this;return new Promise(((t,e)=>{const o=i(e);r[n]={msg:s,data_type:l.data_type,sent_time:l.timer?Date.now():null,ff(e){Mt(o),t(e)}}})).finally(o)}async*stream(t,e={}){const{id:n,msg:s,timeout:i,cleanup:o}=await this.prepareMessage(t,e),{queue:r,config:l}=this;let c,a=!1,u=null;for(r[n]={msg:s,ff:t=>{t?.done&&(delete t.done,a=!0,setTimeout(o)),c(t)},data_type:l.data_type,sent_time:l.timer?Date.now():null};!a;)yield await new Promise(((t,e)=>{u=i(e),c=t})).catch((t=>o(t))).finally((()=>{Mt(u),u=null}))}constructor(t={}){this.config=(t=>{if(null===Tt&&!("adapter"in t))throw new Error("\n This platform has no native WebSocket implementation.\n Please use 'ws' package as an adapter.\n See https://github.com/houd1ni/WebsocketPromisify/issues/23\n ");const e=Object.assign({},Ot,t),n=e.url;if("/"==n[0])try{const t=location.protocol.includes("s:")?"wss":"ws";e.url=`${t}://${location.hostname}:${location.port}${n}`}catch(t){throw new Error("WSP: URL starting with / in non-browser environment!")}return e})(t),this.config.lazy||this.connect()}}export{Lt as WebSocketClient,Lt as default};
1
+ const t=Symbol("Placeholder"),e=e=>{let n=0;for(const s of e)s!==t&&n++;return n},n=(e,n)=>{const s=e.length,i=e.slice(),o=n.length;let r=o,l=0;for(;r&&l<s;l++)i[l]===t&&(i[l]=n[o-r],r--);for(l=s;r;l++,r--)i[l]=n[o-r];return i},s=(t,i,o)=>{const r=t.length-i.length-e(o);if(r<1)return t(...n(i,o));{const e=(...e)=>s(t,n(i,o),e);return e.$args_left=r,e}},i=t=>(...n)=>t.length>e(n)?s(t,[],n):t(...n);function o(e){return function(n,...s){return s.length>0?n===t?(e=>function(n){return n===t?e:e(n)})((t=>e(t,s[0]))):e(n,s[0]):t=>e(n,t)}}function r(t){return i(t)}const l=t=>t.length,c=/^(.*?)(8|16|32|64)(Clamped)?Array$/,a=void 0,u=1/0,h=t=>typeof t,d=t=>null===t,f=t=>"number"==h(t);const p=t=>d(t)||(t=>t===a)(t),g={u:"U",b:"B",n:"N",s:"S",f:"F"},m=Symbol(),y=t=>{const e=h(t);return"object"===e?d(t)?"Null":t.constructor.name:g[e[0]]+e.slice(1)},_=o(((t,e)=>y(e)===t)),w=o(((t,e)=>t===e)),b=o(((t,e)=>{const n=y(t);if(w(n,y(e))&&(w(n,"Object")||w(n,"Array")||(t=>c.test(t))(n))){if(d(t)||d(e))return w(t,e);if(w(t,e))return!0;for(const n of[t,e])for(const s in n)if(!(w(n,e)&&s in t||w(n,t)&&s in e&&b(t[s],e[s])))return!1;return!0}return w(t,e)})),k=o(((t,e)=>(e.push(t),e))),S=r(((t,e,n)=>n.reduce(t,e))),v=o(((t,e)=>{const n=(t=>Array.isArray(t))(e);let s,i;n&&(s=0,i=[]);for(let s in e)t(e[s],s)||(n?i.push(+s):delete e[s]);if(n)for(const t of i)e.splice(t-s++,1);return e})),P=i(((t,e,n,s)=>t(s)?e(s):n(s))),E=(...e)=>(...n)=>{let s,i=!0;for(let o=l(e)-1;o>-1;o--)i?(i=!1,s=e[o](...n)):s=s===t?e[o]():e[o](s);return s},A=o(((t,e)=>e[t])),C=r(((t,e,n)=>n.slice(t,f(e)?e:u))),N=A(0);C(1,u);const $=o(((t,e)=>e.find(t))),j=t=>()=>t,q=o(((t,e)=>(t(e),e))),T=j(!0),W=j(!1),z=o(((t,e)=>e(...t))),O=t=>(...e)=>{const n=t(...e),s=function(t){return"function"===h(t)}(n);return s&&n.$args_left?O(n):(t=>!t)(n)},Q=o(((t,e)=>S(((e,n)=>$((e=>t(n,e)),e)?e:k(n,e)),[],e)));Q(b);const R=t=>{let e,n=!1;return function(...s){return n?e:(n=!0,e=t(...s))}},x=(t,e,n)=>l(e)?p(n)?t:E((s=>s in n?x(t,C(1,u,e),n[s]):t),N)(e):n,B=r(x);B(a),E(P(b(m),W,T),B(m));const I=r(((t,e,n)=>e(n)&&t(n))),L=O,M=Symbol("Placeholder"),D=t=>{let e=0;for(const n of t)n!==M&&e++;return e},U=(t,e)=>{const n=t.length,s=t.slice(),i=e.length;let o=i,r=0;for(;o&&r<n;r++)s[r]===M&&(s[r]=e[i-o],o--);for(r=n;o;r++,o--)s[r]=e[i-o];return s},F=(t,e,n)=>{const s=t.length-e.length-D(n);if(s<1)return t(...U(e,n));{const i=(...s)=>F(t,U(e,n),s);return i.$args_left=s,i}},J=t=>(...e)=>t.length>D(e)?F(t,[],e):t(...e);function G(t){return function(e,...n){return n.length>0?e===M?(t=>function(e){return e===M?t:t(e)})((e=>t(e,n[0]))):t(e,n[0]):n=>t(e,n)}}function H(t){return J(t)}const K=t=>t.length,V=/^(.*?)(8|16|32|64)(Clamped)?Array$/,X=void 0,Y=1/0,Z=t=>typeof t,tt=t=>null===t,et={u:"U",b:"B",n:"N",s:"S",f:"F"},nt=Symbol(),st=t=>{const e=Z(t);return"object"===e?tt(t)?"Null":t.constructor.name:et[e[0]]+e.slice(1)},it=G(((t,e)=>st(e)===t)),ot=G(((t,e)=>t===e)),rt=G(((t,e)=>{const n=st(t);if(ot(n,st(e))&&(ot(n,"Object")||ot(n,"Array")||(s=n,V.test(s)))){if(tt(t)||tt(e))return ot(t,e);if(ot(t,e))return!0;for(const n of[t,e])for(const s in n)if(!(ot(n,e)&&s in t||ot(n,t)&&s in e&&rt(t[s],e[s])))return!1;return!0}var s;return ot(t,e)})),lt=G(((t,e)=>(e.push(t),e))),ct=H(((t,e,n)=>n.reduce(t,e))),at=J(((t,e,n,s)=>t(s)?e(s):n(s))),ut=H(((t,e,n)=>at(t,e,yt,n))),ht=(...t)=>(...e)=>{let n,s=!0;for(let i=K(t)-1;i>-1;i--)s?(s=!1,n=t[i](...e)):n=n===M?t[i]():t[i](n);return n},dt=G(((t,e)=>e[t])),ft=H(((t,e,n)=>n.slice(t,(t=>"number"==Z(t))(e)?e:Y))),pt=dt(0);ft(1,Y);const gt=G(((t,e)=>e.find(t))),mt=t=>()=>t,yt=t=>t,_t=G(((t,e)=>e.split(t))),wt=mt(!0),bt=mt(!1),kt=G(((t,e)=>ct(((e,n)=>gt((e=>t(n,e)),e)?e:lt(n,e)),[],e)))(rt),St=(t,e,n)=>K(e)?(t=>tt(t)||(t=>t===X)(t))(n)?t:ht((s=>s in n?St(t,ft(1,Y,e),n[s]):t),pt)(e):n,vt=H(St);vt(X),ht(at(rt(nt),bt,wt),vt(nt));const Pt=G(((t,e)=>e.map(t))),{floor:Et}=Math,At="0123456789abcdefghijklmnopqrstuvwxyz",Ct=it("String"),Nt=ut(Ct,_t("")),$t=ht((t=>Object.fromEntries(t)),Pt(((t,e)=>[t,e])),Nt);class jt{is_str;delim;abc;abclen;c2pos;standard;setABC(t,e=""){if(this.is_str=Ct(t),this.delim=e,!ht(ot(K(n=t)),K,kt,Nt)(n))throw new Error("Not all chars are unique!");var n;this.abc=t,this.abclen=K(t),this.standard=!!this.is_str&&At.startsWith(t),this.c2pos=$t(t)}zip(t){const{abc:e,abclen:n,delim:s}=this;let i="",o=!0;for(;t>0;)i=e[t%n]+(o?"":s)+i,t=Et(t/n),o=!1;return i||"0"}unzip(t){const{standard:e,abclen:n,c2pos:s,delim:i,is_str:o}=this;if("0"===t)return 0;if(e)return parseInt(t,n);const r=o?t:t.split(i),l=K(r);let c=0;for(let t=0;t<l;t++)c+=s[r[t]]*n**(l-t-1);return c}constructor(t,e){e?this.setABC(t,e):this.setABC(t||At+"ABCDEFGHIJKLMNOPQRSTUVWXYZ")}}const qt=new jt;qt.setABC.bind(qt),qt.zip.bind(qt),qt.unzip.bind(qt);const Tt=(()=>{try{return WebSocket||null}catch{return null}})(),Wt=(t,e,n)=>t.addEventListener(e,n),zt=(t,e)=>setTimeout(e,t),Ot={data_type:"json",log:()=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,reconnection_attempts:1/0,max_idle_time:1/0,lazy:!1,socket:null,adapter:(t,e)=>new WebSocket(t,e),encode:(t,e,{server:n})=>JSON.stringify({[n.id_key]:t,[n.data_key]:e}),decode:t=>JSON.parse(t),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"},ping:{interval:55,content:{}}},{random:Qt}=Math,Rt=new jt,xt=z([]),Bt=I(_("Number"),L(isNaN)),It={_is_ping:!0},Lt=t=>t&&clearTimeout(t),Mt=t=>{const e=Rt.zip(2147483637*Qt()|0);return e in t?Mt(t):e};class Dt{ws=null;intentionally_closed=!1;reconnect_timeout=null;queue={};onReadyQueue=[];onCloseQueue=[];handlers={open:[],close:[],message:[],error:[],timeout:[]};config={};ping_timer=null;idle_timer=null;get opened(){return 1===this.ws?.readyState}init_flush(){v(W,this.queue)}call(t,...e){for(const n of this.handlers[t])n(...e)}log(t,e=null,n=null){const{config:s}=this;setTimeout((()=>{null===n?s.timer?s.log(t,null,e):s.log(t,e):s.log(t,n,e)}))}resetPing(){const{config:{ping:t},ping_timer:e}=this;t&&(p(e)||clearTimeout(e),this.ping_timer=zt(1e3*t.interval,(async()=>{const{ping_timer:e,opened:n}=this;n?(await this.send(t.content,It),this.resetPing()):clearTimeout(e)})))}resetIdle(){const{config:{max_idle_time:t},idle_timer:e}=this;t!==1/0&&(p(e)||clearTimeout(e),this.idle_timer=zt(1e3*t,(()=>this.opened&&this.close())))}initSocket(t){const{queue:e,config:n}=this;this.ws=t,this.onReadyQueue.forEach((t=>t())),this.onReadyQueue.splice(0);const{id_key:s,data_key:i}=n.server;this.call("open",t);for(const n in e)t.send(e[n].msg);null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),this.resetPing(),this.resetIdle(),Wt(t,"close",(async(...t)=>{this.ws=null,this.onCloseQueue.forEach(xt),this.onCloseQueue.splice(0),this.call("close",...t);let{reconnect:e,reconnection_attempts:s}=n;if(Bt(e)){const t=async()=>{if(this.intentionally_closed||!s)return;s--,this.log("reconnect"),p(this.ws)||(this.ws.close(),this.ws=null);const n=await this.connect();p(n)||(this.reconnect_timeout=setTimeout(t,1e3*e))};t()}})),Wt(t,"message",(t=>{try{const e=n.decode(t.data);this.call("message",{...t,data:e});let o=!1;if(_("Object",e)&&s in e){const t=this.queue[e[s]];if(t){const n=t.sent_time?Date.now()-t.sent_time:null;this.log("message",e[i],n),t.ff(e[i]),o=!0}}o||this.log("message-ext",e)}catch(e){console.error(e,`WSP: Decode error. Got: ${t.data}`)}this.resetPing()}))}opening=!1;connect(){return new Promise((t=>{if(this.opened||this.opening)return t(null);this.opening=!0;const e=this.config,n=e.socket||e.adapter(e.url,e.protocols);if(!n||n.readyState>1)return this.opening=!1,this.ws=null,this.log("error","ready() on closing or closed state! status 2."),t(2);const s=R((e=>{this.opening=!1,t(e)}));Wt(n,"error",R((t=>{this.ws=null,this.log("error","status 3. Err: "+t.message),this.call("error",t),s(3)}))),n.readyState?(this.initSocket(n),s(null)):Wt(n,"open",R((()=>{this.log("open"),this.initSocket(n),s(null)})))}))}get socket(){return this.ws}async ready(){return new Promise((t=>{this.config.lazy||this.opened?t():this.onReadyQueue.push(t)}))}on(t,e,n=T,s=!1){const i=t=>n(t)&&e(t);return s?Wt(this.ws,t,i):this.handlers[t].push(i),i}off(t,e,n=!1){if(n)return((t,e,n)=>t.removeEventListener(e,n))(this.ws,t,e);const s=this.handlers[t],i=s.indexOf(e);~i&&s.splice(i,1)}async close(){return new Promise(((t,e)=>{null===this.ws?e("WSP: closing a non-inited socket!"):(this.onCloseQueue.push((()=>{this.init_flush(),t(null)})),this.ws.close(),this.ws=null,this.intentionally_closed=!0)}))}open(){if(!this.opened)return this.intentionally_closed=!1,this.connect()}addEventListener(t,e,n={}){return this.on(t,e,n.predicate,n.raw)}removeEventListener(t,e,n={}){return this.off(t,e,n.raw)}async prepareMessage(t,e={}){this.log(e._is_ping?"ping":"send",t);const{config:n,queue:s}=this,{pipes:i,server:{data_key:o}}=n,{top:r,_is_ping:l}=e,c=Mt(s);if("object"==typeof r&&r[o])throw new Error(`Attempting to set data key/token via ${e._is_ping?"ping":"send"}() options!`);for(const e of i)t=e(t);const[a,u]=await Promise.all([n.encode(c,t,n),this.connect()]);if(u)throw new Error("ERR while opening connection #"+u);const h=q((()=>delete this.queue[c]));return{id:c,msg:a,timeout:e=>zt(n.timeout,(()=>{c in s&&(this.call("timeout",t),e({"Websocket timeout expired":n.timeout,"for the message":t}),h())})),cleanup:h,send:()=>this.opened&&(this.ws.send(a),this.resetPing(),!l&&this.resetIdle())}}async send(t,e={}){const{id:n,msg:s,timeout:i,cleanup:o,send:r}=await this.prepareMessage(t,e),{queue:l,config:c}=this;return new Promise(((t,e)=>{const o=i(e);l[n]={msg:s,data_type:c.data_type,sent_time:c.timer?Date.now():null,ff(e){Lt(o),t(e)}},r()})).finally(o)}async*stream(t,e={}){const{id:n,msg:s,timeout:i,cleanup:o,send:r}=await this.prepareMessage(t,e),{queue:l,config:c}=this;let a,u=!1,h=null;for(l[n]={msg:s,ff:t=>{t?.done&&(delete t.done,u=!0,setTimeout(o)),a(t)},data_type:c.data_type,sent_time:c.timer?Date.now():null},r();!u;)yield await new Promise(((t,e)=>{h=i(e),a=t})).catch((t=>o(t))).finally((()=>{Lt(h),h=null}))}constructor(t={}){this.config=(t=>{if(null===Tt&&!("adapter"in t))throw new Error("\n This platform has no native WebSocket implementation.\n Please use 'ws' package as an adapter.\n See https://github.com/houd1ni/WebsocketPromisify/issues/23\n ");const e=Object.assign({},Ot,t),n=e.url;if("/"==n[0])try{const t=location.protocol.includes("s:")?"wss":"ws";e.url=`${t}://${location.hostname}:${location.port}${n}`}catch(t){throw new Error("WSP: URL starting with / in non-browser environment!")}return e})(t),this.config.lazy||this.connect()}}export{Dt as WebSocketClient,Dt as default};
package/package.json CHANGED
@@ -41,7 +41,7 @@
41
41
  "prod": "npm run gentypes && npm run prod:es && npm run prod:cjs",
42
42
  "all": "npm run dev && npm run prod"
43
43
  },
44
- "version": "2.10.1",
44
+ "version": "2.11.2",
45
45
  "type": "module",
46
46
  "exports": {
47
47
  ".": {
package/TODO DELETED
@@ -1,9 +0,0 @@
1
- #v3 at least:
2
-
3
- [The milestone](https://github.com/houd1ni/WebsocketPromisify/milestone/1)
4
-
5
- - [x] [close event bug](https://github.com/houd1ni/WebsocketPromisify/issues/38) (fixed in 2.5.0)
6
- - [ ] [BREAKING] export named WebSocketClient instead of default export.
7
- - [ ] [ping-pong without id](https://github.com/houd1ni/WebsocketPromisify/issues/39)
8
- - [ ] [implement prepare](https://github.com/houd1ni/WebsocketPromisify/issues/34)
9
- - [ ] [wiki](https://github.com/houd1ni/WebsocketPromisify/issues/4)
package/coverage.lcov DELETED
@@ -1,212 +0,0 @@
1
- TN:
2
- SF:C:\Users\pinke\Documents\WebsocketPromisify\rollup.config.js
3
- FN:3,_interopDefault
4
- FNF:1
5
- FNH:1
6
- FNDA:3,_interopDefault
7
- DA:3,3
8
- DA:5,1
9
- DA:6,1
10
- DA:7,1
11
- DA:8,1
12
- DA:9,1
13
- DA:11,1
14
- DA:36,1
15
- LF:8
16
- LH:8
17
- BRDA:3,0,0,0
18
- BRDA:3,0,1,3
19
- BRDA:3,1,0,3
20
- BRDA:3,1,1,3
21
- BRDA:3,1,2,0
22
- BRDA:14,2,0,1
23
- BRDA:14,2,1,0
24
- BRDA:15,3,0,1
25
- BRDA:15,3,1,0
26
- BRF:9
27
- BRH:5
28
- end_of_record
29
- TN:
30
- SF:C:\Users\pinke\Documents\WebsocketPromisify\dist\ws.js
31
- FN:1,__awaiter
32
- FN:1,(anonymous_1)
33
- FN:1,r
34
- FN:1,c
35
- FN:1,l
36
- FN:1,(anonymous_5)
37
- FN:1,(anonymous_6)
38
- FN:1,(anonymous_7)
39
- FN:1,(anonymous_8)
40
- FN:1,(anonymous_9)
41
- FN:1,(anonymous_10)
42
- FN:1,(anonymous_11)
43
- FN:1,(anonymous_12)
44
- FN:1,(anonymous_13)
45
- FN:1,(anonymous_14)
46
- FN:1,(anonymous_15)
47
- FN:1,(anonymous_16)
48
- FN:1,(anonymous_17)
49
- FN:1,(anonymous_18)
50
- FN:1,(anonymous_19)
51
- FN:1,(anonymous_20)
52
- FN:1,(anonymous_21)
53
- FN:1,(anonymous_22)
54
- FN:1,(anonymous_23)
55
- FN:1,(anonymous_24)
56
- FN:1,(anonymous_25)
57
- FN:1,(anonymous_26)
58
- FN:1,(anonymous_27)
59
- FN:1,(anonymous_28)
60
- FN:1,(anonymous_29)
61
- FN:1,(anonymous_30)
62
- FN:1,(anonymous_31)
63
- FN:1,(anonymous_32)
64
- FN:1,(anonymous_33)
65
- FN:1,(anonymous_34)
66
- FN:1,(anonymous_35)
67
- FN:1,(anonymous_36)
68
- FN:1,(anonymous_37)
69
- FN:1,(anonymous_38)
70
- FN:1,(anonymous_39)
71
- FN:1,(anonymous_40)
72
- FN:1,(anonymous_41)
73
- FN:1,(anonymous_42)
74
- FN:1,(anonymous_43)
75
- FN:1,(anonymous_44)
76
- FN:1,(anonymous_45)
77
- FN:1,(anonymous_46)
78
- FN:1,(anonymous_47)
79
- FN:1,(anonymous_48)
80
- FN:1,(anonymous_49)
81
- FNF:50
82
- FNH:45
83
- FNDA:40,__awaiter
84
- FNDA:40,(anonymous_1)
85
- FNDA:2,r
86
- FNDA:0,c
87
- FNDA:42,l
88
- FNDA:5,(anonymous_5)
89
- FNDA:7,(anonymous_6)
90
- FNDA:51,(anonymous_7)
91
- FNDA:29,(anonymous_8)
92
- FNDA:11,(anonymous_9)
93
- FNDA:7,(anonymous_10)
94
- FNDA:11,(anonymous_11)
95
- FNDA:3,(anonymous_12)
96
- FNDA:3,(anonymous_13)
97
- FNDA:7,(anonymous_14)
98
- FNDA:7,(anonymous_15)
99
- FNDA:3,(anonymous_16)
100
- FNDA:5,(anonymous_17)
101
- FNDA:5,(anonymous_18)
102
- FNDA:6,(anonymous_19)
103
- FNDA:15,(anonymous_20)
104
- FNDA:1,(anonymous_21)
105
- FNDA:10,(anonymous_22)
106
- FNDA:36,(anonymous_23)
107
- FNDA:0,(anonymous_24)
108
- FNDA:6,(anonymous_25)
109
- FNDA:6,(anonymous_26)
110
- FNDA:10,(anonymous_27)
111
- FNDA:10,(anonymous_28)
112
- FNDA:13,(anonymous_29)
113
- FNDA:36,(anonymous_30)
114
- FNDA:15,(anonymous_31)
115
- FNDA:15,(anonymous_32)
116
- FNDA:15,(anonymous_33)
117
- FNDA:9,(anonymous_34)
118
- FNDA:3,(anonymous_35)
119
- FNDA:3,(anonymous_36)
120
- FNDA:3,(anonymous_37)
121
- FNDA:0,(anonymous_38)
122
- FNDA:0,(anonymous_39)
123
- FNDA:3,(anonymous_40)
124
- FNDA:3,(anonymous_41)
125
- FNDA:3,(anonymous_42)
126
- FNDA:3,(anonymous_43)
127
- FNDA:7,(anonymous_44)
128
- FNDA:7,(anonymous_45)
129
- FNDA:0,(anonymous_46)
130
- FNDA:3,(anonymous_47)
131
- FNDA:7,(anonymous_48)
132
- FNDA:1,(anonymous_49)
133
- DA:1,51
134
- LF:1
135
- LH:1
136
- BRDA:1,0,0,40
137
- BRDA:1,0,1,40
138
- BRDA:1,1,0,37
139
- BRDA:1,1,1,5
140
- BRDA:1,2,0,40
141
- BRDA:1,2,1,40
142
- BRDA:1,3,0,0
143
- BRDA:1,3,1,11
144
- BRDA:1,4,0,11
145
- BRDA:1,4,1,1
146
- BRDA:1,5,0,3
147
- BRDA:1,5,1,4
148
- BRDA:1,6,0,7
149
- BRDA:1,6,1,7
150
- BRDA:1,6,2,7
151
- BRDA:1,7,0,5
152
- BRDA:1,7,1,4
153
- BRDA:1,8,0,5
154
- BRDA:1,8,1,1
155
- BRDA:1,9,0,6
156
- BRDA:1,9,1,0
157
- BRDA:1,10,0,6
158
- BRDA:1,10,1,0
159
- BRDA:1,11,0,0
160
- BRDA:1,11,1,6
161
- BRDA:1,12,0,0
162
- BRDA:1,12,1,15
163
- BRDA:1,13,0,15
164
- BRDA:1,13,1,13
165
- BRDA:1,14,0,0
166
- BRDA:1,14,1,15
167
- BRDA:1,15,0,15
168
- BRDA:1,15,1,15
169
- BRDA:1,16,0,1
170
- BRDA:1,16,1,14
171
- BRDA:1,17,0,0
172
- BRDA:1,17,1,10
173
- BRDA:1,18,0,0
174
- BRDA:1,19,0,10
175
- BRDA:1,19,1,8
176
- BRDA:1,20,0,23
177
- BRDA:1,21,0,30
178
- BRDA:1,22,0,0
179
- BRDA:1,22,1,36
180
- BRDA:1,23,0,0
181
- BRDA:1,23,1,36
182
- BRDA:1,24,0,0
183
- BRDA:1,24,1,3
184
- BRDA:1,25,0,0
185
- BRDA:1,25,1,0
186
- BRDA:1,25,2,0
187
- BRDA:1,26,0,0
188
- BRDA:1,26,1,3
189
- BRDA:1,27,0,7
190
- BRDA:1,28,0,7
191
- BRDA:1,28,1,2
192
- BRDA:1,29,0,0
193
- BRDA:1,29,1,7
194
- BRDA:1,30,0,0
195
- BRDA:1,30,1,0
196
- BRDA:1,31,0,3
197
- BRDA:1,31,1,4
198
- BRDA:1,32,0,4
199
- BRDA:1,32,1,0
200
- BRDA:1,33,0,4
201
- BRDA:1,33,1,0
202
- BRDA:1,34,0,4
203
- BRDA:1,34,1,2
204
- BRDA:1,35,0,0
205
- BRDA:1,35,1,0
206
- BRDA:1,36,0,0
207
- BRDA:1,36,1,7
208
- BRDA:1,37,0,1
209
- BRDA:1,37,1,1
210
- BRF:74
211
- BRH:51
212
- end_of_record
package/rollup.config.js DELETED
@@ -1,38 +0,0 @@
1
- import commonjs from '@rollup/plugin-commonjs'
2
- import resolve from '@rollup/plugin-node-resolve'
3
- import replace from '@rollup/plugin-replace'
4
- import terser from '@rollup/plugin-terser'
5
- import typescript from 'rollup-plugin-typescript2'
6
- import tsc from 'typescript'
7
-
8
- export default {
9
- input: 'src/WSC.ts',
10
- output: {
11
- file: process.env.NODE_ENV=='development'
12
- ? 'dist/bundle.dev.js'
13
- : process.env.BUILD == 'cjs' ? 'dist/bundle.cjs' : 'dist/bundle.mjs',
14
- format: process.env.BUILD == 'cjs' ? 'cjs' : 'es',
15
- name: 'wspromisify'
16
- },
17
- treeshake: { moduleSideEffects: false },
18
- plugins: [
19
- resolve(),
20
- commonjs(),
21
- typescript({
22
- typescript: tsc,
23
- tsconfig: "./tsconfig.json",
24
- tsconfigOverride: {
25
- compilerOptions: {
26
- sourceMap: false,
27
- inlineSourceMap: process.env.NODE_ENV=='development',
28
- module: 'esnext'
29
- }
30
- }
31
- }),
32
- process.env.NODE_ENV!='development' && terser(),
33
- replace({
34
- preventAssignment: true,
35
- values: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }
36
- })
37
- ]
38
- }